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 |
|---|---|---|---|---|---|---|---|---|
// Generated by Selenium IDE
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using NUnit.Framework;
[TestFixture]
public class AlteraImovelValidoTest {
private IWebDriver driver;
public IDictionary<string, object> vars {get; private set;}
private IJavaScriptExecutor js;
[SetUp]
public void SetUp() {
driver = new ChromeDriver();
js = (IJavaScriptExecutor)driver;
vars = new Dictionary<string, object>();
}
[TearDown]
protected void TearDown() {
driver.Quit();
}
[Test]
public void alteraImovelValido() {
driver.Navigate().GoToUrl("https://localhost:3001/");
driver.Manage().Window.Size = new System.Drawing.Size(839, 1050);
driver.FindElement(By.LinkText("Entrar ou Cadastrar")).Click();
driver.FindElement(By.LinkText("Meus Imoveis")).Click();
driver.FindElement(By.CssSelector("tr:nth-child(1) .far")).Click();
driver.FindElement(By.Id("wrapper")).Click();
driver.FindElement(By.Id("ValorDoAluguel")).SendKeys("350");
driver.FindElement(By.Id("ValorDoAluguel")).SendKeys(Keys.Enter);
}
}
| 32.097561 | 71 | 0.730243 | [
"MIT"
] | marcosdosea/Alugai | Teste/AlterarImovelValidoTest.cs | 1,316 | C# |
using Unity.Mathematics.FixedPoint;
using UnityEngine;
public class SimulationInput : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit))
{
ApplyForceSystem.Target = hit.point;
}
}
if (Input.GetMouseButton(1))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit))
{
//TODO Explicit conversions
FpApplyForceSystem.Target = new fp3((fp)hit.point.x, (fp)hit.point.y, (fp)hit.point.z);
}
}
}
}
| 20.166667 | 91 | 0.680992 | [
"MIT"
] | danielmansson/Unity.Mathematics.FixedPoint.Example | Assets/Code/SimulationInput.cs | 607 | C# |
namespace MyOnlineShop.Application.Shopping.EventHandlers
{
using MyOnlineShop.Application.Common;
using MyOnlineShop.Domain.Catalog.Events;
using MyOnlineShop.Domain.Shopping.Repositories;
using System.Threading.Tasks;
public class ProductNameUpdatedEventHandler : IEventHandler<ProductNameUpdatedEvent>
{
private readonly IShoppingCartDomainRepository shoppingCartDomainRepository;
public ProductNameUpdatedEventHandler(IShoppingCartDomainRepository shoppingCartDomainRepository)
{
this.shoppingCartDomainRepository = shoppingCartDomainRepository;
}
public async Task Handle(ProductNameUpdatedEvent domainEvent)
{
await this.shoppingCartDomainRepository
.UpdateCartItemsWithProductName(domainEvent.ProductId, domainEvent.ProductName);
}
}
}
| 36.541667 | 105 | 0.749145 | [
"MIT"
] | DimchoLakov/MyOnlineShop-Domain-Driven-Design | MyOnlineShop/MyOnlineShop.Application/Shopping/EventHandlers/ProductNameUpdatedEventHandler.cs | 879 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Dolittle.Runtime.Events.Store.Streams.Filters.EventHorizon;
using Machine.Specifications;
namespace Dolittle.Runtime.Events.Store.Streams.for_StreamDefinition;
public class from_public_filter_definition
{
static StreamId source_stream_id;
static StreamId target_stream_id;
static PublicFilterDefinition filter_definition;
static StreamDefinition stream_definition;
Establish context = () =>
{
source_stream_id = Guid.Parse("42890d11-9060-4c1a-91c7-0f81374427c5");
target_stream_id = Guid.Parse("76098767-5fde-4296-9da6-80624fda8592");
filter_definition = new PublicFilterDefinition(source_stream_id, target_stream_id);
};
Because of = () => stream_definition = new StreamDefinition(filter_definition);
It should_be_partitioned = () => stream_definition.Partitioned.ShouldBeTrue();
It should_be_public = () => stream_definition.Public.ShouldBeTrue();
It should_have_the_correct_stream_id = () => stream_definition.StreamId.ShouldEqual(target_stream_id);
It should_have_the_correct_filter_definition = () => stream_definition.FilterDefinition.ShouldEqual(filter_definition);
} | 44.066667 | 123 | 0.778366 | [
"MIT"
] | dolittle-runtime/Runtime | Specifications/Events.Store/Streams/for_StreamDefinition/when_creating/from_public_filter_definition.cs | 1,322 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using СomponentСompatibilityApp.Models;
namespace СomponentСompatibilityApp
{
public class Startup
{
public IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddRazorRuntimeCompilation();
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ApplicationContext>(c => c.UseSqlServer(connectionString));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
});
}
}
}
| 27.895833 | 93 | 0.666916 | [
"MIT"
] | oleh-dumanskyi/pc-component-check | Startup.cs | 1,343 | C# |
using System.Resources;
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("CLScraper.Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CLScraper.Common")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
| 34.967742 | 83 | 0.74631 | [
"MIT"
] | markjulmar/desktop-to-xamarin | Demos/CLScraper/Updated/CLScraper.Common/Properties/AssemblyInfo.cs | 1,087 | C# |
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Shaders
{
public static class HackMan
{
public static T GetField<T>(this object instance, string fieldname) => (T)AccessTools.Field(instance.GetType(), fieldname).GetValue(instance);
public static FieldInfo GetFieldInfo(this object instance, string fieldname) => AccessTools.Field(instance.GetType(), fieldname);
public static T GetProperty<T>(this object instance, string fieldname) => (T)AccessTools.Property(instance.GetType(), fieldname).GetValue(instance);
public static object CreateInstance(this Type type) => AccessTools.CreateInstance(type);
public static T[] GetFields<T>(this object instance)
{
List<T> fields = new List<T>();
var declaredFields = AccessTools.GetDeclaredFields(instance.GetType())?.Where((t) => t.FieldType == typeof(T));
foreach (var val in declaredFields)
{
fields.Add(instance.GetField<T>(val.Name));
}
return fields.ToArray();
}
public static void SetField(this object instance, string fieldname, object setVal) => AccessTools.Field(instance.GetType(), fieldname).SetValue(instance, setVal);
public static void CallMethod(this object instance, string method) => instance?.CallMethod(method, null);
public static void CallMethod(this object instance, string method, params object[] args) => instance?.CallMethod<object>(method, args);
public static T CallMethod<T>(this object instance, string method) => (T)instance.CallMethod<object>(method, null);
public static T CallMethod<T>(this object instance, string method, params object[] args)
{
Type[] parameters = null;
if (args != null)
{
parameters = args.Length > 0 ? new Type[args.Length] : null;
for (int i = 0; i < args.Length; i++)
{
parameters[i] = args[i].GetType();
}
}
return (T)instance?.GetMethod(method, parameters).Invoke(instance, args);
}
public static MethodInfo GetMethod(this object instance, string method, params Type[] parameters) => instance.GetMethod(method, parameters, null);
public static MethodInfo GetMethod(this object instance, string method, Type[] parameters = null, Type[] generics = null) => AccessTools.Method(instance.GetType(), method, parameters, generics);
}
}
| 51.58 | 202 | 0.652966 | [
"MIT"
] | Novocain1/ShadersMod | src/Util/HackMan.cs | 2,581 | C# |
using System;
using AlphaTest.Application.UseCases.Common;
namespace AlphaTest.Application.UseCases.Examinations.Commands.RevokeAnswer
{
public class RevokeAnswerUseCaseRequest : IUseCaseRequest
{
public RevokeAnswerUseCaseRequest(Guid examinationID, Guid questionID, Guid studentID)
{
ExaminationID = examinationID;
QuestionID = questionID;
StudentID = studentID;
}
public Guid ExaminationID { get; private set; }
public Guid QuestionID { get; private set; }
public Guid StudentID { get; private set; }
}
}
| 26.521739 | 94 | 0.67541 | [
"MIT"
] | Damakshn/AlphaTest | src/AlphaTest.Application/UseCases/Examinations/Commands/RevokeAnswer/RevokeAnswerUseCaseRequest.cs | 612 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace InventoryManager.WPF.UI.ViewModels
{
public class StorableBaseViewModel : BaseViewModel, IStorableViewModel
{
public double GetWeightForContainer()
{
throw new NotImplementedException();
}
public double GetWeightIncludingStrappedItems()
{
throw new NotImplementedException();
}
}
}
| 22.3 | 74 | 0.663677 | [
"MIT"
] | Pat02/InventoryManager | InventoryManager.WPF.UI/ViewModels/StorableBaseViewModel.cs | 448 | 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.
namespace Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10
{
using Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema"
/// />
/// </summary>
public partial class Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchemaTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema"
/// /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema"
/// />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema"
/// />.</param>
/// <returns>
/// an instance of <see cref="Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema"
/// />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.IPaths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.IPaths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 58.723684 | 265 | 0.642841 | [
"MIT"
] | Agazoth/azure-powershell | src/Resources/MSGraph.Autorest/generated/api/Models/ApiV10/Paths1Idoj4GServiceprincipalsServiceprincipalIdMicrosoftGraphRemovepasswordPostRequestbodyContentApplicationJsonSchema.TypeConverter.cs | 8,775 | 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 InnerFrames.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("InnerFrames.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.597222 | 177 | 0.603095 | [
"MIT"
] | CNinnovation/MVVMWorkshopSep2017 | InnerFrames/InnerFrames/Properties/Resources.Designer.cs | 2,781 | C# |
using System.ServiceModel;
namespace Helper
{
[ServiceContract]
public interface IRequestProcessor
{
//should have the same interface as client,server,util,launcher.
[OperationContract(Action = "RequestProcessor.joinNode")]
string joinNode(string nodeSocketAddress);
[OperationContract(Action = "RequestProcessor.signOffNode")]
string signOffNode(int nodeSocketAddress);
[OperationContract(Action = "RequestProcessor.propagateSignOffRequest")]
string propagateSignOffRequest(int nodeID);
[OperationContract(Action = "RequestProcessor.propagateJoinRequest")]
string propagateJoinRequest(string nodeSocketAddress);
[OperationContract(Action = "RequestProcessor.startElection")]
string startElection(string startedIP);
[OperationContract(Action = "RequestProcessor.propagateCoordinatorMessage")]
string propagateCoordinatorMessage(string starterIP);
[OperationContract(Action = "RequestProcessor.showNetworkState")]
string showNetworkState();
}
}
| 36.064516 | 85 | 0.709302 | [
"Apache-2.0"
] | amatanat/Centralized-read-and-write | CentralizedReadWrite/IHelloService/IRequestProcessor.cs | 1,120 | C# |
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace blazor_inlineEditor
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
}
}
}
| 28.692308 | 124 | 0.717158 | [
"MIT"
] | hiiammalte/blazor_InlineEditor | blazor_inlineEditor/Program.cs | 746 | C# |
using System;
using System.Linq.Expressions;
using DNTFrameworkCore.Linq;
namespace DNTFrameworkCore.Specifications
{
/// <summary>
/// Represents the combined specification which indicates that either of the given
/// specification should be satisfied by the given object.
/// </summary>
/// <typeparam name="T">The type of the object to which the specification is applied.</typeparam>
public class OrSpecification<T> : CompositeSpecification<T>
{
/// <summary>
/// Initializes a new instance of <see cref="OrSpecification{T}"/> class.
/// </summary>
/// <param name="left">The first specification.</param>
/// <param name="right">The second specification.</param>
public OrSpecification(Specification<T> left, Specification<T> right) : base(left, right) { }
/// <summary>
/// Gets the LINQ expression which represents the current specification.
/// </summary>
/// <returns>The LINQ expression.</returns>
public override Expression<Func<T, bool>> ToExpression()
{
return Left.ToExpression().Or(Right.ToExpression());
}
}
} | 39.1 | 101 | 0.647911 | [
"Apache-2.0"
] | amir-ashy/DNTFrameworkCore | src/DNTFrameworkCore/Specifications/OrSpecification.cs | 1,173 | C# |
using System.Collections.Generic;
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
static EnemyManager _instance;
static int instances = 0;
public float movementSpeed = 0;
public float minSpawnY = -14;
public float maxSpawnY = 14;
List<Enemy> deactivated = new List<Enemy>();
List<Enemy> activated = new List<Enemy>();
public static EnemyManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType(typeof(EnemyManager)) as EnemyManager;
}
return _instance;
}
}
void Start()
{
instances++;
if (instances > 1)
{
Debug.LogWarning("There are more than one EnemyManager");
}
else
{
_instance = this;
}
foreach (Transform child in transform)
{
deactivated.Add(child.GetComponent<Enemy>());
}
}
public void SpawnEnemy()
{
Enemy enemy = deactivated[0];
ActivateEnemy(enemy);
enemy.Spawn(movementSpeed, minSpawnY, maxSpawnY);
}
public void ActivateEnemy(Enemy enemy)
{
deactivated.Remove(enemy);
activated.Add(enemy);
}
public void ResetEnemy(Enemy sender)
{
activated.Remove(sender);
deactivated.Add(sender);
}
public void ResetAll()
{
gameObject.BroadcastMessage("ResetObject");
}
public void PauseAll()
{
this.gameObject.BroadcastMessage("Pause");
}
public void ResumeAll()
{
this.gameObject.BroadcastMessage("Resume");
}
}
| 16.682927 | 71 | 0.693713 | [
"MIT"
] | berkanuslu/bitcoin-runner-unity | Assets/Scripts/EnemyManager.cs | 1,370 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace CinemateAPI.Migrations
{
public partial class initialMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ProfilePicture = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "MoviesDetails",
columns: table => new
{
Id = table.Column<string>(nullable: false),
MovideDbId = table.Column<string>(nullable: false),
Title = table.Column<string>(nullable: false),
ImageUrl = table.Column<string>(nullable: false),
Description = table.Column<string>(nullable: false),
HomePage = table.Column<string>(nullable: true),
CreationDate = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MoviesDetails", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Reviews",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Summary = table.Column<string>(maxLength: 150, nullable: false),
Content = table.Column<string>(maxLength: 2000, nullable: false),
CreationDate = table.Column<DateTime>(nullable: false),
AuthorId = table.Column<string>(nullable: false),
MovieDetailsId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Reviews", x => x.Id);
table.ForeignKey(
name: "FK_Reviews_AspNetUsers_AuthorId",
column: x => x.AuthorId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Reviews_MoviesDetails_MovieDetailsId",
column: x => x.MovieDetailsId,
principalTable: "MoviesDetails",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UsersFavourites",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
MovieDetailsId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UsersFavourites", x => new { x.UserId, x.MovieDetailsId });
table.ForeignKey(
name: "FK_UsersFavourites_MoviesDetails_MovieDetailsId",
column: x => x.MovieDetailsId,
principalTable: "MoviesDetails",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UsersFavourites_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Comment",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Content = table.Column<string>(maxLength: 2000, nullable: false),
CreationDate = table.Column<DateTime>(nullable: false),
AuthorId = table.Column<string>(nullable: false),
ReviewId1 = table.Column<string>(nullable: true),
ReviewId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Comment", x => x.Id);
table.ForeignKey(
name: "FK_Comment_AspNetUsers_AuthorId",
column: x => x.AuthorId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Comment_Reviews_ReviewId1",
column: x => x.ReviewId1,
principalTable: "Reviews",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "UsersLikes",
columns: table => new
{
ReviewId = table.Column<int>(nullable: false),
AuthorId = table.Column<string>(nullable: false),
ReviewId1 = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_UsersLikes", x => new { x.AuthorId, x.ReviewId });
table.ForeignKey(
name: "FK_UsersLikes_AspNetUsers_AuthorId",
column: x => x.AuthorId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UsersLikes_Reviews_ReviewId1",
column: x => x.ReviewId1,
principalTable: "Reviews",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Comment_AuthorId",
table: "Comment",
column: "AuthorId");
migrationBuilder.CreateIndex(
name: "IX_Comment_ReviewId1",
table: "Comment",
column: "ReviewId1");
migrationBuilder.CreateIndex(
name: "IX_Reviews_AuthorId",
table: "Reviews",
column: "AuthorId");
migrationBuilder.CreateIndex(
name: "IX_Reviews_MovieDetailsId",
table: "Reviews",
column: "MovieDetailsId");
migrationBuilder.CreateIndex(
name: "IX_UsersFavourites_MovieDetailsId",
table: "UsersFavourites",
column: "MovieDetailsId");
migrationBuilder.CreateIndex(
name: "IX_UsersLikes_ReviewId1",
table: "UsersLikes",
column: "ReviewId1");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "Comment");
migrationBuilder.DropTable(
name: "UsersFavourites");
migrationBuilder.DropTable(
name: "UsersLikes");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "Reviews");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "MoviesDetails");
}
}
}
| 42.827763 | 108 | 0.478992 | [
"MIT"
] | GeorgiSv/CinemateAPI | CinemateAPI/Data/Migrations/20220127171001_initialMigration.cs | 16,662 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using SZORM.DbExpressions;
using SZORM.InternalExtensions;
using SZORM.Utility;
namespace SZORM.Factory.SQLite
{
partial class SqlGenerator : DbExpressionVisitor<DbExpression>
{
static Dictionary<string, Action<DbMethodCallExpression, SqlGenerator>> InitMethodHandlers()
{
var methodHandlers = new Dictionary<string, Action<DbMethodCallExpression, SqlGenerator>>();
methodHandlers.Add("Equals", Method_Equals);
methodHandlers.Add("Trim", Method_Trim);
methodHandlers.Add("TrimStart", Method_TrimStart);
methodHandlers.Add("TrimEnd", Method_TrimEnd);
methodHandlers.Add("StartsWith", Method_StartsWith);
methodHandlers.Add("EndsWith", Method_EndsWith);
methodHandlers.Add("ToUpper", Method_String_ToUpper);
methodHandlers.Add("ToLower", Method_String_ToLower);
methodHandlers.Add("Substring", Method_String_Substring);
methodHandlers.Add("IsNullOrEmpty", Method_String_IsNullOrEmpty);
methodHandlers.Add("Contains", Method_Contains);
methodHandlers.Add("Count", Method_Count);
methodHandlers.Add("LongCount", Method_LongCount);
methodHandlers.Add("Sum", Method_Sum);
methodHandlers.Add("Max", Method_Max);
methodHandlers.Add("Min", Method_Min);
methodHandlers.Add("Average", Method_Average);
methodHandlers.Add("IfNull", Method_IfNull);
methodHandlers.Add("AddYears", Method_DateTime_AddYears);
methodHandlers.Add("AddMonths", Method_DateTime_AddMonths);
methodHandlers.Add("AddDays", Method_DateTime_AddDays);
methodHandlers.Add("AddHours", Method_DateTime_AddHours);
methodHandlers.Add("AddMinutes", Method_DateTime_AddMinutes);
methodHandlers.Add("AddSeconds", Method_DateTime_AddSeconds);
methodHandlers.Add("Parse", Method_Parse);
methodHandlers.Add("NewGuid", Method_Guid_NewGuid);
methodHandlers.Add("DiffYears", Method_DbFunctions_DiffYears);
methodHandlers.Add("DiffMonths", Method_DbFunctions_DiffMonths);
methodHandlers.Add("DiffDays", Method_DbFunctions_DiffDays);
methodHandlers.Add("DiffHours", Method_DbFunctions_DiffHours);
methodHandlers.Add("DiffMinutes", Method_DbFunctions_DiffMinutes);
methodHandlers.Add("DiffSeconds", Method_DbFunctions_DiffSeconds);
methodHandlers.Add("DiffMilliseconds", Method_DbFunctions_DiffMilliseconds);
methodHandlers.Add("DiffMicroseconds", Method_DbFunctions_DiffMicroseconds);
var ret = Utils.Clone(methodHandlers);
return ret;
}
static void Method_Equals(DbMethodCallExpression exp, SqlGenerator generator)
{
if (exp.Method.ReturnType != UtilConstants.TypeOfBoolean || exp.Method.IsStatic || exp.Method.GetParameters().Length != 1)
throw UtilExceptions.NotSupportedMethod(exp.Method);
DbExpression right = exp.Arguments[0];
if (right.Type != exp.Object.Type)
{
right = DbExpression.Convert(right, exp.Object.Type);
}
DbExpression.Equal(exp.Object, right).Accept(generator);
}
static void Method_Trim(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_Trim);
generator._sqlBuilder.Append("TRIM(");
exp.Object.Accept(generator);
generator._sqlBuilder.Append(")");
}
static void Method_TrimStart(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_TrimStart);
EnsureTrimCharArgumentIsSpaces(exp.Arguments[0]);
generator._sqlBuilder.Append("LTRIM(");
exp.Object.Accept(generator);
generator._sqlBuilder.Append(")");
}
static void Method_TrimEnd(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_TrimEnd);
EnsureTrimCharArgumentIsSpaces(exp.Arguments[0]);
generator._sqlBuilder.Append("RTRIM(");
exp.Object.Accept(generator);
generator._sqlBuilder.Append(")");
}
static void Method_StartsWith(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_StartsWith);
exp.Object.Accept(generator);
generator._sqlBuilder.Append(" LIKE ");
exp.Arguments.First().Accept(generator);
generator._sqlBuilder.Append(" || '%'");
}
static void Method_EndsWith(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_EndsWith);
exp.Object.Accept(generator);
generator._sqlBuilder.Append(" LIKE '%' || ");
exp.Arguments.First().Accept(generator);
}
static void Method_String_Contains(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_Contains);
exp.Object.Accept(generator);
generator._sqlBuilder.Append(" LIKE '%' || ");
exp.Arguments.First().Accept(generator);
generator._sqlBuilder.Append(" || '%'");
}
static void Method_String_ToUpper(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_ToUpper);
generator._sqlBuilder.Append("UPPER(");
exp.Object.Accept(generator);
generator._sqlBuilder.Append(")");
}
static void Method_String_ToLower(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_ToLower);
generator._sqlBuilder.Append("LOWER(");
exp.Object.Accept(generator);
generator._sqlBuilder.Append(")");
}
static void Method_String_Substring(DbMethodCallExpression exp, SqlGenerator generator)
{
generator._sqlBuilder.Append("SUBSTR(");
exp.Object.Accept(generator);
generator._sqlBuilder.Append(",");
exp.Arguments[0].Accept(generator);
generator._sqlBuilder.Append(" + 1");
if (exp.Method == UtilConstants.MethodInfo_String_Substring_Int32)
{
}
else if (exp.Method == UtilConstants.MethodInfo_String_Substring_Int32_Int32)
{
generator._sqlBuilder.Append(",");
exp.Arguments[1].Accept(generator);
}
else
throw UtilExceptions.NotSupportedMethod(exp.Method);
generator._sqlBuilder.Append(")");
}
static void Method_String_IsNullOrEmpty(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_String_IsNullOrEmpty);
DbExpression e = exp.Arguments.First();
DbEqualExpression equalNullExpression = DbExpression.Equal(e, DbExpression.Constant(null, UtilConstants.TypeOfString));
DbEqualExpression equalEmptyExpression = DbExpression.Equal(e, DbExpression.Constant(string.Empty));
DbOrExpression orExpression = DbExpression.Or(equalNullExpression, equalEmptyExpression);
DbCaseWhenExpression.WhenThenExpressionPair whenThenPair = new DbCaseWhenExpression.WhenThenExpressionPair(orExpression, DbConstantExpression.One);
List<DbCaseWhenExpression.WhenThenExpressionPair> whenThenExps = new List<DbCaseWhenExpression.WhenThenExpressionPair>(1);
whenThenExps.Add(whenThenPair);
DbCaseWhenExpression caseWhenExpression = DbExpression.CaseWhen(whenThenExps, DbConstantExpression.Zero, UtilConstants.TypeOfBoolean);
var eqExp = DbExpression.Equal(caseWhenExpression, DbConstantExpression.One);
eqExp.Accept(generator);
}
static void Method_Contains(DbMethodCallExpression exp, SqlGenerator generator)
{
MethodInfo method = exp.Method;
if (method.DeclaringType == UtilConstants.TypeOfString)
{
Method_String_Contains(exp, generator);
return;
}
List<DbExpression> exps = new List<DbExpression>();
IEnumerable values = null;
DbExpression operand = null;
Type declaringType = method.DeclaringType;
if (typeof(IList).IsAssignableFrom(declaringType) || (declaringType.IsGenericType() && typeof(ICollection<>).MakeGenericType(declaringType.GetGenericArguments()).IsAssignableFrom(declaringType)))
{
DbMemberExpression memberExp = exp.Object as DbMemberExpression;
if (memberExp == null || !memberExp.IsEvaluable())
throw new NotSupportedException(exp.ToString());
values = DbExpressionExtension.Evaluate(memberExp) as IEnumerable; //Enumerable
operand = exp.Arguments[0];
goto constructInState;
}
if (method.IsStatic && declaringType == typeof(Enumerable) && exp.Arguments.Count == 2)
{
DbMemberExpression memberExp = exp.Arguments[0] as DbMemberExpression;
if (memberExp == null || !memberExp.IsEvaluable())
throw new NotSupportedException(exp.ToString());
values = DbExpressionExtension.Evaluate(memberExp) as IEnumerable;
operand = exp.Arguments[1];
goto constructInState;
}
throw UtilExceptions.NotSupportedMethod(exp.Method);
constructInState:
foreach (object value in values)
{
if (value == null)
exps.Add(DbExpression.Constant(null, operand.Type));
else
exps.Add(DbExpression.Parameter(value));
}
In(generator, exps, operand);
}
static void In(SqlGenerator generator, List<DbExpression> elementExps, DbExpression operand)
{
if (elementExps.Count == 0)
{
generator._sqlBuilder.Append("1=0");
return;
}
operand.Accept(generator);
generator._sqlBuilder.Append(" IN (");
for (int i = 0; i < elementExps.Count; i++)
{
if (i > 0)
generator._sqlBuilder.Append(",");
elementExps[i].Accept(generator);
}
generator._sqlBuilder.Append(")");
return;
}
static void Method_Count(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
Aggregate_Count(generator);
}
static void Method_LongCount(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
Aggregate_LongCount(generator);
}
static void Method_Sum(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
Aggregate_Sum(generator, exp.Arguments.First(), exp.Method.ReturnType);
}
static void Method_Max(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
Aggregate_Max(generator, exp.Arguments.First(), exp.Method.ReturnType);
}
static void Method_Min(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
Aggregate_Min(generator, exp.Arguments.First(), exp.Method.ReturnType);
}
static void Method_Average(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
Aggregate_Average(generator, exp.Arguments.First(), exp.Method.ReturnType);
}
static void Method_IfNull(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, typeof(SqlFun));
IfNull(generator, exp.Arguments.First(), exp.Method.ReturnType);
}
static void Method_DateTime_AddYears(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
DbFunction_DATEADD(generator, "years", exp);
}
static void Method_DateTime_AddMonths(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
DbFunction_DATEADD(generator, "months", exp);
}
static void Method_DateTime_AddDays(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
DbFunction_DATEADD(generator, "days", exp);
}
static void Method_DateTime_AddHours(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
DbFunction_DATEADD(generator, "hours", exp);
}
static void Method_DateTime_AddMinutes(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
DbFunction_DATEADD(generator, "minutes", exp);
}
static void Method_DateTime_AddSeconds(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
DbFunction_DATEADD(generator, "seconds", exp);
}
static void Method_Parse(DbMethodCallExpression exp, SqlGenerator generator)
{
if (exp.Arguments.Count != 1)
throw UtilExceptions.NotSupportedMethod(exp.Method);
DbExpression arg = exp.Arguments[0];
if (arg.Type != UtilConstants.TypeOfString)
throw UtilExceptions.NotSupportedMethod(exp.Method);
Type retType = exp.Method.ReturnType;
EnsureMethodDeclaringType(exp, retType);
DbExpression e = DbExpression.Convert(arg, retType);
e.Accept(generator);
}
static void Method_Guid_NewGuid(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_Guid_NewGuid);
throw UtilExceptions.NotSupportedMethod(exp.Method);
}
static void Method_DbFunctions_DiffYears(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffYears);
Append_DiffYears(generator, exp.Arguments[0], exp.Arguments[1]);
}
static void Method_DbFunctions_DiffMonths(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMonths);
DbExpression startDateTimeExp = exp.Arguments[0];
DbExpression endDateTimeExp = exp.Arguments[1];
/*
* This method will generating sql like following:
(cast(STRFTIME('%Y','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%Y','2015-08-06 09:01:24') as INTEGER)) * 12 + (cast(STRFTIME('%m','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%m','2015-08-06 09:01:24') as INTEGER))
*/
generator._sqlBuilder.Append("(");
/* (cast(STRFTIME('%Y','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%Y','2015-08-06 09:01:24') as INTEGER)) * 12 */
Append_DiffYears(generator, startDateTimeExp, endDateTimeExp);
generator._sqlBuilder.Append(" * 12");
generator._sqlBuilder.Append(" + ");
/* (cast(STRFTIME('%m','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%m','2015-08-06 09:01:24') as INTEGER)) */
generator._sqlBuilder.Append("(");
DbFunction_DATEPART(generator, "m", endDateTimeExp);
generator._sqlBuilder.Append(" - ");
DbFunction_DATEPART(generator, "m", startDateTimeExp);
generator._sqlBuilder.Append(")");
generator._sqlBuilder.Append(")");
}
static void Method_DbFunctions_DiffDays(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffDays);
Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], null);
}
static void Method_DbFunctions_DiffHours(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffHours);
Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], 24);
}
static void Method_DbFunctions_DiffMinutes(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMinutes);
Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], 24 * 60);
}
static void Method_DbFunctions_DiffSeconds(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffSeconds);
Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], 24 * 60 * 60);
}
static void Method_DbFunctions_DiffMilliseconds(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMilliseconds);
throw UtilExceptions.NotSupportedMethod(exp.Method);
}
static void Method_DbFunctions_DiffMicroseconds(DbMethodCallExpression exp, SqlGenerator generator)
{
EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMicroseconds);
throw UtilExceptions.NotSupportedMethod(exp.Method);
}
static void Append_JULIANDAY(SqlGenerator generator, DbExpression startDateTimeExp, DbExpression endDateTimeExp)
{
/* (JULIANDAY(endDateTimeExp)- JULIANDAY(startDateTimeExp)) */
generator._sqlBuilder.Append("(");
generator._sqlBuilder.Append("JULIANDAY(");
endDateTimeExp.Accept(generator);
generator._sqlBuilder.Append(")");
generator._sqlBuilder.Append(" - ");
generator._sqlBuilder.Append("JULIANDAY(");
startDateTimeExp.Accept(generator);
generator._sqlBuilder.Append(")");
generator._sqlBuilder.Append(")");
}
static void Append_DiffYears(SqlGenerator generator, DbExpression startDateTimeExp, DbExpression endDateTimeExp)
{
/* (CAST(STRFTIME('%Y',endDateTimeExp) as INTEGER) - CAST(STRFTIME('%Y',startDateTimeExp) as INTEGER)) */
generator._sqlBuilder.Append("(");
DbFunction_DATEPART(generator, "Y", endDateTimeExp);
generator._sqlBuilder.Append(" - ");
DbFunction_DATEPART(generator, "Y", startDateTimeExp);
generator._sqlBuilder.Append(")");
}
static void Append_DateDiff(SqlGenerator generator, DbExpression startDateTimeExp, DbExpression endDateTimeExp, int? multiplier)
{
/* CAST((JULIANDAY(endDateTimeExp)- JULIANDAY(startDateTimeExp)) AS INTEGER) */
/* OR */
/* CAST((JULIANDAY(endDateTimeExp)- JULIANDAY(startDateTimeExp)) * multiplier AS INTEGER) */
generator._sqlBuilder.Append("CAST(");
Append_JULIANDAY(generator, startDateTimeExp, endDateTimeExp);
if (multiplier != null)
generator._sqlBuilder.Append(" * ", multiplier.Value.ToString());
generator._sqlBuilder.Append(" AS INTEGER)");
}
}
}
| 42.387164 | 245 | 0.643872 | [
"MIT"
] | WinterWoods/SZORM | Factory/SQLite/SqlGenerator_MethodHandlers.cs | 20,475 | C# |
using Microsoft.Xna.Framework;
using SMFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AnalyticsCompiler
{
class RandomPoint : SMFramework.Testing.LabPoint
{
public RandomPoint(Vector3 position, float variance)
{
m_RootPosition = position;
Variance = variance;
}
public bool IsValid
{
get { return true; }
}
public void InterpretData(DataSnapshot dataSource)
{
}
public String SourceSensor
{
get;
set;
}
public String Label
{
get { return "Random Point [" + m_RootPosition + "] [Variance " + Variance + "]"; }
}
public Vector3 Position
{
get
{
return m_RootPosition + new Vector3(
(float)(m_RandomGenerator.NextDouble() * 2 - 1) * Variance,
(float)(m_RandomGenerator.NextDouble() * 2 - 1) * Variance,
(float)(m_RandomGenerator.NextDouble() * 2 - 1) * Variance
);
}
set
{
m_RootPosition = value;
}
}
private Vector3 m_RootPosition;
private static Random m_RandomGenerator = new Random();
float Variance;
}
}
| 18.032258 | 86 | 0.669052 | [
"MIT"
] | dgerding/Construct | SeeingMachinesVisualization/SeeingMachinesProject/Analytics Compiler/RandomPoint.cs | 1,120 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
internal class PageRouteModelFactory
{
private static readonly Action<ILogger, string, Exception> _unsupportedAreaPath;
private static readonly string IndexFileName = "Index" + RazorViewEngine.ViewExtension;
private readonly RazorPagesOptions _options;
private readonly ILogger _logger;
private readonly string _normalizedRootDirectory;
private readonly string _normalizedAreaRootDirectory;
static PageRouteModelFactory()
{
_unsupportedAreaPath = LoggerMessage.Define<string>(
LogLevel.Warning,
new EventId(1, "UnsupportedAreaPath"),
"The page at '{FilePath}' is located under the area root directory '/Areas/' but does not follow the path format '/Areas/AreaName/Pages/Directory/FileName.cshtml"
);
}
public PageRouteModelFactory(RazorPagesOptions options, ILogger logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_normalizedRootDirectory = NormalizeDirectory(options.RootDirectory);
_normalizedAreaRootDirectory = "/Areas/";
}
public PageRouteModel CreateRouteModel(string relativePath, string routeTemplate)
{
var viewEnginePath = GetViewEnginePath(_normalizedRootDirectory, relativePath);
var routeModel = new PageRouteModel(relativePath, viewEnginePath);
PopulateRouteModel(routeModel, viewEnginePath, routeTemplate);
return routeModel;
}
public PageRouteModel CreateAreaRouteModel(string relativePath, string routeTemplate)
{
if (!TryParseAreaPath(relativePath, out var areaResult))
{
return null;
}
var routeModel = new PageRouteModel(
relativePath,
areaResult.viewEnginePath,
areaResult.areaName
);
var routePrefix = CreateAreaRoute(areaResult.areaName, areaResult.viewEnginePath);
PopulateRouteModel(routeModel, routePrefix, routeTemplate);
routeModel.RouteValues["area"] = areaResult.areaName;
return routeModel;
}
private static void PopulateRouteModel(
PageRouteModel model,
string pageRoute,
string routeTemplate
)
{
model.RouteValues.Add("page", model.ViewEnginePath);
var selectorModel = CreateSelectorModel(pageRoute, routeTemplate);
model.Selectors.Add(selectorModel);
var fileName = Path.GetFileName(model.RelativePath);
if (
!AttributeRouteModel.IsOverridePattern(routeTemplate)
&& string.Equals(IndexFileName, fileName, StringComparison.OrdinalIgnoreCase)
)
{
// For pages without an override route, and ending in /Index.cshtml, we want to allow
// incoming routing, but force outgoing routes to match to the path sans /Index.
selectorModel.AttributeRouteModel.SuppressLinkGeneration = true;
var index = pageRoute.LastIndexOf('/');
var parentDirectoryPath =
index == -1 ? string.Empty : pageRoute.Substring(0, index);
model.Selectors.Add(CreateSelectorModel(parentDirectoryPath, routeTemplate));
}
}
// Internal for unit testing
internal bool TryParseAreaPath(
string relativePath,
out (string areaName, string viewEnginePath) result
)
{
// path = "/Areas/Products/Pages/Manage/Home.cshtml"
// Result ("Products", "/Manage/Home")
const string AreaPagesRoot = "/Pages/";
result = default;
Debug.Assert(relativePath.StartsWith("/", StringComparison.Ordinal));
// Parse the area root directory.
var areaRootEndIndex = relativePath.IndexOf('/', startIndex: 1);
if (
areaRootEndIndex == -1
|| areaRootEndIndex >= relativePath.Length - 1
|| // There's at least one token after the area root.
!relativePath.StartsWith(
_normalizedAreaRootDirectory,
StringComparison.OrdinalIgnoreCase
)
) // The path must start with area root.
{
_unsupportedAreaPath(_logger, relativePath, null);
return false;
}
// The first directory that follows the area root is the area name.
var areaEndIndex = relativePath.IndexOf('/', startIndex: areaRootEndIndex + 1);
if (areaEndIndex == -1 || areaEndIndex == relativePath.Length)
{
_unsupportedAreaPath(_logger, relativePath, null);
return false;
}
var areaName = relativePath.Substring(
areaRootEndIndex + 1,
areaEndIndex - areaRootEndIndex - 1
);
// Ensure the next token is the "Pages" directory
if (
string.Compare(
relativePath,
areaEndIndex,
AreaPagesRoot,
0,
AreaPagesRoot.Length,
StringComparison.OrdinalIgnoreCase
) != 0
)
{
_unsupportedAreaPath(_logger, relativePath, null);
return false;
}
// Include the trailing slash of the root directory at the start of the viewEnginePath
var pageNameIndex = areaEndIndex + AreaPagesRoot.Length - 1;
var viewEnginePath = relativePath.Substring(
pageNameIndex,
relativePath.Length - pageNameIndex - RazorViewEngine.ViewExtension.Length
);
result = (areaName, viewEnginePath);
return true;
}
private string GetViewEnginePath(string rootDirectory, string path)
{
// rootDirectory = "/Pages/AllMyPages/"
// path = "/Pages/AllMyPages/Home.cshtml"
// Result = "/Home"
Debug.Assert(path.StartsWith(rootDirectory, StringComparison.OrdinalIgnoreCase));
Debug.Assert(
path.EndsWith(RazorViewEngine.ViewExtension, StringComparison.OrdinalIgnoreCase)
);
var startIndex = rootDirectory.Length - 1;
var endIndex = path.Length - RazorViewEngine.ViewExtension.Length;
return path.Substring(startIndex, endIndex - startIndex);
}
private static string CreateAreaRoute(string areaName, string viewEnginePath)
{
// AreaName = Products, ViewEnginePath = /List/Categories
// Result = /Products/List/Categories
Debug.Assert(!string.IsNullOrEmpty(areaName));
Debug.Assert(!string.IsNullOrEmpty(viewEnginePath));
Debug.Assert(viewEnginePath.StartsWith("/", StringComparison.Ordinal));
return string.Create(
1 + areaName.Length + viewEnginePath.Length,
(areaName, viewEnginePath),
(span, tuple) =>
{
var (areaNameValue, viewEnginePathValue) = tuple;
span[0] = '/';
span = span.Slice(1);
areaNameValue.AsSpan().CopyTo(span);
span = span.Slice(areaNameValue.Length);
viewEnginePathValue.AsSpan().CopyTo(span);
}
);
}
private static SelectorModel CreateSelectorModel(string prefix, string routeTemplate)
{
return new SelectorModel
{
AttributeRouteModel = new AttributeRouteModel
{
Template = AttributeRouteModel.CombineTemplates(prefix, routeTemplate),
},
EndpointMetadata = { new PageRouteMetadata(prefix, routeTemplate) }
};
}
private static string NormalizeDirectory(string directory)
{
Debug.Assert(directory.StartsWith("/", StringComparison.Ordinal));
if (directory.Length > 1 && !directory.EndsWith("/", StringComparison.Ordinal))
{
return directory + "/";
}
return directory;
}
}
}
| 39.269565 | 178 | 0.587688 | [
"Apache-2.0"
] | belav/aspnetcore | src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs | 9,034 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.ContainerService.Outputs
{
[OutputType]
public sealed class KubernetesClusterAddonProfile
{
/// <summary>
/// A `aci_connector_linux` block. For more details, please visit [Create and configure an AKS cluster to use virtual nodes](https://docs.microsoft.com/en-us/azure/aks/virtual-nodes-portal).
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileAciConnectorLinux? AciConnectorLinux;
/// <summary>
/// An `azure_keyvault_secrets_provider` block as defined below. For more details, please visit [Azure Keyvault Secrets Provider for AKS](https://docs.microsoft.com/en-us/azure/aks/csi-secrets-store-driver).
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileAzureKeyvaultSecretsProvider? AzureKeyvaultSecretsProvider;
/// <summary>
/// A `azure_policy` block as defined below. For more details please visit [Understand Azure Policy for Azure Kubernetes Service](https://docs.microsoft.com/en-ie/azure/governance/policy/concepts/rego-for-aks)
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileAzurePolicy? AzurePolicy;
/// <summary>
/// A `http_application_routing` block as defined below.
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileHttpApplicationRouting? HttpApplicationRouting;
/// <summary>
/// An `ingress_application_gateway` block as defined below.
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileIngressApplicationGateway? IngressApplicationGateway;
/// <summary>
/// A `kube_dashboard` block as defined below.
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileKubeDashboard? KubeDashboard;
/// <summary>
/// A `oms_agent` block as defined below. For more details, please visit [How to onboard Azure Monitor for containers](https://docs.microsoft.com/en-us/azure/monitoring/monitoring-container-insights-onboard).
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileOmsAgent? OmsAgent;
/// <summary>
/// An `open_service_mesh` block as defined below. For more details, please visit [Open Service Mesh for AKS](https://docs.microsoft.com/azure/aks/open-service-mesh-about).
/// </summary>
public readonly Outputs.KubernetesClusterAddonProfileOpenServiceMesh? OpenServiceMesh;
[OutputConstructor]
private KubernetesClusterAddonProfile(
Outputs.KubernetesClusterAddonProfileAciConnectorLinux? aciConnectorLinux,
Outputs.KubernetesClusterAddonProfileAzureKeyvaultSecretsProvider? azureKeyvaultSecretsProvider,
Outputs.KubernetesClusterAddonProfileAzurePolicy? azurePolicy,
Outputs.KubernetesClusterAddonProfileHttpApplicationRouting? httpApplicationRouting,
Outputs.KubernetesClusterAddonProfileIngressApplicationGateway? ingressApplicationGateway,
Outputs.KubernetesClusterAddonProfileKubeDashboard? kubeDashboard,
Outputs.KubernetesClusterAddonProfileOmsAgent? omsAgent,
Outputs.KubernetesClusterAddonProfileOpenServiceMesh? openServiceMesh)
{
AciConnectorLinux = aciConnectorLinux;
AzureKeyvaultSecretsProvider = azureKeyvaultSecretsProvider;
AzurePolicy = azurePolicy;
HttpApplicationRouting = httpApplicationRouting;
IngressApplicationGateway = ingressApplicationGateway;
KubeDashboard = kubeDashboard;
OmsAgent = omsAgent;
OpenServiceMesh = openServiceMesh;
}
}
}
| 51.897436 | 217 | 0.723073 | [
"ECL-2.0",
"Apache-2.0"
] | ScriptBox99/pulumi-azure | sdk/dotnet/ContainerService/Outputs/KubernetesClusterAddonProfile.cs | 4,048 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Stride.Core.Assets.Editor.Quantum.NodePresenters;
using Stride.Core.Assets.Editor.Quantum.NodePresenters.Commands;
using Stride.Core.Assets.Editor.Quantum.NodePresenters.Keys;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Extensions;
using Stride.Core.Reflection;
using Stride.Assets.Entities;
using Stride.Assets.Presentation.NodePresenters.Keys;
using Stride.Assets.Presentation.ViewModel;
using Stride.Engine;
using Stride.Core.Presentation.Core;
namespace Stride.Assets.Presentation.NodePresenters.Updaters
{
internal sealed class EntityHierarchyAssetNodeUpdater : AssetNodePresenterUpdaterBase
{
protected override void UpdateNode(IAssetNodePresenter node)
{
if (!(node.Asset?.Asset is EntityHierarchyAssetBase))
return;
if (node.Value is EntityComponent && node.Parent?.Type == typeof(EntityComponentCollection))
{
// Apply the display name of the component
var displayAttribute = TypeDescriptorFactory.Default.AttributeRegistry.GetAttribute<DisplayAttribute>(node.Value.GetType());
if (!string.IsNullOrEmpty(displayAttribute?.Name))
node.DisplayName = displayAttribute.Name;
node.CombineKey = node.Value.GetType().Name;
if (node.Value is TransformComponent)
{
// Always put the transformation component in first.
node.Order = -1;
var removeCommand = node.Commands.FirstOrDefault(x => x.Name == RemoveItemCommand.CommandName);
node.Commands.Remove(removeCommand);
// Remove the Children property of the transformation component (it should be accessible via the scene graph)
node[nameof(TransformComponent.Children)].IsVisible = false;
}
}
if (node.Type == typeof(EntityComponentCollection))
{
var types = typeof(EntityComponent).GetInheritedInstantiableTypes()
.Where(x => Attribute.GetCustomAttribute(x, typeof(NonInstantiableAttribute)) == null &&
(EntityComponentAttributes.Get(x).AllowMultipleComponents
|| ((EntityComponentCollection)node.Value).All(y => y.GetType() != x)))
.OrderBy(DisplayAttribute.GetDisplayName)
.Select(x => new AbstractNodeType(x)).ToArray();
node.AttachedProperties.Add(EntityHierarchyData.EntityComponentAvailableTypesKey, types);
//TODO: Choose a better grouping method.
var typeGroups =
types.GroupBy(t => ComponentCategoryAttribute.GetCategory(t.Type))
.OrderBy(g => g.Key)
.Select(g => new AbstractNodeTypeGroup(g.Key, g.ToArray())).ToArray();
node.AttachedProperties.Add(EntityHierarchyData.EntityComponentAvailableTypeGroupsKey, typeGroups);
// Cannot replace entity component collection.
var replaceCommandIndex = node.Commands.IndexOf(x => x.Name == ReplacePropertyCommand.CommandName);
if (replaceCommandIndex >= 0)
node.Commands.RemoveAt(replaceCommandIndex);
// Combine components by type, but also append a index in case multiple components of the same types exist in the same collection.
var componentCount = new Dictionary<Type, int>();
foreach (var componentNode in node.Children)
{
var type = componentNode.Value.GetType();
int count;
componentCount.TryGetValue(type, out count);
componentNode.CombineKey = $"{type.Name}@{count}";
componentCount[type] = ++count;
}
}
if (typeof(EntityComponent).IsAssignableFrom(node.Type))
{
node.AttachedProperties.Add(ReferenceData.Key, new ComponentReferenceViewModel());
}
if (typeof(Entity) == node.Type)
{
node.AttachedProperties.Add(ReferenceData.Key, new EntityReferenceViewModel());
}
}
}
}
| 50.902174 | 163 | 0.6246 | [
"MIT"
] | Alan-love/xenko | sources/editor/Stride.Assets.Presentation/NodePresenters/Updaters/EntityHierarchyAssetNodeUpdater.cs | 4,683 | C# |
using System;
using System.Reflection;
using Moq;
using NUnit.Framework;
using Quartz;
using Quartz.Impl.Matchers;
using Quartz.Spi;
using SimpleInjector;
namespace Topshelf.SimpleInjector.Quartz.Test
{
[TestFixture]
public class TopshelfSimpleInjectorQuartzTest
{
private static Container _container;
[SetUp]
public void SetUp()
{
_container = new Container();
}
[Test, RunInApplicationDomain]
public void QuartzJobIsExecutedSuccessfullyTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
_container.Register<ISampleDependency, SampleDependency>();
//Act
var host = HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.Service<TestService>(s =>
{
s.ScheduleQuartzJob(configurator => configurator.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1)));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.AtLeastOnce);
}
[Test, RunInApplicationDomain]
public void QuartzJobWithCustomJobFactoryIsExecutedSuccessfullyTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
Mock<IJobFactory> factoryMock = new Mock<IJobFactory>();
factoryMock.Setup(factory => factory.NewJob(It.IsAny<TriggerFiredBundle>(), It.IsAny<IScheduler>())).Returns((IJob)testJobMock.Object);
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
_container.Register<ISampleDependency, SampleDependency>();
//Act
var host = HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.Service<TestService>(s =>
{
s.UsingQuartzJobFactory(() => (IJobFactory)factoryMock.Object);
s.ScheduleQuartzJob(configurator => configurator.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1)));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.AtLeastOnce);
factoryMock.Verify(factory => factory.NewJob(It.IsAny<TriggerFiredBundle>(), It.IsAny<IScheduler>()), Times.AtLeastOnce);
}
[Test, RunInApplicationDomain]
public void QuartzJobListenerIsExecutedSuccessfullyTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
Mock<IJobListener> jobListenerMock = new Mock<IJobListener>();
jobListenerMock.SetupGet(listener => listener.Name).Returns("jobWithListener");
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
_container.Register<ISampleDependency, SampleDependency>();
var jobWithListener = "jobWithListener";
var jobKey = new JobKey(jobWithListener);
//Act
var host = HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.Service<TestService>(s =>
{
s.ScheduleQuartzJob(configurator =>
configurator
.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1), jobWithListener)
.AddJobListener(() => (IJobListener)jobListenerMock.Object, KeyMatcher<JobKey>.KeyEquals(jobKey)));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.AtLeastOnce);
jobListenerMock.Verify(listener => listener.JobToBeExecuted(It.IsAny<IJobExecutionContext>()), Times.AtLeastOnce);
jobListenerMock.Verify(listener => listener.JobWasExecuted(It.IsAny<IJobExecutionContext>(), It.IsAny<JobExecutionException>()), Times.AtLeastOnce);
}
[Test, RunInApplicationDomain]
public void QuartzJobAsAServiceIsExecutedSuccessfullyTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
//Act
var host = HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.ScheduleQuartzJobAsService(configurator =>
configurator
.WithJob(() => JobBuilder.Create<IJob>().Build())
.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1)));
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.AtLeastOnce);
}
[Test, RunInApplicationDomain]
public void JobFactoryIsCorrectlyUsedForIJobCreationTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
_container.Register<ISampleDependency, SampleDependency>();
Mock<IJobFactory> factoryMock = new Mock<IJobFactory>();
//Act
var host = HostFactory.New(config =>
{
config.UsingQuartzJobFactory<IJobFactory>(() => factoryMock.Object);
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.Service<TestService>(s =>
{
s.ScheduleQuartzJob(configurator => configurator.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1)));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
factoryMock.Verify(factory => factory.NewJob(It.IsAny<TriggerFiredBundle>(), It.IsAny<IScheduler>()), Times.AtLeastOnce);
}
[Test, RunInApplicationDomain]
public void ExceptionIsThrownWhenTheContainerIsNullTest()
{
//Arrange
Container nullContainer = null;
//Act
var exception = Assert.Throws<ArgumentNullException>(() =>
HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(nullContainer);
}));
//Assert
Assert.AreEqual("Value cannot be null.\r\nParameter name: container", exception.Message);
}
[Test, RunInApplicationDomain]
public void ExceptionIsThrownWhenMissingCallToHostConfiguratorUseQuartzSimpleInjectorTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
//Act
var exception = Assert.Throws<ServiceBuilderException>(() =>
HostFactory.New(config =>
{
config.UseTestHost();
//config.UseQuartzSimpleInjector(_container); Missing
_container.Verify();
config.Service<TestService>(s =>
{
s.ScheduleQuartzJob(configurator => configurator.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1)));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
}));
//Assert
Assert.AreEqual("An exception occurred creating the service: TestService", exception.Message);
}
[Test, RunInApplicationDomain]
public void ExceptionIsThrownWhenContainerIsMisconfiguredTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
_container.Register<ISampleDependency, SampleDependency>();
//Act
var host = HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.ScheduleQuartzJobAsService(configurator =>
configurator
.WithJob(() => JobBuilder.Create<IJob>().Build())
.WithSimpleRepeatableSchedule<IJob>(TimeSpan.FromMilliseconds(1)));
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.Never);
}
[Test, RunInApplicationDomain]
public void DecoratedJobsAreCorrectlyExecutingTest()
{
//Arrange
Mock<IDecoratorDependency> decoratorDependencyMock = new Mock<IDecoratorDependency>();
_container.RegisterDecorator<IJob, TestJobDecorator>();
_container.Register<IDecoratorDependency>(() => decoratorDependencyMock.Object);
_container.Register<ISampleDependency, SampleDependency>();
//Act
var host = HostFactory.New(config =>
{
config.UseQuartzSimpleInjectorWithDecorators(_container, Assembly.GetExecutingAssembly());
config.UseTestHost();
_container.Verify();
config.Service<TestService>(s =>
{
s.ScheduleQuartzJob(configurator => configurator.WithSimpleRepeatableSchedule<TestJob>(TimeSpan.FromMilliseconds(1), nameof(TestJob)));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
decoratorDependencyMock.Verify(dependency => dependency.DoSomething(), Times.AtLeastOnce);
}
//[Test, RunInApplicationDomain]
//public void QuartzJobWithInvalidCronScheduleThrowsExceptionTest()
//{
// //Arrange
// Mock<IJob> testJobMock = new Mock<IJob>();
// _container.RegisterSingleton<IJob>(() => testJobMock.Object);
// _container.Register<ISampleDependency, SampleDependency>();
// //Act
// Exception exception = null;
// try
// {
// HostFactory.New(config =>
// {
// config.UseTestHost();
// config.UseQuartzSimpleInjector(_container);
// _container.Verify();
// config.ScheduleQuartzJobAsService(configurator =>
// configurator
// .WithJob(() => JobBuilder.Create<IJob>().Build())
// .WithCronSchedule<IJob>("Invalid Cron Schedule"));
// });
// }
// catch (Exception ex)
// {
// exception = ex;
// }
// //Assert
// Assert.AreEqual("must specify a valid cron expression\r\nParameter name: cronExpression", exception.Message);
// testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.Never);
//}
[Test, RunInApplicationDomain]
public void QuartzJobWithCronScheduleIsExecutedSuccessfullyTest()
{
//Arrange
Mock<IJob> testJobMock = new Mock<IJob>();
_container.RegisterSingleton<IJob>(() => testJobMock.Object);
_container.Register<ISampleDependency, SampleDependency>();
//Act
var host = HostFactory.New(config =>
{
config.UseTestHost();
config.UseQuartzSimpleInjector(_container);
_container.Verify();
config.Service<TestService>(s =>
{
s.ScheduleQuartzJob(configurator => configurator
.WithCronSchedule<IJob>("0/1 * * * * ?")
.EnableJobWhen(() => true));
s.ConstructUsingSimpleInjector();
s.WhenStarted((service, control) => service.Start());
s.WhenStopped((service, control) => service.Stop());
});
});
var exitCode = host.Run();
//Assert
Assert.AreEqual(TopshelfExitCode.Ok, exitCode);
testJobMock.Verify(job => job.Execute(It.IsAny<IJobExecutionContext>()), Times.AtLeastOnce);
}
}
public class TestService
{
private readonly ISampleDependency _sample;
public TestService(ISampleDependency sample)
{
_sample = sample;
}
public bool Start()
{
Console.WriteLine("Sample Service Started.");
Console.WriteLine("Sample Dependency: {0}", _sample);
return _sample != null;
}
public bool Stop()
{
return _sample != null;
}
}
public interface ISampleDependency
{
}
[Serializable]
public class SampleDependency : ISampleDependency
{
}
public class TestJob : IJob
{
public void Execute(IJobExecutionContext context)
{
Console.WriteLine("Executing...");
}
}
public interface IDecoratorDependency
{
void DoSomething();
}
public class TestJobDecorator : IJob
{
private readonly IJob _jobDecoratee;
private readonly IDecoratorDependency _decoratorDependency;
public TestJobDecorator(IJob jobDecoratee, IDecoratorDependency decoratorDependency)
{
_jobDecoratee = jobDecoratee;
_decoratorDependency = decoratorDependency;
}
public void Execute(IJobExecutionContext context)
{
_jobDecoratee.Execute(context);
_decoratorDependency.DoSomething();
}
}
} | 37.971631 | 160 | 0.562446 | [
"MIT"
] | AdaskoTheBeAsT/Topshelf.SimpleInjector | Tests/Topshelf.SimpleInjector.Quartz.Test/TopshelfSimpleInjectorQuartzTest.cs | 16,064 | C# |
using System.Collections.Generic;
using System.IO;
using System.Windows;
using RayCarrot.IO;
using RayCarrot.Rayman;
using RayCarrot.Rayman.Ray1;
namespace RayCarrot.RCP.Metro
{
/// <summary>
/// The Rayman by his Fans game info
/// </summary>
public sealed class GameInfo_RaymanByHisFans : GameInfo
{
#region Protected Override Properties
/// <summary>
/// Gets the backup directories for the game
/// </summary>
protected override IList<GameBackups_Directory> GetBackupDirectories => new GameBackups_Directory[]
{
// NOTE: Due to a mistake where the .sct files were not included in previous backups we need to keep this version for legacy support
new GameBackups_Directory(Game.GetInstallDir(), SearchOption.TopDirectoryOnly, "*.cfg", "1", 0),
new GameBackups_Directory(Game.GetInstallDir(), SearchOption.TopDirectoryOnly, "*.cfg", "0", 1),
new GameBackups_Directory(Game.GetInstallDir() + "PCMAP", SearchOption.TopDirectoryOnly, "*.sct", "1", 1),
};
#endregion
#region Public Override Properties
/// <summary>
/// The game
/// </summary>
public override Games Game => Games.RaymanByHisFans;
/// <summary>
/// The category for the game
/// </summary>
public override GameCategory Category => GameCategory.Rayman;
/// <summary>
/// The game display name
/// </summary>
public override string DisplayName => "Rayman by his Fans";
/// <summary>
/// The game backup name
/// </summary>
public override string BackupName => "Rayman by his Fans";
/// <summary>
/// Gets the launch name for the game
/// </summary>
public override string DefaultFileName => "rayfan.bat";
/// <summary>
/// The config page view model, if any is available
/// </summary>
public override GameOptionsDialog_ConfigPageViewModel ConfigPageViewModel => new Config_RaymanByHisFans_ViewModel(Game);
/// <summary>
/// The options UI, if any is available
/// </summary>
public override FrameworkElement OptionsUI => new GameOptions_DOSBox_UI(Game);
/// <summary>
/// The progression view model, if any is available
/// </summary>
public override GameProgression_BaseViewModel ProgressionViewModel => new GameProgression_RaymanDesigner_ViewModel(Game);
/// <summary>
/// Optional RayMap URL
/// </summary>
public override string RayMapURL => AppURLs.GetRay1MapGameURL("RaymanByHisFansPC", "r1/pc_fan");
/// <summary>
/// Gets the file links for the game
/// </summary>
public override IList<GameFileLink> GetGameFileLinks => new GameFileLink[0];
/// <summary>
/// Indicates if the game has archives which can be opened
/// </summary>
public override bool HasArchives => true;
/// <summary>
/// Gets the archive data manager for the game
/// </summary>
public override IArchiveDataManager GetArchiveDataManager => new Ray1PCArchiveDataManager(new Ray1PCArchiveConfigViewModel(Ray1Settings.GetDefaultSettings(Ray1Game.RayKit, Platform.PC)));
/// <summary>
/// Gets the archive file paths for the game
/// </summary>
/// <param name="installDir">The game's install directory</param>
public override FileSystemPath[] GetArchiveFilePaths(FileSystemPath installDir) => Ray1PCArchiveDataManager.GetArchiveFiles(installDir);
/// <summary>
/// An optional emulator to use for the game
/// </summary>
public override Emulator Emulator => new Emulator_DOSBox(Game, GameType.DosBox);
#endregion
}
} | 36.952381 | 195 | 0.631959 | [
"MIT"
] | RayCarrot/RayCarrot.RCP.Metro | src/RayCarrot.RCP.Metro/Games/Info/Rayman/GameInfo_RaymanByHisFans.cs | 3,882 | C# |
namespace FamilyStore.Web.Controllers
{
using System;
using System.Threading.Tasks;
using FamilyStore.Data.Common.Repositories;
using FamilyStore.Data.Models;
using FamilyStore.Services.Data;
using FamilyStore.Web.ViewModels.Settings;
using Microsoft.AspNetCore.Mvc;
public class SettingsController : BaseController
{
private readonly ISettingsService settingsService;
private readonly IDeletableEntityRepository<Setting> repository;
public SettingsController(ISettingsService settingsService, IDeletableEntityRepository<Setting> repository)
{
this.settingsService = settingsService;
this.repository = repository;
}
public IActionResult Index()
{
var settings = this.settingsService.GetAll<SettingViewModel>();
var model = new SettingsListViewModel { Settings = settings };
return this.View(model);
}
public async Task<IActionResult> InsertSetting()
{
var random = new Random();
var setting = new Setting { Name = $"Name_{random.Next()}", Value = $"Value_{random.Next()}" };
await this.repository.AddAsync(setting);
await this.repository.SaveChangesAsync();
return this.RedirectToAction(nameof(this.Index));
}
}
}
| 31.181818 | 115 | 0.656706 | [
"MIT"
] | SvetlinNikolov/FamilyStore | src/Web/FamilyStore.Web/Controllers/SettingsController.cs | 1,374 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// StagedDiscountDstCampPrizeModel Data Structure.
/// </summary>
public class StagedDiscountDstCampPrizeModel : AlipayObject
{
/// <summary>
/// 折扣预算ID
/// </summary>
[JsonPropertyName("budget_id")]
public string BudgetId { get; set; }
/// <summary>
/// 折扣幅度列表.
/// </summary>
[JsonPropertyName("discount_rate_model_list")]
public List<DiscountRateModel> DiscountRateModelList { get; set; }
/// <summary>
/// 奖品id
/// </summary>
[JsonPropertyName("id")]
public string Id { get; set; }
/// <summary>
/// 单次优惠上限(元)
/// </summary>
[JsonPropertyName("max_discount_amt")]
public string MaxDiscountAmt { get; set; }
}
}
| 25.916667 | 74 | 0.572347 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/StagedDiscountDstCampPrizeModel.cs | 973 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Framework.Testing.Input;
using osu.Framework.Utils;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Osu.Skinning;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osu.Game.Screens.Play;
using osu.Game.Skinning;
using osu.Game.Tests.Gameplay;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class TestSceneGameplayCursor : OsuSkinnableTestScene
{
[Cached]
private GameplayState gameplayState;
private OsuCursorContainer lastContainer;
[Resolved]
private OsuConfigManager config { get; set; }
private Drawable background;
public TestSceneGameplayCursor()
{
var ruleset = new OsuRuleset();
gameplayState = TestGameplayState.Create(ruleset);
AddStep("change background colour", () =>
{
background?.Expire();
Add(background = new Box
{
RelativeSizeAxes = Axes.Both,
Depth = float.MaxValue,
Colour = new Colour4(RNG.NextSingle(), RNG.NextSingle(), RNG.NextSingle(), 1)
});
});
AddSliderStep("circle size", 0f, 10f, 0f, val =>
{
config.SetValue(OsuSetting.AutoCursorSize, true);
gameplayState.Beatmap.Difficulty.CircleSize = val;
Scheduler.AddOnce(loadContent);
});
AddStep("test cursor container", () => loadContent(false));
}
[TestCase(1, 1)]
[TestCase(5, 1)]
[TestCase(10, 1)]
[TestCase(1, 1.5f)]
[TestCase(5, 1.5f)]
[TestCase(10, 1.5f)]
public void TestSizing(int circleSize, float userScale)
{
AddStep($"set user scale to {userScale}", () => config.SetValue(OsuSetting.GameplayCursorSize, userScale));
AddStep($"adjust cs to {circleSize}", () => gameplayState.Beatmap.Difficulty.CircleSize = circleSize);
AddStep("turn on autosizing", () => config.SetValue(OsuSetting.AutoCursorSize, true));
AddStep("load content", loadContent);
AddUntilStep("cursor size correct", () => lastContainer.ActiveCursor.Scale.X == OsuCursorContainer.GetScaleForCircleSize(circleSize) * userScale);
AddStep("set user scale to 1", () => config.SetValue(OsuSetting.GameplayCursorSize, 1f));
AddUntilStep("cursor size correct", () => lastContainer.ActiveCursor.Scale.X == OsuCursorContainer.GetScaleForCircleSize(circleSize));
AddStep("turn off autosizing", () => config.SetValue(OsuSetting.AutoCursorSize, false));
AddUntilStep("cursor size correct", () => lastContainer.ActiveCursor.Scale.X == 1);
AddStep($"set user scale to {userScale}", () => config.SetValue(OsuSetting.GameplayCursorSize, userScale));
AddUntilStep("cursor size correct", () => lastContainer.ActiveCursor.Scale.X == userScale);
}
[Test]
public void TestTopLeftOrigin()
{
AddStep("load content", () => loadContent(false, () => new SkinProvidingContainer(new TopLeftCursorSkin())));
}
private void loadContent() => loadContent(false);
private void loadContent(bool automated, Func<SkinProvidingContainer> skinProvider = null)
{
SetContents(_ =>
{
var inputManager = automated ? (InputManager)new MovingCursorInputManager() : new OsuInputManager(new OsuRuleset().RulesetInfo);
var skinContainer = skinProvider?.Invoke() ?? new SkinProvidingContainer(null);
lastContainer = automated ? new ClickingCursorContainer() : new OsuCursorContainer();
return inputManager.WithChild(skinContainer.WithChild(lastContainer));
});
}
private class TopLeftCursorSkin : ISkin
{
public Drawable GetDrawableComponent(ISkinComponent component) => null;
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) => null;
public ISample GetSample(ISampleInfo sampleInfo) => null;
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup)
{
switch (lookup)
{
case OsuSkinConfiguration osuLookup:
if (osuLookup == OsuSkinConfiguration.CursorCentre)
return SkinUtils.As<TValue>(new BindableBool());
break;
}
return null;
}
}
private class ClickingCursorContainer : OsuCursorContainer
{
private bool pressed;
public bool Pressed
{
set
{
if (value == pressed)
return;
pressed = value;
if (value)
OnPressed(new KeyBindingPressEvent<OsuAction>(GetContainingInputManager().CurrentState, OsuAction.LeftButton));
else
OnReleased(new KeyBindingReleaseEvent<OsuAction>(GetContainingInputManager().CurrentState, OsuAction.LeftButton));
}
}
protected override void Update()
{
base.Update();
Pressed = ((int)(Time.Current / 1000)) % 2 == 0;
}
}
private class MovingCursorInputManager : ManualInputManager
{
public MovingCursorInputManager()
{
UseParentInput = false;
ShowVisualCursorGuide = false;
}
protected override void Update()
{
base.Update();
const double spin_duration = 5000;
double currentTime = Time.Current;
double angle = (currentTime % spin_duration) / spin_duration * 2 * Math.PI;
Vector2 rPos = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
MoveMouseTo(ToScreenSpace(DrawSize / 2 + DrawSize / 3 * rPos));
}
}
}
}
| 37.5 | 159 | 0.576487 | [
"MIT"
] | Theighlin/osu | osu.Game.Rulesets.Osu.Tests/TestSceneGameplayCursor.cs | 6,792 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.AppMesh.Outputs
{
[OutputType]
public sealed class VirtualNodeSpecBackendVirtualServiceClientPolicy
{
/// <summary>
/// The Transport Layer Security (TLS) client policy.
/// </summary>
public readonly Outputs.VirtualNodeSpecBackendVirtualServiceClientPolicyTls? Tls;
[OutputConstructor]
private VirtualNodeSpecBackendVirtualServiceClientPolicy(Outputs.VirtualNodeSpecBackendVirtualServiceClientPolicyTls? tls)
{
Tls = tls;
}
}
}
| 30.678571 | 130 | 0.712456 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/AppMesh/Outputs/VirtualNodeSpecBackendVirtualServiceClientPolicy.cs | 859 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Maui;
using Maui.Entities;
namespace Maui.Dynamics
{
public static class CalcTool
{
public static double Yield( this MauiX.ICalc self, StockPrice from, StockPrice to )
{
return ( to.Close - from.Close ) * 100 / from.Close;
}
}
}
| 21.555556 | 92 | 0.626289 | [
"BSD-3-Clause"
] | bg0jr/Maui | src/Dynamics/Maui.Dynamics/Glue/CalcTool.cs | 390 | C# |
using System.Threading.Tasks;
using Surging.Cloud.CPlatform.Ioc;
using Surging.Cloud.KestrelHttpServer;
namespace Surging.Hero.FileService.Domain.Captchas
{
public interface ICaptchaDomainService : ITransientDependency
{
Task<IActionResult> GetCaptcha(string uuid);
}
} | 26.363636 | 65 | 0.77931 | [
"MIT"
] | liuhll/hero | src/Services/FileService/Surging.Hero.FileService.Domain/Captchas/ICaptchaDomainService.cs | 290 | C# |
using ProgLessons.IoC_example.App.Services.Core;
namespace ProgLessons.IoC_example.Presentation.UI.Console
{
class Program
{
static void Main(string[] args)
{
var app = new AppManager(typeof(ConsoleManager));
app.Run();
}
}
} | 23 | 62 | 0.585284 | [
"MIT"
] | prog-lessons/c-sharp | ProgLessons.IoC-example/Presentation/ProgLessons.IoC-example.Presentation.UI.Console/Program.cs | 301 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='IShellView2.xml' path='doc/member[@name="IShellView2"]/*' />
[Guid("88E39E80-3578-11CF-AE69-08002B2E1262")]
[NativeTypeName("struct IShellView2 : IShellView")]
[NativeInheritance("IShellView")]
public unsafe partial struct IShellView2 : IShellView2.Interface
{
public void** lpVtbl;
/// <inheritdoc cref="IUnknown.QueryInterface" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IShellView2*, Guid*, void**, int>)(lpVtbl[0]))((IShellView2*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc cref="IUnknown.AddRef" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IShellView2*, uint>)(lpVtbl[1]))((IShellView2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IUnknown.Release" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IShellView2*, uint>)(lpVtbl[2]))((IShellView2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IOleWindow.GetWindow" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public HRESULT GetWindow(HWND* phwnd)
{
return ((delegate* unmanaged<IShellView2*, HWND*, int>)(lpVtbl[3]))((IShellView2*)Unsafe.AsPointer(ref this), phwnd);
}
/// <inheritdoc cref="IOleWindow.ContextSensitiveHelp" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public HRESULT ContextSensitiveHelp(BOOL fEnterMode)
{
return ((delegate* unmanaged<IShellView2*, BOOL, int>)(lpVtbl[4]))((IShellView2*)Unsafe.AsPointer(ref this), fEnterMode);
}
/// <inheritdoc cref="IShellView.TranslateAcceleratorW" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public HRESULT TranslateAcceleratorW(MSG* pmsg)
{
return ((delegate* unmanaged<IShellView2*, MSG*, int>)(lpVtbl[5]))((IShellView2*)Unsafe.AsPointer(ref this), pmsg);
}
/// <inheritdoc cref="IShellView.EnableModeless" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public HRESULT EnableModeless(BOOL fEnable)
{
return ((delegate* unmanaged<IShellView2*, BOOL, int>)(lpVtbl[6]))((IShellView2*)Unsafe.AsPointer(ref this), fEnable);
}
/// <inheritdoc cref="IShellView.UIActivate" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
public HRESULT UIActivate(uint uState)
{
return ((delegate* unmanaged<IShellView2*, uint, int>)(lpVtbl[7]))((IShellView2*)Unsafe.AsPointer(ref this), uState);
}
/// <inheritdoc cref="IShellView.Refresh" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
public HRESULT Refresh()
{
return ((delegate* unmanaged<IShellView2*, int>)(lpVtbl[8]))((IShellView2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IShellView.CreateViewWindow" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
public HRESULT CreateViewWindow(IShellView* psvPrevious, [NativeTypeName("LPCFOLDERSETTINGS")] FOLDERSETTINGS* pfs, IShellBrowser* psb, RECT* prcView, HWND* phWnd)
{
return ((delegate* unmanaged<IShellView2*, IShellView*, FOLDERSETTINGS*, IShellBrowser*, RECT*, HWND*, int>)(lpVtbl[9]))((IShellView2*)Unsafe.AsPointer(ref this), psvPrevious, pfs, psb, prcView, phWnd);
}
/// <inheritdoc cref="IShellView.DestroyViewWindow" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(10)]
public HRESULT DestroyViewWindow()
{
return ((delegate* unmanaged<IShellView2*, int>)(lpVtbl[10]))((IShellView2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IShellView.GetCurrentInfo" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(11)]
public HRESULT GetCurrentInfo([NativeTypeName("LPFOLDERSETTINGS")] FOLDERSETTINGS* pfs)
{
return ((delegate* unmanaged<IShellView2*, FOLDERSETTINGS*, int>)(lpVtbl[11]))((IShellView2*)Unsafe.AsPointer(ref this), pfs);
}
/// <inheritdoc cref="IShellView.AddPropertySheetPages" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(12)]
public HRESULT AddPropertySheetPages([NativeTypeName("DWORD")] uint dwReserved, [NativeTypeName("LPFNSVADDPROPSHEETPAGE")] delegate* unmanaged<HPROPSHEETPAGE, LPARAM, BOOL> pfn, LPARAM lparam)
{
return ((delegate* unmanaged<IShellView2*, uint, delegate* unmanaged<HPROPSHEETPAGE, LPARAM, BOOL>, LPARAM, int>)(lpVtbl[12]))((IShellView2*)Unsafe.AsPointer(ref this), dwReserved, pfn, lparam);
}
/// <inheritdoc cref="IShellView.SaveViewState" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(13)]
public HRESULT SaveViewState()
{
return ((delegate* unmanaged<IShellView2*, int>)(lpVtbl[13]))((IShellView2*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc cref="IShellView.SelectItem" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(14)]
public HRESULT SelectItem([NativeTypeName("LPCITEMIDLIST")] ITEMIDLIST* pidlItem, [NativeTypeName("SVSIF")] uint uFlags)
{
return ((delegate* unmanaged<IShellView2*, ITEMIDLIST*, uint, int>)(lpVtbl[14]))((IShellView2*)Unsafe.AsPointer(ref this), pidlItem, uFlags);
}
/// <inheritdoc cref="IShellView.GetItemObject" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(15)]
public HRESULT GetItemObject(uint uItem, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IShellView2*, uint, Guid*, void**, int>)(lpVtbl[15]))((IShellView2*)Unsafe.AsPointer(ref this), uItem, riid, ppv);
}
/// <include file='IShellView2.xml' path='doc/member[@name="IShellView2.GetView"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(16)]
public HRESULT GetView([NativeTypeName("SHELLVIEWID *")] Guid* pvid, [NativeTypeName("ULONG")] uint uView)
{
return ((delegate* unmanaged<IShellView2*, Guid*, uint, int>)(lpVtbl[16]))((IShellView2*)Unsafe.AsPointer(ref this), pvid, uView);
}
/// <include file='IShellView2.xml' path='doc/member[@name="IShellView2.CreateViewWindow2"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(17)]
public HRESULT CreateViewWindow2([NativeTypeName("LPSV2CVW2_PARAMS")] SV2CVW2_PARAMS* lpParams)
{
return ((delegate* unmanaged<IShellView2*, SV2CVW2_PARAMS*, int>)(lpVtbl[17]))((IShellView2*)Unsafe.AsPointer(ref this), lpParams);
}
/// <include file='IShellView2.xml' path='doc/member[@name="IShellView2.HandleRename"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(18)]
public HRESULT HandleRename([NativeTypeName("LPCITEMIDLIST")] ITEMIDLIST* pidlNew)
{
return ((delegate* unmanaged<IShellView2*, ITEMIDLIST*, int>)(lpVtbl[18]))((IShellView2*)Unsafe.AsPointer(ref this), pidlNew);
}
/// <include file='IShellView2.xml' path='doc/member[@name="IShellView2.SelectAndPositionItem"]/*' />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(19)]
public HRESULT SelectAndPositionItem([NativeTypeName("LPCITEMIDLIST")] ITEMIDLIST* pidlItem, uint uFlags, POINT* ppt)
{
return ((delegate* unmanaged<IShellView2*, ITEMIDLIST*, uint, POINT*, int>)(lpVtbl[19]))((IShellView2*)Unsafe.AsPointer(ref this), pidlItem, uFlags, ppt);
}
public interface Interface : IShellView.Interface
{
[VtblIndex(16)]
HRESULT GetView([NativeTypeName("SHELLVIEWID *")] Guid* pvid, [NativeTypeName("ULONG")] uint uView);
[VtblIndex(17)]
HRESULT CreateViewWindow2([NativeTypeName("LPSV2CVW2_PARAMS")] SV2CVW2_PARAMS* lpParams);
[VtblIndex(18)]
HRESULT HandleRename([NativeTypeName("LPCITEMIDLIST")] ITEMIDLIST* pidlNew);
[VtblIndex(19)]
HRESULT SelectAndPositionItem([NativeTypeName("LPCITEMIDLIST")] ITEMIDLIST* pidlItem, uint uFlags, POINT* ppt);
}
public partial struct Vtbl<TSelf>
where TSelf : unmanaged, Interface
{
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> AddRef;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> Release;
[NativeTypeName("HRESULT (HWND *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, HWND*, int> GetWindow;
[NativeTypeName("HRESULT (BOOL) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, BOOL, int> ContextSensitiveHelp;
[NativeTypeName("HRESULT (MSG *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, MSG*, int> TranslateAcceleratorW;
[NativeTypeName("HRESULT (BOOL) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, BOOL, int> EnableModeless;
[NativeTypeName("HRESULT (UINT) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, int> UIActivate;
[NativeTypeName("HRESULT () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int> Refresh;
[NativeTypeName("HRESULT (IShellView *, LPCFOLDERSETTINGS, IShellBrowser *, RECT *, HWND *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IShellView*, FOLDERSETTINGS*, IShellBrowser*, RECT*, HWND*, int> CreateViewWindow;
[NativeTypeName("HRESULT () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int> DestroyViewWindow;
[NativeTypeName("HRESULT (LPFOLDERSETTINGS) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, FOLDERSETTINGS*, int> GetCurrentInfo;
[NativeTypeName("HRESULT (DWORD, LPFNSVADDPROPSHEETPAGE, LPARAM) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, delegate* unmanaged<HPROPSHEETPAGE, LPARAM, BOOL>, LPARAM, int> AddPropertySheetPages;
[NativeTypeName("HRESULT () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, int> SaveViewState;
[NativeTypeName("HRESULT (LPCITEMIDLIST, SVSIF) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, ITEMIDLIST*, uint, int> SelectItem;
[NativeTypeName("HRESULT (UINT, const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint, Guid*, void**, int> GetItemObject;
[NativeTypeName("HRESULT (SHELLVIEWID *, ULONG) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, uint, int> GetView;
[NativeTypeName("HRESULT (LPSV2CVW2_PARAMS) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, SV2CVW2_PARAMS*, int> CreateViewWindow2;
[NativeTypeName("HRESULT (LPCITEMIDLIST) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, ITEMIDLIST*, int> HandleRename;
[NativeTypeName("HRESULT (LPCITEMIDLIST, UINT, POINT *) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, ITEMIDLIST*, uint, POINT*, int> SelectAndPositionItem;
}
}
| 46.022989 | 210 | 0.694555 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ShObjIdl_core/IShellView2.cs | 12,014 | C# |
using AuditingDatabase;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace DotNetCoreArchitecture.Domain.CRM
{
[Table("SpecialOfferExpanding")]
public class SpecialOfferExpanding : IAuditable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("Id")]
public Guid Id { get; set; }
[Column("OfferName")]
public string OfferName { get; set; }
[Column("OfferType")]
public string OfferType { get; set; }
[Column("IssueDate")]
public DateTime IssueDate { get; set; }
[Column("FromDate")]
public DateTime FromDate { get; set; }
[Column("ToDate")]
public DateTime ToDate { get; set; }
/* customer special offer reference key */
[Column("Description")]
public string Description { get; set; }
[Column("Notes")]
public string Notes { get; set; }
[Column("IsApproved")]
public bool IsApproved { get; set; }
[Column("IsExpired")]
public bool IsExpired { get; set; }
[Column("ApprovedDate")]
public DateTime ApprovedDate { get; set; }
[Column("ExpiredDate")]
public DateTime ExpiredDate { get; set; }
}
}
| 25.090909 | 61 | 0.613768 | [
"MIT"
] | yousefataya/HRMS | source/Domain/CRM/SpecialOfferExpanding.cs | 1,380 | C# |
/*
* Copyright (c) 2010 Yuri K. Schlesner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Sha2
{
public class Sha256
{
private static readonly UInt32[] K = new UInt32[64] {
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
};
private static UInt32 ROTL(UInt32 x, byte n)
{
Debug.Assert(n < 32);
return (x << n) | (x >> (32 - n));
}
private static UInt32 ROTR(UInt32 x, byte n)
{
Debug.Assert(n < 32);
return (x >> n) | (x << (32 - n));
}
private static UInt32 Ch(UInt32 x, UInt32 y, UInt32 z)
{
return (x & y) ^ ((~x) & z);
}
private static UInt32 Maj(UInt32 x, UInt32 y, UInt32 z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
private static UInt32 Sigma0(UInt32 x)
{
return ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22);
}
private static UInt32 Sigma1(UInt32 x)
{
return ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25);
}
private static UInt32 sigma0(UInt32 x)
{
return ROTR(x, 7) ^ ROTR(x, 18) ^ (x >> 3);
}
private static UInt32 sigma1(UInt32 x)
{
return ROTR(x, 17) ^ ROTR(x, 19) ^ (x >> 10);
}
private UInt32[] H = new UInt32[8] {
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
};
private byte[] pending_block = new byte[64];
private uint pending_block_off = 0;
private UInt32[] uint_buffer = new UInt32[16];
private UInt64 bits_processed = 0;
private bool closed = false;
private void processBlock(UInt32[] M)
{
Debug.Assert(M.Length == 16);
// 1. Prepare the message schedule (W[t]):
UInt32[] W = new UInt32[64];
for (int t = 0; t < 16; ++t)
{
W[t] = M[t];
}
for (int t = 16; t < 64; ++t)
{
W[t] = sigma1(W[t - 2]) + W[t - 7] + sigma0(W[t - 15]) + W[t - 16];
}
// 2. Initialize the eight working variables with the (i-1)-st hash value:
UInt32 a = H[0],
b = H[1],
c = H[2],
d = H[3],
e = H[4],
f = H[5],
g = H[6],
h = H[7];
// 3. For t=0 to 63:
for (int t = 0; t < 64; ++t)
{
UInt32 T1 = h + Sigma1(e) + Ch(e, f, g) + K[t] + W[t];
UInt32 T2 = Sigma0(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
}
// 4. Compute the intermediate hash value H:
H[0] = a + H[0];
H[1] = b + H[1];
H[2] = c + H[2];
H[3] = d + H[3];
H[4] = e + H[4];
H[5] = f + H[5];
H[6] = g + H[6];
H[7] = h + H[7];
}
public void AddData(byte[] data, uint offset, uint len)
{
if (closed)
throw new InvalidOperationException("Adding data to a closed hasher.");
if (len == 0)
return;
bits_processed += len * 8;
while (len > 0)
{
uint amount_to_copy;
if (len < 64)
{
if (pending_block_off + len > 64)
amount_to_copy = 64 - pending_block_off;
else
amount_to_copy = len;
}
else
{
amount_to_copy = 64 - pending_block_off;
}
Array.Copy(data, offset, pending_block, pending_block_off, amount_to_copy);
len -= amount_to_copy;
offset += amount_to_copy;
pending_block_off += amount_to_copy;
if (pending_block_off == 64)
{
toUintArray(pending_block, uint_buffer);
processBlock(uint_buffer);
pending_block_off = 0;
}
}
}
public ReadOnlyCollection<byte> GetHash()
{
return toByteArray(GetHashUInt32());
}
public ReadOnlyCollection<UInt32> GetHashUInt32()
{
if (!closed)
{
UInt64 size_temp = bits_processed;
AddData(new byte[1] { 0x80 }, 0, 1);
uint available_space = 64 - pending_block_off;
if (available_space < 8)
available_space += 64;
// 0-initialized
byte[] padding = new byte[available_space];
// Insert lenght uint64
for (uint i = 1; i <= 8; ++i)
{
padding[padding.Length - i] = (byte)size_temp;
size_temp >>= 8;
}
getInitialPadding n = new getInitialPadding();
n.paddingcopy(padding);
AddData(padding, 0u, (uint)padding.Length);
Debug.Assert(pending_block_off == 0);
closed = true;
}
return Array.AsReadOnly(H);
}
private static void toUintArray(byte[] src, UInt32[] dest)
{
for (uint i = 0, j = 0; i < dest.Length; ++i, j += 4)
{
dest[i] = ((UInt32)src[j+0] << 24) | ((UInt32)src[j+1] << 16) | ((UInt32)src[j+2] << 8) | ((UInt32)src[j+3]);
}
}
private static ReadOnlyCollection<byte> toByteArray(ReadOnlyCollection<UInt32> src)
{
byte[] dest = new byte[src.Count * 4];
int pos = 0;
for (int i = 0; i < src.Count; ++i)
{
dest[pos++] = (byte)(src[i] >> 24);
dest[pos++] = (byte)(src[i] >> 16);
dest[pos++] = (byte)(src[i] >> 8);
dest[pos++] = (byte)(src[i]);
}
return Array.AsReadOnly(dest);
}
public static ReadOnlyCollection<byte> HashFile(Stream fs)
{
Sha256 sha = new Sha256();
byte[] buf = new byte[8196];
uint bytes_read;
do
{
bytes_read = (uint)fs.Read(buf, 0, buf.Length);
if (bytes_read == 0)
break;
sha.AddData(buf, 0, bytes_read);
}
while (bytes_read == 8196);
return sha.GetHash();
}
}
}
| 32.173913 | 125 | 0.48795 | [
"MIT"
] | aayush-makkad/Sha-256-Prevention-buffer- | Sha256.cs | 8,882 | C# |
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using System;
namespace Content.Shared.Traitor.Uplink
{
[Serializable, NetSerializable]
public class UplinkUpdateState : BoundUserInterfaceState
{
public UplinkAccountData Account;
public UplinkListingData[] Listings;
public UplinkUpdateState(UplinkAccountData account, UplinkListingData[] listings)
{
Account = account;
Listings = listings;
}
}
}
| 24.9 | 89 | 0.692771 | [
"MIT"
] | A-Box-12/space-station-14 | Content.Shared/Traitor/Uplink/UplinkUpdateState.cs | 498 | C# |
using System;
namespace A1._1_SortedList
{
public class Aluno
{
private string nome;
public string Nome
{
get { return nome; }
}
private int numeroMatricula;
public int NumeroMatricula
{
get { return numeroMatricula; }
}
public Aluno(String nome, int numeroMatricula)
{
this.nome = nome;
this.numeroMatricula = numeroMatricula;
}
public override string ToString()
{
return "[Aluno: " + this.nome + ", matricula: " + this.numeroMatricula + "]";
}
public override bool Equals(object obj)
{
Aluno outro = obj as Aluno;
if (outro == null)
{
return false;
}
return this.nome.Equals(outro.nome);
}
///<image url="$(ProjectDir)\Slides\image.png" scale=""/>
//importante: rapidez da busca depende do CÓDIGO DE DISPERSÃO!
public override int GetHashCode()
{
return this.nome.GetHashCode();
}
///obtendo o código de dispersão
///comparando código de dispersão de a1 e tonini
//IMPORTANTE!!
//Dois objetos que são iguais possuem o mesmo hash code.
//PORÉM, o contrário não é verdadeiro:
//Dois objetos com mesmo hash codes não são necessariamente iguais!
///<image url="$(ProjectDir)\Slides\image.png" scale=""/>
}
}
| 23.338462 | 89 | 0.535267 | [
"MIT"
] | karolinagb/SortedListEmCsharp | SortedListEmCsharp/SortedListEmCsharp/Aluno.cs | 1,532 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Owin;
// 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("SenDev.DashboardsDemo.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SenDev.DashboardsDemo.Web")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3d5900ae-111a-45be-96b3-d9e4606ca793")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: OwinStartup(typeof(SenDev.DashboardsDemo.Web.Startup))]
| 38.710526 | 84 | 0.755269 | [
"MIT"
] | AksenovArtem/SenDevXafDashboards | src/Demo/SenDev.DashboardsDemo.Web/Properties/AssemblyInfo.cs | 1,474 | C# |
using URF.Core.Abstractions.Services;
using EzApiCore.Data.Models;
public interface ICategoriesService : IService<Categories>
{
}
| 16.625 | 58 | 0.804511 | [
"MIT"
] | rvegajr/ez-api-urf-core | Src/EzApiCore.Services/ICategoriesService.cs | 135 | C# |
using System.Collections;
namespace EnvDTE
{
public interface LinkedWindows : IEnumerable
{
Window Parent { get; }
int Count { get; }
DTE DTE { get; }
Window Item(object index);
new IEnumerator GetEnumerator();
void Remove(Window Window);
void Add(Window Window);
}
}
| 21.125 | 48 | 0.591716 | [
"Apache-2.0"
] | JetBrains/JetBrains.EnvDTE | EnvDTE.Interfaces/LinkedWindows.cs | 340 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515
{
using static Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Extensions;
/// <summary>Properties of the event source.</summary>
public partial class EventSourceCommonProperties :
Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IEventSourceCommonProperties,
Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IEventSourceCommonPropertiesInternal,
Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.IValidates
{
/// <summary>
/// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IResourceProperties"
/// />
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IResourceProperties __resourceProperties = new Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.ResourceProperties();
/// <summary>Backing field for <see cref="TimestampPropertyName" /> property.</summary>
private string _timestampPropertyName;
/// <summary>
/// The event property that will be used as the event source's timestamp. If a value isn't specified for timestampPropertyName,
/// or if null or empty-string is specified, the event creation time will be used.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Origin(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.PropertyOrigin.Owned)]
public string TimestampPropertyName { get => this._timestampPropertyName; set => this._timestampPropertyName = value; }
/// <summary>Creates an new <see cref="EventSourceCommonProperties" /> instance.</summary>
public EventSourceCommonProperties()
{
}
/// <summary>Validates that this object meets the validation criteria.</summary>
/// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.IEventListener" /> instance that will receive validation
/// events.</param>
/// <returns>
/// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed.
/// </returns>
public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.IEventListener eventListener)
{
await eventListener.AssertNotNull(nameof(__resourceProperties), __resourceProperties);
await eventListener.AssertObjectIsValid(nameof(__resourceProperties), __resourceProperties);
}
}
/// Properties of the event source.
public partial interface IEventSourceCommonProperties :
Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.IJsonSerializable,
Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IResourceProperties
{
/// <summary>
/// The event property that will be used as the event source's timestamp. If a value isn't specified for timestampPropertyName,
/// or if null or empty-string is specified, the event creation time will be used.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The event property that will be used as the event source's timestamp. If a value isn't specified for timestampPropertyName, or if null or empty-string is specified, the event creation time will be used.",
SerializedName = @"timestampPropertyName",
PossibleTypes = new [] { typeof(string) })]
string TimestampPropertyName { get; set; }
}
/// Properties of the event source.
internal partial interface IEventSourceCommonPropertiesInternal :
Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IResourcePropertiesInternal
{
/// <summary>
/// The event property that will be used as the event source's timestamp. If a value isn't specified for timestampPropertyName,
/// or if null or empty-string is specified, the event creation time will be used.
/// </summary>
string TimestampPropertyName { get; set; }
}
} | 60.391892 | 231 | 0.711792 | [
"MIT"
] | 3quanfeng/azure-powershell | src/TimeSeriesInsights/generated/api/Models/Api20200515/EventSourceCommonProperties.cs | 4,396 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// ANTLR Version: 4.5.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from Hello.g4 by ANTLR 4.5.1
// Unreachable code detected
#pragma warning disable 0162
// The variable '...' is assigned but its value is never used
#pragma warning disable 0219
// Missing XML comment for publicly visible type or member '...'
#pragma warning disable 1591
using System;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using DFA = Antlr4.Runtime.Dfa.DFA;
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.5.1")]
[System.CLSCompliant(false)]
public partial class HelloParser : Parser {
public const int
T__0=1, ID=2, WS=3;
public const int
RULE_r = 0;
public static readonly string[] ruleNames = {
"r"
};
private static readonly string[] _LiteralNames = {
null, "'hello'"
};
private static readonly string[] _SymbolicNames = {
null, null, "ID", "WS"
};
public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames);
[NotNull]
public override IVocabulary Vocabulary
{
get
{
return DefaultVocabulary;
}
}
public override string GrammarFileName { get { return "Hello.g4"; } }
public override string[] RuleNames { get { return ruleNames; } }
public override string SerializedAtn { get { return _serializedATN; } }
public HelloParser(ITokenStream input)
: base(input)
{
Interpreter = new ParserATNSimulator(this,_ATN);
}
public partial class RContext : ParserRuleContext {
public IToken _ID;
public ITerminalNode ID() { return GetToken(HelloParser.ID, 0); }
public RContext(ParserRuleContext parent, int invokingState)
: base(parent, invokingState)
{
}
public override int RuleIndex { get { return RULE_r; } }
public override void EnterRule(IParseTreeListener listener) {
IHelloListener typedListener = listener as IHelloListener;
if (typedListener != null) typedListener.EnterR(this);
}
public override void ExitRule(IParseTreeListener listener) {
IHelloListener typedListener = listener as IHelloListener;
if (typedListener != null) typedListener.ExitR(this);
}
}
[RuleVersion(0)]
public RContext r() {
RContext _localctx = new RContext(Context, State);
EnterRule(_localctx, 0, RULE_r);
try {
EnterOuterAlt(_localctx, 1);
{
State = 2; Match(T__0);
State = 3; _localctx._ID = Match(ID);
UnityEngine.Debug.Log("Antlr say: Hello, " + (_localctx._ID!=null?_localctx._ID.Text:null));
}
}
catch (RecognitionException re) {
_localctx.exception = re;
ErrorHandler.ReportError(this, re);
ErrorHandler.Recover(this, re);
}
finally {
ExitRule();
}
return _localctx;
}
public static readonly string _serializedATN =
"\x3\x430\xD6D1\x8206\xAD2D\x4417\xAEF1\x8D80\xAADD\x3\x5\t\x4\x2\t\x2"+
"\x3\x2\x3\x2\x3\x2\x3\x2\x3\x2\x2\x2\x3\x2\x2\x2\a\x2\x4\x3\x2\x2\x2\x4"+
"\x5\a\x3\x2\x2\x5\x6\a\x4\x2\x2\x6\a\b\x2\x1\x2\a\x3\x3\x2\x2\x2\x2";
public static readonly ATN _ATN =
new ATNDeserializer().Deserialize(_serializedATN.ToCharArray());
}
| 29.57265 | 102 | 0.681792 | [
"MIT"
] | ivancanosa/AntlrExampleUnity | Assets/Grammars/Hello/HelloParser.cs | 3,460 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TT.Domain;
using TT.Domain.Entities.LocationLogs;
using TT.Domain.Exceptions;
using TT.Domain.Identity.Entities;
using TT.Domain.Players.Commands;
using TT.Domain.Players.Entities;
using TT.Domain.Procedures;
using TT.Domain.Statics;
using TT.Domain.TFEnergies.Entities;
using TT.Domain.ViewModels;
using TT.Tests.Builders.Identity;
using TT.Tests.Builders.Players;
using TT.Tests.Builders.TFEnergies;
namespace TT.Tests.Players.Commands
{
[TestFixture]
public class CleanseTests : TestBase
{
private BuffBox buffs;
[SetUp]
public void Init()
{
buffs = new BuffBox();
}
[Test]
public void should_cleanse_player()
{
var TFEnergies = new List<TFEnergy>
{
new TFEnergyBuilder().With(t => t.Amount, 50).BuildAndSave()
};
var stats = new List<Stat>
{
new StatBuilder().With(t => t.AchievementType, StatsProcedures.Stat__BusRides).With(t => t.Amount, 20).BuildAndSave()
};
var player = new PlayerBuilder()
.With(p => p.Id, 100)
.With(p => p.Health, 0)
.With(p => p.User, new UserBuilder()
.With(u => u.Stats, stats)
.With(u => u.Id, "bob")
.BuildAndSave())
.With(p => p.Location, LocationsStatics.STREET_200_MAIN_STREET)
.With(p => p.TFEnergies, TFEnergies)
.BuildAndSave();
Assert.That(() => DomainRegistry.Repository.Execute(new Cleanse {PlayerId = 100, Buffs = buffs}),
Throws.Nothing);
var playerLoaded = DataContext.AsQueryable<Player>().First();
Assert.That(playerLoaded.PlayerLogs.First().Message,
Is.EqualTo("You cleansed at Street: 200 Main Street."));
Assert.That(playerLoaded.Health, Is.EqualTo(150));
Assert.That(playerLoaded.LastActionTimestamp, Is.EqualTo(DateTime.UtcNow).Within(1).Seconds);
var locationLog = DataContext.AsQueryable<LocationLog>().First();
Assert.That(locationLog.dbLocationName, Is.EqualTo(player.Location));
Assert.That(locationLog.Message,
Is.EqualTo("<span class='playerCleansingNotification'>John Doe cleansed here.</span>"));
var stat = playerLoaded.User.Stats.FirstOrDefault(s => s.AchievementType == StatsProcedures.Stat__TimesCleansed);
Assert.That(stat, Is.Not.Null);
Assert.That(stat.Owner.Id, Is.EqualTo("bob"));
Assert.That(stat.Amount, Is.EqualTo(1));
}
[Test]
public void should_throw_exception_if_player_not_found()
{
new PlayerBuilder()
.With(p => p.Id, 100)
.BuildAndSave();
var cmd = new Cleanse { PlayerId = 3, Buffs = buffs};
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message.EqualTo("Player with ID '3' could not be found"));
}
[Test]
public void should_throw_exception_if_player_has_insufficient_AP()
{
new PlayerBuilder()
.With(p => p.Id, 100)
.With(p => p.ActionPoints, PvPStatics.CleanseCost - 1)
.BuildAndSave();
var cmd = new Cleanse { PlayerId = 100, Buffs = buffs };
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message
.EqualTo("You don't have enough action points to cleanse!"));
}
[Test]
public void should_throw_exception_if_player_not_animate()
{
new PlayerBuilder()
.With(p => p.Id, 100)
.With(p => p.Mobility, PvPStatics.MobilityInanimate)
.BuildAndSave();
var cmd = new Cleanse { PlayerId = 100, Buffs = buffs };
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message.EqualTo("You must be animate in order to cleanse!"));
}
[Test]
public void should_throw_exception_if_player_has_insufficient_mana()
{
new PlayerBuilder()
.With(p => p.Id, 100)
.With(p => p.Mana, PvPStatics.CleanseManaCost - 1)
.BuildAndSave();
var cmd = new Cleanse { PlayerId = 100, Buffs = buffs };
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message.EqualTo("You don't have enough mana to cleanse!"));
}
[Test]
public void should_throw_exception_if_player_has_cleansed_or_meditated_too_much()
{
new PlayerBuilder()
.With(p => p.Id, 100)
.With(p => p.CleansesMeditatesThisRound, PvPStatics.MaxCleansesMeditatesPerUpdate)
.BuildAndSave();
var cmd = new Cleanse { PlayerId = 100, Buffs = buffs };
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message
.EqualTo("You have cleansed and meditated the maximum number of times this update."));
}
[Test]
public void should_throw_exception_if_player_id_not_provided()
{
var cmd = new Cleanse { Buffs = buffs };
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message.EqualTo("Player ID is required!"));
}
[Test]
public void should_throw_exception_if_buffs_not_provided()
{
var cmd = new Cleanse { PlayerId = 100 };
Assert.That(() => Repository.Execute(cmd),
Throws.TypeOf<DomainException>().With.Message.EqualTo("Buffs are required!"));
}
[Test]
public void should_skip_AP_validation_for_bot()
{
var TFEnergies = new List<TFEnergy>
{
new TFEnergyBuilder().With(t => t.Amount, 50).BuildAndSave()
};
var stats = new List<Stat>
{
new StatBuilder().With(t => t.AchievementType, StatsProcedures.Stat__BusRides).BuildAndSave()
};
new PlayerBuilder()
.With(p => p.Id, 100)
.With(p => p.Level, 1)
.With(p => p.Health, 0)
.With(p => p.MaxHealth, 100)
.With(p => p.User, new UserBuilder()
.With(u => u.Stats, stats)
.With(u => u.Id, "bob")
.BuildAndSave())
.With(p => p.Mobility, PvPStatics.MobilityFull)
.With(p => p.ActionPoints, PvPStatics.CleanseCost -1)
.With(p => p.Mana, PvPStatics.CleanseManaCost - 1)
.With(p => p.CleansesMeditatesThisRound, PvPStatics.MaxCleansesMeditatesPerUpdate)
.With(p => p.Location, LocationsStatics.STREET_200_MAIN_STREET)
.With(p => p.TFEnergies, TFEnergies)
.BuildAndSave();
Assert.That(
() => DomainRegistry.Repository.Execute(new Cleanse {PlayerId = 100, Buffs = buffs, NoValidate = true}),
Throws.Nothing);
Assert.That(DataContext.AsQueryable<Player>().First().Health, Is.GreaterThan(0));
}
}
}
| 37.86 | 133 | 0.564184 | [
"MIT"
] | transformania/tt-game | src/TT.Tests/Players/Commands/CleanseTests.cs | 7,574 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class MethodCompiler : CSharpSymbolVisitor<TypeCompilationState, object>
{
private readonly CSharpCompilation _compilation;
private readonly bool _emittingPdb;
private readonly bool _emitTestCoverageData;
private readonly CancellationToken _cancellationToken;
private readonly DiagnosticBag _diagnostics;
private readonly bool _hasDeclarationErrors;
private readonly PEModuleBuilder _moduleBeingBuiltOpt; // Null if compiling for diagnostics
private readonly Predicate<Symbol> _filterOpt; // If not null, limit analysis to specific symbols
private readonly DebugDocumentProvider _debugDocumentProvider;
private readonly SynthesizedEntryPointSymbol.AsyncForwardEntryPoint _entryPointOpt;
//
// MethodCompiler employs concurrency by following flattened fork/join pattern.
//
// For every item that we want to compile in parallel a new task is forked.
// compileTaskQueue is used to track and observe all the tasks.
// Once compileTaskQueue is empty, we know that there are no more tasks (and no more can be created)
// and that means we are done compiling. WaitForWorkers ensures this condition.
//
// Note that while tasks may fork more tasks (nested types, lambdas, whatever else that may introduce more types),
// we do not want any child/parent relationship between spawned tasks and their creators.
// Creator has no real dependencies on the completion of its children and should finish and release any resources
// as soon as it can regardless of the tasks it may have spawned.
//
// Stack is used so that the wait would observe the most recently added task and have
// more chances to do inlined execution.
private ConcurrentStack<Task> _compilerTasks;
// This field tracks whether any bound method body had hasErrors set or whether any constant field had a bad value.
// We track it so that we can abort emission in the event that an error occurs without a corresponding diagnostic
// (e.g. if this module depends on a bad type or constant from another module).
// CONSIDER: instead of storing a flag, we could track the first member symbol with an error (to improve the diagnostic).
// NOTE: once the flag is set to true, it should never go back to false!!!
// Do not use this as a short-circuiting for stages that might produce diagnostics.
// That would make diagnostics to depend on the random order in which methods are compiled.
private bool _globalHasErrors;
private void SetGlobalErrorIfTrue(bool arg)
{
//NOTE: this is not a volatile write
// for correctness we need only single threaded consistency.
// Within a single task - if we have got an error it may not be safe to continue with some lowerings.
// It is ok if other tasks will see the change after some delay or does not observe at all.
// Such races are unavoidable and will just result in performing some work that is safe to do
// but may no longer be needed.
// The final Join of compiling tasks cannot happen without interlocked operations and that
// will ensure that any write of the flag is globally visible.
if (arg)
{
_globalHasErrors = true;
}
}
// Internal for testing only.
internal MethodCompiler(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool emitTestCoverageData, bool hasDeclarationErrors,
DiagnosticBag diagnostics, Predicate<Symbol> filterOpt, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt, CancellationToken cancellationToken)
{
Debug.Assert(compilation != null);
Debug.Assert(diagnostics != null);
_compilation = compilation;
_moduleBeingBuiltOpt = moduleBeingBuiltOpt;
_emittingPdb = emittingPdb;
_cancellationToken = cancellationToken;
_diagnostics = diagnostics;
_filterOpt = filterOpt;
_entryPointOpt = entryPointOpt;
_hasDeclarationErrors = hasDeclarationErrors;
SetGlobalErrorIfTrue(hasDeclarationErrors);
if (emittingPdb || emitTestCoverageData)
{
_debugDocumentProvider = (path, basePath) => moduleBeingBuiltOpt.DebugDocumentsBuilder.GetOrAddDebugDocument(path, basePath, CreateDebugDocumentForFile);
}
_emitTestCoverageData = emitTestCoverageData;
}
public static void CompileMethodBodies(
CSharpCompilation compilation,
PEModuleBuilder moduleBeingBuiltOpt,
bool emittingPdb,
bool emitTestCoverageData,
bool hasDeclarationErrors,
DiagnosticBag diagnostics,
Predicate<Symbol> filterOpt,
CancellationToken cancellationToken)
{
Debug.Assert(compilation != null);
Debug.Assert(diagnostics != null);
if (compilation.PreviousSubmission != null)
{
// In case there is a previous submission, we should ensure
// it has already created anonymous type/delegates templates
// NOTE: if there are any errors, we will pick up what was created anyway
compilation.PreviousSubmission.EnsureAnonymousTypeTemplates(cancellationToken);
// TODO: revise to use a loop instead of a recursion
}
MethodSymbol entryPoint = null;
if (filterOpt is null)
{
entryPoint = GetEntryPoint(compilation, moduleBeingBuiltOpt, hasDeclarationErrors, diagnostics, cancellationToken);
}
var methodCompiler = new MethodCompiler(
compilation,
moduleBeingBuiltOpt,
emittingPdb,
emitTestCoverageData,
hasDeclarationErrors,
diagnostics,
filterOpt,
entryPoint as SynthesizedEntryPointSymbol.AsyncForwardEntryPoint,
cancellationToken);
if (compilation.Options.ConcurrentBuild)
{
methodCompiler._compilerTasks = new ConcurrentStack<Task>();
}
// directly traverse global namespace (no point to defer this to async)
methodCompiler.CompileNamespace(compilation.SourceModule.GlobalNamespace);
methodCompiler.WaitForWorkers();
// compile additional and anonymous types if any
if (moduleBeingBuiltOpt != null)
{
var additionalTypes = moduleBeingBuiltOpt.GetAdditionalTopLevelTypes(diagnostics);
methodCompiler.CompileSynthesizedMethods(additionalTypes, diagnostics);
var embeddedTypes = moduleBeingBuiltOpt.GetEmbeddedTypes(diagnostics);
methodCompiler.CompileSynthesizedMethods(embeddedTypes, diagnostics);
// By this time we have processed all types reachable from module's global namespace
compilation.AnonymousTypeManager.AssignTemplatesNamesAndCompile(methodCompiler, moduleBeingBuiltOpt, diagnostics);
methodCompiler.WaitForWorkers();
var privateImplClass = moduleBeingBuiltOpt.PrivateImplClass;
if (privateImplClass != null)
{
// all threads that were adding methods must be finished now, we can freeze the class:
privateImplClass.Freeze();
methodCompiler.CompileSynthesizedMethods(privateImplClass, diagnostics);
}
}
// If we are trying to emit and there's an error without a corresponding diagnostic (e.g. because
// we depend on an invalid type or constant from another module), then explicitly add a diagnostic.
// This diagnostic is not very helpful to the user, but it will prevent us from emitting an invalid
// module or crashing.
if (moduleBeingBuiltOpt != null && (methodCompiler._globalHasErrors || moduleBeingBuiltOpt.SourceModule.HasBadAttributes) && !diagnostics.HasAnyErrors() && !hasDeclarationErrors)
{
diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Cci.INamedEntity)moduleBeingBuiltOpt).Name);
}
diagnostics.AddRange(compilation.AdditionalCodegenWarnings);
// we can get unused field warnings only if compiling whole compilation.
if (filterOpt == null)
{
WarnUnusedFields(compilation, diagnostics, cancellationToken);
if (moduleBeingBuiltOpt != null && entryPoint != null && compilation.Options.OutputKind.IsApplication())
{
moduleBeingBuiltOpt.SetPEEntryPoint(entryPoint, diagnostics);
}
}
}
// Returns the MethodSymbol for the assembly entrypoint. If the user has a Task returning main,
// this function returns the synthesized Main MethodSymbol.
private static MethodSymbol GetEntryPoint(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuilt, bool hasDeclarationErrors, DiagnosticBag diagnostics, CancellationToken cancellationToken)
{
var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(cancellationToken);
if (entryPointAndDiagnostics == null)
{
return null;
}
Debug.Assert(!entryPointAndDiagnostics.Diagnostics.IsDefault);
diagnostics.AddRange(entryPointAndDiagnostics.Diagnostics);
var entryPoint = entryPointAndDiagnostics.MethodSymbol;
if ((object)entryPoint == null)
{
Debug.Assert(entryPointAndDiagnostics.Diagnostics.HasAnyErrors() || !compilation.Options.Errors.IsDefaultOrEmpty);
return null;
}
// entryPoint can be a SynthesizedEntryPointSymbol if a script is being compiled.
SynthesizedEntryPointSymbol synthesizedEntryPoint = entryPoint as SynthesizedEntryPointSymbol;
if ((object)synthesizedEntryPoint == null)
{
var returnType = entryPoint.ReturnType;
if (returnType.IsGenericTaskType(compilation) || returnType.IsNonGenericTaskType(compilation))
{
synthesizedEntryPoint = new SynthesizedEntryPointSymbol.AsyncForwardEntryPoint(compilation, entryPoint.ContainingType, entryPoint);
entryPoint = synthesizedEntryPoint;
if ((object)moduleBeingBuilt != null)
{
moduleBeingBuilt.AddSynthesizedDefinition(entryPoint.ContainingType, synthesizedEntryPoint);
}
}
}
if (((object)synthesizedEntryPoint != null) &&
(moduleBeingBuilt != null) &&
!hasDeclarationErrors &&
!diagnostics.HasAnyErrors())
{
BoundStatement body = synthesizedEntryPoint.CreateBody(diagnostics);
if (body.HasErrors || diagnostics.HasAnyErrors())
{
return entryPoint;
}
var dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty;
VariableSlotAllocator lazyVariableSlotAllocator = null;
var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();
StateMachineTypeSymbol stateMachineTypeOpt = null;
const int methodOrdinal = -1;
var loweredBody = LowerBodyOrInitializer(
synthesizedEntryPoint,
methodOrdinal,
body,
null,
new TypeCompilationState(synthesizedEntryPoint.ContainingType, compilation, moduleBeingBuilt),
false,
null,
ref dynamicAnalysisSpans,
diagnostics,
ref lazyVariableSlotAllocator,
lambdaDebugInfoBuilder,
closureDebugInfoBuilder,
out stateMachineTypeOpt);
Debug.Assert((object)lazyVariableSlotAllocator == null);
Debug.Assert((object)stateMachineTypeOpt == null);
Debug.Assert(dynamicAnalysisSpans.IsEmpty);
Debug.Assert(lambdaDebugInfoBuilder.IsEmpty());
Debug.Assert(closureDebugInfoBuilder.IsEmpty());
lambdaDebugInfoBuilder.Free();
closureDebugInfoBuilder.Free();
var emittedBody = GenerateMethodBody(
moduleBeingBuilt,
synthesizedEntryPoint,
methodOrdinal,
loweredBody,
ImmutableArray<LambdaDebugInfo>.Empty,
ImmutableArray<ClosureDebugInfo>.Empty,
stateMachineTypeOpt: null,
variableSlotAllocatorOpt: null,
diagnostics: diagnostics,
debugDocumentProvider: null,
importChainOpt: null,
emittingPdb: false,
emitTestCoverageData: false,
dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty,
entryPointOpt: null);
moduleBeingBuilt.SetMethodBody(synthesizedEntryPoint, emittedBody);
}
return entryPoint;
}
private void WaitForWorkers()
{
var tasks = _compilerTasks;
if (tasks == null)
{
return;
}
Task curTask;
while (tasks.TryPop(out curTask))
{
curTask.GetAwaiter().GetResult();
}
}
private static void WarnUnusedFields(CSharpCompilation compilation, DiagnosticBag diagnostics, CancellationToken cancellationToken)
{
SourceAssemblySymbol assembly = (SourceAssemblySymbol)compilation.Assembly;
diagnostics.AddRange(assembly.GetUnusedFieldWarnings(cancellationToken));
}
public override object VisitNamespace(NamespaceSymbol symbol, TypeCompilationState arg)
{
if (!PassesFilter(_filterOpt, symbol))
{
return null;
}
arg = null; // do not use compilation state of outer type.
_cancellationToken.ThrowIfCancellationRequested();
if (_compilation.Options.ConcurrentBuild)
{
Task worker = CompileNamespaceAsTask(symbol);
_compilerTasks.Push(worker);
}
else
{
CompileNamespace(symbol);
}
return null;
}
private Task CompileNamespaceAsTask(NamespaceSymbol symbol)
{
return Task.Run(UICultureUtilities.WithCurrentUICulture(() =>
{
try
{
CompileNamespace(symbol);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}), _cancellationToken);
}
private void CompileNamespace(NamespaceSymbol symbol)
{
foreach (var s in symbol.GetMembersUnordered())
{
s.Accept(this, null);
}
}
public override object VisitNamedType(NamedTypeSymbol symbol, TypeCompilationState arg)
{
if (!PassesFilter(_filterOpt, symbol))
{
return null;
}
arg = null; // do not use compilation state of outer type.
_cancellationToken.ThrowIfCancellationRequested();
if (_compilation.Options.ConcurrentBuild)
{
Task worker = CompileNamedTypeAsTask(symbol);
_compilerTasks.Push(worker);
}
else
{
CompileNamedType(symbol);
}
return null;
}
private Task CompileNamedTypeAsTask(NamedTypeSymbol symbol)
{
return Task.Run(UICultureUtilities.WithCurrentUICulture(() =>
{
try
{
CompileNamedType(symbol);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}), _cancellationToken);
}
private void CompileNamedType(NamedTypeSymbol containingType)
{
var compilationState = new TypeCompilationState(containingType, _compilation, _moduleBeingBuiltOpt);
_cancellationToken.ThrowIfCancellationRequested();
// Find the constructor of a script class.
SynthesizedInstanceConstructor scriptCtor = null;
SynthesizedInteractiveInitializerMethod scriptInitializer = null;
SynthesizedEntryPointSymbol scriptEntryPoint = null;
int scriptCtorOrdinal = -1;
if (containingType.IsScriptClass)
{
// The field initializers of a script class could be arbitrary statements,
// including blocks. Field initializers containing blocks need to
// use a MethodBodySemanticModel to build up the appropriate tree of binders, and
// MethodBodySemanticModel requires an "owning" method. That's why we're digging out
// the constructor - it will own the field initializers.
scriptCtor = containingType.GetScriptConstructor();
scriptInitializer = containingType.GetScriptInitializer();
scriptEntryPoint = containingType.GetScriptEntryPoint();
Debug.Assert((object)scriptCtor != null);
Debug.Assert((object)scriptInitializer != null);
}
var synthesizedSubmissionFields = containingType.IsSubmissionClass ? new SynthesizedSubmissionFields(_compilation, containingType) : null;
var processedStaticInitializers = new Binder.ProcessedFieldInitializers();
var processedInstanceInitializers = new Binder.ProcessedFieldInitializers();
var sourceTypeSymbol = containingType as SourceMemberContainerTypeSymbol;
if ((object)sourceTypeSymbol != null)
{
_cancellationToken.ThrowIfCancellationRequested();
Binder.BindFieldInitializers(_compilation, scriptInitializer, sourceTypeSymbol.StaticInitializers, _diagnostics, ref processedStaticInitializers);
_cancellationToken.ThrowIfCancellationRequested();
Binder.BindFieldInitializers(_compilation, scriptInitializer, sourceTypeSymbol.InstanceInitializers, _diagnostics, ref processedInstanceInitializers);
if (compilationState.Emitting)
{
CompileSynthesizedExplicitImplementations(sourceTypeSymbol, compilationState);
}
}
// Indicates if a static constructor is in the member,
// so we can decide to synthesize a static constructor.
bool hasStaticConstructor = false;
var members = containingType.GetMembers();
for (int memberOrdinal = 0; memberOrdinal < members.Length; memberOrdinal++)
{
var member = members[memberOrdinal];
//When a filter is supplied, limit the compilation of members passing the filter.
if (!PassesFilter(_filterOpt, member))
{
continue;
}
switch (member.Kind)
{
case SymbolKind.NamedType:
member.Accept(this, compilationState);
break;
case SymbolKind.Method:
{
MethodSymbol method = (MethodSymbol)member;
if (method.IsScriptConstructor)
{
Debug.Assert(scriptCtorOrdinal == -1);
Debug.Assert((object)scriptCtor == method);
scriptCtorOrdinal = memberOrdinal;
continue;
}
if ((object)method == scriptEntryPoint)
{
continue;
}
if (IsFieldLikeEventAccessor(method))
{
continue;
}
if (method.IsPartialDefinition())
{
method = method.PartialImplementationPart;
if ((object)method == null)
{
continue;
}
}
Binder.ProcessedFieldInitializers processedInitializers =
(method.MethodKind == MethodKind.Constructor || method.IsScriptInitializer) ? processedInstanceInitializers :
method.MethodKind == MethodKind.StaticConstructor ? processedStaticInitializers :
default(Binder.ProcessedFieldInitializers);
CompileMethod(method, memberOrdinal, ref processedInitializers, synthesizedSubmissionFields, compilationState);
// Set a flag to indicate that a static constructor is created.
if (method.MethodKind == MethodKind.StaticConstructor)
{
hasStaticConstructor = true;
}
break;
}
case SymbolKind.Property:
{
SourcePropertySymbol sourceProperty = member as SourcePropertySymbol;
if ((object)sourceProperty != null && sourceProperty.IsSealed && compilationState.Emitting)
{
CompileSynthesizedSealedAccessors(sourceProperty, compilationState);
}
break;
}
case SymbolKind.Event:
{
SourceEventSymbol eventSymbol = member as SourceEventSymbol;
if ((object)eventSymbol != null && eventSymbol.HasAssociatedField && !eventSymbol.IsAbstract && compilationState.Emitting)
{
CompileFieldLikeEventAccessor(eventSymbol, isAddMethod: true);
CompileFieldLikeEventAccessor(eventSymbol, isAddMethod: false);
}
break;
}
case SymbolKind.Field:
{
SourceMemberFieldSymbol fieldSymbol = member as SourceMemberFieldSymbol;
if ((object)fieldSymbol != null)
{
if (fieldSymbol.IsConst)
{
// We check specifically for constant fields with bad values because they never result
// in bound nodes being inserted into method bodies (in which case, they would be covered
// by the method-level check).
ConstantValue constantValue = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
SetGlobalErrorIfTrue(constantValue == null || constantValue.IsBad);
}
if (fieldSymbol.IsFixedSizeBuffer && compilationState.Emitting)
{
// force the generation of implementation types for fixed-size buffers
TypeSymbol discarded = fieldSymbol.FixedImplementationType(compilationState.ModuleBuilderOpt);
}
}
break;
}
}
}
Debug.Assert(containingType.IsScriptClass == (scriptCtorOrdinal >= 0));
// process additional anonymous type members
if (AnonymousTypeManager.IsAnonymousTypeTemplate(containingType))
{
var processedInitializers = default(Binder.ProcessedFieldInitializers);
foreach (var method in AnonymousTypeManager.GetAnonymousTypeHiddenMethods(containingType))
{
CompileMethod(method, -1, ref processedInitializers, synthesizedSubmissionFields, compilationState);
}
}
// In the case there are field initializers but we haven't created an implicit static constructor (.cctor) for it,
// (since we may not add .cctor implicitly created for decimals into the symbol table)
// it is necessary for the compiler to generate the static constructor here if we are emitting.
if (_moduleBeingBuiltOpt != null && !hasStaticConstructor && !processedStaticInitializers.BoundInitializers.IsDefaultOrEmpty)
{
Debug.Assert(processedStaticInitializers.BoundInitializers.All((init) =>
(init.Kind == BoundKind.FieldEqualsValue) && !((BoundFieldEqualsValue)init).Field.IsMetadataConstant));
MethodSymbol method = new SynthesizedStaticConstructor(sourceTypeSymbol);
if (PassesFilter(_filterOpt, method))
{
CompileMethod(method, -1, ref processedStaticInitializers, synthesizedSubmissionFields, compilationState);
// If this method has been successfully built, we emit it.
if (_moduleBeingBuiltOpt.GetMethodBody(method) != null)
{
_moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, method);
}
}
}
// If there is no explicit or implicit .cctor and no static initializers, then report
// warnings for any static non-nullable fields. (If there is no .cctor, there
// shouldn't be any initializers but for robustness, we check both.)
if (!hasStaticConstructor &&
processedStaticInitializers.BoundInitializers.IsDefaultOrEmpty &&
_compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion())
{
switch (containingType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
UnassignedFieldsWalker.ReportUninitializedNonNullableReferenceTypeFields(
walkerOpt: null,
thisSlot: -1,
isStatic: true,
members,
getIsAssigned: (walker, slot, member) => false,
getSymbolForLocation: (walker, member) => member,
_diagnostics);
break;
}
}
// compile submission constructor last so that synthesized submission fields are collected from all script methods:
if (scriptCtor != null && compilationState.Emitting)
{
Debug.Assert(scriptCtorOrdinal >= 0);
var processedInitializers = new Binder.ProcessedFieldInitializers() { BoundInitializers = ImmutableArray<BoundInitializer>.Empty };
CompileMethod(scriptCtor, scriptCtorOrdinal, ref processedInitializers, synthesizedSubmissionFields, compilationState);
if (synthesizedSubmissionFields != null)
{
synthesizedSubmissionFields.AddToType(containingType, compilationState.ModuleBuilderOpt);
}
}
// Emit synthesized methods produced during lowering if any
if (_moduleBeingBuiltOpt != null)
{
CompileSynthesizedMethods(compilationState);
}
compilationState.Free();
}
private void CompileSynthesizedMethods(PrivateImplementationDetails privateImplClass, DiagnosticBag diagnostics)
{
Debug.Assert(_moduleBeingBuiltOpt != null);
var compilationState = new TypeCompilationState(null, _compilation, _moduleBeingBuiltOpt);
foreach (MethodSymbol method in privateImplClass.GetMethods(new EmitContext(_moduleBeingBuiltOpt, null, diagnostics, metadataOnly: false, includePrivateMembers: true)))
{
Debug.Assert(method.SynthesizesLoweredBoundBody);
method.GenerateMethodBody(compilationState, diagnostics);
}
CompileSynthesizedMethods(compilationState);
compilationState.Free();
}
private void CompileSynthesizedMethods(ImmutableArray<NamedTypeSymbol> additionalTypes, DiagnosticBag diagnostics)
{
foreach (var additionalType in additionalTypes)
{
var compilationState = new TypeCompilationState(additionalType, _compilation, _moduleBeingBuiltOpt);
foreach (var method in additionalType.GetMethodsToEmit())
{
method.GenerateMethodBody(compilationState, diagnostics);
}
if (!diagnostics.HasAnyErrors())
{
CompileSynthesizedMethods(compilationState);
}
compilationState.Free();
}
}
private void CompileSynthesizedMethods(TypeCompilationState compilationState)
{
Debug.Assert(_moduleBeingBuiltOpt != null);
Debug.Assert(compilationState.ModuleBuilderOpt == _moduleBeingBuiltOpt);
var synthesizedMethods = compilationState.SynthesizedMethods;
if (synthesizedMethods == null)
{
return;
}
var oldImportChain = compilationState.CurrentImportChain;
try
{
foreach (var methodWithBody in synthesizedMethods)
{
var importChain = methodWithBody.ImportChain;
compilationState.CurrentImportChain = importChain;
// We make sure that an asynchronous mutation to the diagnostic bag does not
// confuse the method body generator by making a fresh bag and then loading
// any diagnostics emitted into it back into the main diagnostic bag.
var diagnosticsThisMethod = DiagnosticBag.GetInstance();
var method = methodWithBody.Method;
var lambda = method as SynthesizedClosureMethod;
var variableSlotAllocatorOpt = ((object)lambda != null) ?
_moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(lambda, lambda.TopLevelMethod, diagnosticsThisMethod) :
_moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(method, method, diagnosticsThisMethod);
// Synthesized methods have no ordinal stored in custom debug information (only user-defined methods have ordinals).
// In case of async lambdas, which synthesize a state machine type during the following rewrite, the containing method has already been uniquely named,
// so there is no need to produce a unique method ordinal for the corresponding state machine type, whose name includes the (unique) containing method name.
const int methodOrdinal = -1;
MethodBody emittedBody = null;
try
{
// Local functions can be iterators as well as be async (lambdas can only be async), so we need to lower both iterators and async
IteratorStateMachine iteratorStateMachine;
BoundStatement loweredBody = IteratorRewriter.Rewrite(methodWithBody.Body, method, methodOrdinal, variableSlotAllocatorOpt, compilationState, diagnosticsThisMethod, out iteratorStateMachine);
StateMachineTypeSymbol stateMachine = iteratorStateMachine;
if (!loweredBody.HasErrors)
{
AsyncStateMachine asyncStateMachine;
loweredBody = AsyncRewriter.Rewrite(loweredBody, method, methodOrdinal, variableSlotAllocatorOpt, compilationState, diagnosticsThisMethod, out asyncStateMachine);
Debug.Assert((object)iteratorStateMachine == null || (object)asyncStateMachine == null);
stateMachine = stateMachine ?? asyncStateMachine;
}
if (!diagnosticsThisMethod.HasAnyErrors() && !_globalHasErrors)
{
emittedBody = GenerateMethodBody(
_moduleBeingBuiltOpt,
method,
methodOrdinal,
loweredBody,
ImmutableArray<LambdaDebugInfo>.Empty,
ImmutableArray<ClosureDebugInfo>.Empty,
stateMachine,
variableSlotAllocatorOpt,
diagnosticsThisMethod,
_debugDocumentProvider,
method.GenerateDebugInfo ? importChain : null,
emittingPdb: _emittingPdb,
emitTestCoverageData: _emitTestCoverageData,
dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty,
_entryPointOpt);
}
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(_diagnostics);
}
_diagnostics.AddRange(diagnosticsThisMethod);
diagnosticsThisMethod.Free();
// error while generating IL
if (emittedBody == null)
{
break;
}
_moduleBeingBuiltOpt.SetMethodBody(method, emittedBody);
}
}
finally
{
compilationState.CurrentImportChain = oldImportChain;
}
}
private static bool IsFieldLikeEventAccessor(MethodSymbol method)
{
Symbol associatedPropertyOrEvent = method.AssociatedSymbol;
return (object)associatedPropertyOrEvent != null &&
associatedPropertyOrEvent.Kind == SymbolKind.Event &&
((EventSymbol)associatedPropertyOrEvent).HasAssociatedField;
}
/// <summary>
/// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a
/// base type from another assembly) it is necessary for the compiler to generate explicit implementations for
/// some interface methods. They don't go in the symbol table, but if we are emitting, then we should
/// generate code for them.
/// </summary>
private void CompileSynthesizedExplicitImplementations(SourceMemberContainerTypeSymbol sourceTypeSymbol, TypeCompilationState compilationState)
{
// we are not generating any observable diagnostics here so it is ok to short-circuit on global errors.
if (!_globalHasErrors)
{
foreach (var synthesizedExplicitImpl in sourceTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken))
{
Debug.Assert(synthesizedExplicitImpl.SynthesizesLoweredBoundBody);
var discardedDiagnostics = DiagnosticBag.GetInstance();
synthesizedExplicitImpl.GenerateMethodBody(compilationState, discardedDiagnostics);
Debug.Assert(!discardedDiagnostics.HasAnyErrors());
discardedDiagnostics.Free();
_moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, synthesizedExplicitImpl);
}
}
}
private void CompileSynthesizedSealedAccessors(SourcePropertySymbol sourceProperty, TypeCompilationState compilationState)
{
SynthesizedSealedPropertyAccessor synthesizedAccessor = sourceProperty.SynthesizedSealedAccessorOpt;
// we are not generating any observable diagnostics here so it is ok to short-circuit on global errors.
if ((object)synthesizedAccessor != null && !_globalHasErrors)
{
Debug.Assert(synthesizedAccessor.SynthesizesLoweredBoundBody);
var discardedDiagnostics = DiagnosticBag.GetInstance();
synthesizedAccessor.GenerateMethodBody(compilationState, discardedDiagnostics);
Debug.Assert(!discardedDiagnostics.HasAnyErrors());
discardedDiagnostics.Free();
_moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceProperty.ContainingType, synthesizedAccessor);
}
}
private void CompileFieldLikeEventAccessor(SourceEventSymbol eventSymbol, bool isAddMethod)
{
MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
var diagnosticsThisMethod = DiagnosticBag.GetInstance();
try
{
BoundBlock boundBody = MethodBodySynthesizer.ConstructFieldLikeEventAccessorBody(eventSymbol, isAddMethod, _compilation, diagnosticsThisMethod);
var hasErrors = diagnosticsThisMethod.HasAnyErrors();
SetGlobalErrorIfTrue(hasErrors);
// we cannot rely on GlobalHasErrors since that can be changed concurrently by other methods compiling
// we however do not want to continue with generating method body if we have errors in this particular method - generating may crash
// or if had declaration errors - we will fail anyways, but if some types are bad enough, generating may produce duplicate errors about that.
if (!hasErrors && !_hasDeclarationErrors)
{
const int accessorOrdinal = -1;
MethodBody emittedBody = GenerateMethodBody(
_moduleBeingBuiltOpt,
accessor,
accessorOrdinal,
boundBody,
ImmutableArray<LambdaDebugInfo>.Empty,
ImmutableArray<ClosureDebugInfo>.Empty,
stateMachineTypeOpt: null,
variableSlotAllocatorOpt: null,
diagnostics: diagnosticsThisMethod,
debugDocumentProvider: _debugDocumentProvider,
importChainOpt: null,
emittingPdb: false,
emitTestCoverageData: _emitTestCoverageData,
dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty,
entryPointOpt: null);
_moduleBeingBuiltOpt.SetMethodBody(accessor, emittedBody);
// Definition is already in the symbol table, so don't call moduleBeingBuilt.AddCompilerGeneratedDefinition
}
}
finally
{
_diagnostics.AddRange(diagnosticsThisMethod);
diagnosticsThisMethod.Free();
}
}
public override object VisitMethod(MethodSymbol symbol, TypeCompilationState arg)
{
throw ExceptionUtilities.Unreachable;
}
public override object VisitProperty(PropertySymbol symbol, TypeCompilationState argument)
{
throw ExceptionUtilities.Unreachable;
}
public override object VisitEvent(EventSymbol symbol, TypeCompilationState argument)
{
throw ExceptionUtilities.Unreachable;
}
public override object VisitField(FieldSymbol symbol, TypeCompilationState argument)
{
throw ExceptionUtilities.Unreachable;
}
private void CompileMethod(
MethodSymbol methodSymbol,
int methodOrdinal,
ref Binder.ProcessedFieldInitializers processedInitializers,
SynthesizedSubmissionFields previousSubmissionFields,
TypeCompilationState compilationState)
{
_cancellationToken.ThrowIfCancellationRequested();
SourceMemberMethodSymbol sourceMethod = methodSymbol as SourceMemberMethodSymbol;
if (methodSymbol.IsAbstract)
{
if ((object)sourceMethod != null)
{
bool diagsWritten;
sourceMethod.SetDiagnostics(ImmutableArray<Diagnostic>.Empty, out diagsWritten);
if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && _compilation.EventQueue != null)
{
_compilation.SymbolDeclaredEvent(methodSymbol);
}
}
return;
}
// get cached diagnostics if not building and we have 'em
if (_moduleBeingBuiltOpt == null && (object)sourceMethod != null)
{
var cachedDiagnostics = sourceMethod.Diagnostics;
if (!cachedDiagnostics.IsDefault)
{
_diagnostics.AddRange(cachedDiagnostics);
return;
}
}
ImportChain oldImportChain = compilationState.CurrentImportChain;
// In order to avoid generating code for methods with errors, we create a diagnostic bag just for this method.
DiagnosticBag diagsForCurrentMethod = DiagnosticBag.GetInstance();
try
{
// if synthesized method returns its body in lowered form
if (methodSymbol.SynthesizesLoweredBoundBody)
{
if (_moduleBeingBuiltOpt != null)
{
methodSymbol.GenerateMethodBody(compilationState, diagsForCurrentMethod);
_diagnostics.AddRange(diagsForCurrentMethod);
}
return;
}
// no need to emit the default ctor, we are not emitting those
if (methodSymbol.IsDefaultValueTypeConstructor())
{
return;
}
bool includeInitializersInBody = false;
BoundBlock body;
bool originalBodyNested = false;
// initializers that have been analyzed but not yet lowered.
BoundStatementList analyzedInitializers = null;
MethodBodySemanticModel.InitialState forSemanticModel = default;
ImportChain importChain = null;
var hasTrailingExpression = false;
if (methodSymbol.IsScriptConstructor)
{
Debug.Assert(methodSymbol.IsImplicitlyDeclared);
body = new BoundBlock(methodSymbol.GetNonNullSyntaxNode(), ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty) { WasCompilerGenerated = true };
}
else if (methodSymbol.IsScriptInitializer)
{
Debug.Assert(methodSymbol.IsImplicitlyDeclared);
// rewrite top-level statements and script variable declarations to a list of statements and assignments, respectively:
var initializerStatements = InitializerRewriter.RewriteScriptInitializer(processedInitializers.BoundInitializers, (SynthesizedInteractiveInitializerMethod)methodSymbol, out hasTrailingExpression);
// the lowered script initializers should not be treated as initializers anymore but as a method body:
body = BoundBlock.SynthesizedNoLocals(initializerStatements.Syntax, initializerStatements.Statements);
var unusedDiagnostics = DiagnosticBag.GetInstance();
DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, initializerStatements, unusedDiagnostics, requireOutParamsAssigned: false);
DiagnosticsPass.IssueDiagnostics(_compilation, initializerStatements, unusedDiagnostics, methodSymbol);
unusedDiagnostics.Free();
}
else
{
// Do not emit initializers if we are invoking another constructor of this class.
includeInitializersInBody = !processedInitializers.BoundInitializers.IsDefaultOrEmpty &&
!HasThisConstructorInitializer(methodSymbol);
body = BindMethodBody(methodSymbol, compilationState, diagsForCurrentMethod, out importChain, out originalBodyNested, out forSemanticModel);
if (diagsForCurrentMethod.HasAnyErrors() && body != null)
{
body = (BoundBlock)body.WithHasErrors();
}
if (body != null && methodSymbol.IsConstructor())
{
UnassignedFieldsWalker.Analyze(_compilation, methodSymbol, body, diagsForCurrentMethod);
}
// lower initializers just once. the lowered tree will be reused when emitting all constructors
// with field initializers. Once lowered, these initializers will be stashed in processedInitializers.LoweredInitializers
// (see later in this method). Don't bother lowering _now_ if this particular ctor won't have the initializers
// appended to its body.
if (includeInitializersInBody && processedInitializers.LoweredInitializers == null)
{
analyzedInitializers = InitializerRewriter.RewriteConstructor(processedInitializers.BoundInitializers, methodSymbol);
processedInitializers.HasErrors = processedInitializers.HasErrors || analyzedInitializers.HasAnyErrors;
if (body != null && ((methodSymbol.ContainingType.IsStructType() && !methodSymbol.IsImplicitConstructor) || _emitTestCoverageData))
{
if (_emitTestCoverageData && methodSymbol.IsImplicitConstructor)
{
// Flow analysis over the initializers is necessary in order to find assignments to fields.
// Bodies of implicit constructors do not get flow analysis later, so the initializers
// are analyzed here.
DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, analyzedInitializers, diagsForCurrentMethod, requireOutParamsAssigned: false);
}
// In order to get correct diagnostics, we need to analyze initializers and the body together.
body = body.Update(body.Locals, body.LocalFunctions, body.Statements.Insert(0, analyzedInitializers));
includeInitializersInBody = false;
analyzedInitializers = null;
}
else
{
// These analyses check for diagnostics in lambdas.
// Control flow analysis and implicit return insertion are unnecessary.
DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, analyzedInitializers, diagsForCurrentMethod, requireOutParamsAssigned: false);
DiagnosticsPass.IssueDiagnostics(_compilation, analyzedInitializers, diagsForCurrentMethod, methodSymbol);
}
}
}
#if DEBUG
// If the method is a synthesized static or instance constructor, then debugImports will be null and we will use the value
// from the first field initializer.
if ((methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.StaticConstructor) &&
methodSymbol.IsImplicitlyDeclared && body == null)
{
// There was no body to bind, so we didn't get anything from BindMethodBody.
Debug.Assert(importChain == null);
}
// Either there were no field initializers or we grabbed debug imports from the first one.
Debug.Assert(processedInitializers.BoundInitializers.IsDefaultOrEmpty || processedInitializers.FirstImportChain != null);
#endif
importChain = importChain ?? processedInitializers.FirstImportChain;
// Associate these debug imports with all methods generated from this one.
compilationState.CurrentImportChain = importChain;
if (body != null)
{
DiagnosticsPass.IssueDiagnostics(_compilation, body, diagsForCurrentMethod, methodSymbol);
}
BoundBlock flowAnalyzedBody = null;
if (body != null)
{
flowAnalyzedBody = FlowAnalysisPass.Rewrite(methodSymbol, body, diagsForCurrentMethod, hasTrailingExpression: hasTrailingExpression, originalBodyNested: originalBodyNested);
}
bool hasErrors = _hasDeclarationErrors || diagsForCurrentMethod.HasAnyErrors() || processedInitializers.HasErrors;
// Record whether or not the bound tree for the lowered method body (including any initializers) contained any
// errors (note: errors, not diagnostics).
SetGlobalErrorIfTrue(hasErrors);
bool diagsWritten = false;
var actualDiagnostics = diagsForCurrentMethod.ToReadOnly();
if (sourceMethod != null)
{
actualDiagnostics = sourceMethod.SetDiagnostics(actualDiagnostics, out diagsWritten);
}
if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && _compilation.EventQueue != null)
{
Lazy<SemanticModel> lazySemanticModel = null;
if (body != null)
{
lazySemanticModel = new Lazy<SemanticModel>(() =>
{
var syntax = body.Syntax;
var semanticModel = (SyntaxTreeSemanticModel)_compilation.GetSemanticModel(syntax.SyntaxTree);
if (forSemanticModel.Syntax is { } semanticModelSyntax)
{
semanticModel.GetOrAddModel(semanticModelSyntax,
(rootSyntax) =>
{
Debug.Assert(rootSyntax == forSemanticModel.Syntax);
return MethodBodySemanticModel.Create(semanticModel,
methodSymbol,
forSemanticModel);
});
}
return semanticModel;
});
}
_compilation.EventQueue.TryEnqueue(new SymbolDeclaredCompilationEvent(_compilation, methodSymbol.GetPublicSymbol(), lazySemanticModel));
}
// Don't lower if we're not emitting or if there were errors.
// Methods that had binding errors are considered too broken to be lowered reliably.
if (_moduleBeingBuiltOpt == null || hasErrors)
{
_diagnostics.AddRange(actualDiagnostics);
return;
}
// ############################
// LOWERING AND EMIT
// Any errors generated below here are considered Emit diagnostics
// and will not be reported to callers Compilation.GetDiagnostics()
ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty;
bool hasBody = flowAnalyzedBody != null;
VariableSlotAllocator lazyVariableSlotAllocator = null;
StateMachineTypeSymbol stateMachineTypeOpt = null;
var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();
BoundStatement loweredBodyOpt = null;
try
{
if (hasBody)
{
loweredBodyOpt = LowerBodyOrInitializer(
methodSymbol,
methodOrdinal,
flowAnalyzedBody,
previousSubmissionFields,
compilationState,
_emitTestCoverageData,
_debugDocumentProvider,
ref dynamicAnalysisSpans,
diagsForCurrentMethod,
ref lazyVariableSlotAllocator,
lambdaDebugInfoBuilder,
closureDebugInfoBuilder,
out stateMachineTypeOpt);
Debug.Assert(loweredBodyOpt != null);
}
else
{
loweredBodyOpt = null;
}
hasErrors = hasErrors || (hasBody && loweredBodyOpt.HasErrors) || diagsForCurrentMethod.HasAnyErrors();
SetGlobalErrorIfTrue(hasErrors);
// don't emit if the resulting method would contain initializers with errors
if (!hasErrors && (hasBody || includeInitializersInBody))
{
Debug.Assert(!methodSymbol.IsImplicitInstanceConstructor || !methodSymbol.ContainingType.IsStructType());
// Fields must be initialized before constructor initializer (which is the first statement of the analyzed body, if specified),
// so that the initialization occurs before any method overridden by the declaring class can be invoked from the base constructor
// and access the fields.
ImmutableArray<BoundStatement> boundStatements;
if (methodSymbol.IsScriptConstructor)
{
boundStatements = MethodBodySynthesizer.ConstructScriptConstructorBody(loweredBodyOpt, methodSymbol, previousSubmissionFields, _compilation);
}
else
{
boundStatements = ImmutableArray<BoundStatement>.Empty;
if (analyzedInitializers != null)
{
// For dynamic analysis, field initializers are instrumented as part of constructors,
// and so are never instrumented here.
Debug.Assert(!_emitTestCoverageData);
StateMachineTypeSymbol initializerStateMachineTypeOpt;
BoundStatement lowered = LowerBodyOrInitializer(
methodSymbol,
methodOrdinal,
analyzedInitializers,
previousSubmissionFields,
compilationState,
_emitTestCoverageData,
_debugDocumentProvider,
ref dynamicAnalysisSpans,
diagsForCurrentMethod,
ref lazyVariableSlotAllocator,
lambdaDebugInfoBuilder,
closureDebugInfoBuilder,
out initializerStateMachineTypeOpt);
processedInitializers.LoweredInitializers = lowered;
// initializers can't produce state machines
Debug.Assert((object)initializerStateMachineTypeOpt == null);
Debug.Assert(!hasErrors);
hasErrors = lowered.HasAnyErrors || diagsForCurrentMethod.HasAnyErrors();
SetGlobalErrorIfTrue(hasErrors);
if (hasErrors)
{
_diagnostics.AddRange(diagsForCurrentMethod);
return;
}
// Only do the cast if we haven't returned with some error diagnostics.
// Otherwise, `lowered` might have been a BoundBadStatement.
processedInitializers.LoweredInitializers = (BoundStatementList)lowered;
}
// initializers for global code have already been included in the body
if (includeInitializersInBody)
{
if (processedInitializers.LoweredInitializers.Kind == BoundKind.StatementList)
{
BoundStatementList lowered = (BoundStatementList)processedInitializers.LoweredInitializers;
boundStatements = boundStatements.Concat(lowered.Statements);
}
else
{
boundStatements = boundStatements.Add(processedInitializers.LoweredInitializers);
}
}
if (hasBody)
{
boundStatements = boundStatements.Concat(ImmutableArray.Create(loweredBodyOpt));
}
}
CSharpSyntaxNode syntax = methodSymbol.GetNonNullSyntaxNode();
var boundBody = BoundStatementList.Synthesized(syntax, boundStatements);
var emittedBody = GenerateMethodBody(
_moduleBeingBuiltOpt,
methodSymbol,
methodOrdinal,
boundBody,
lambdaDebugInfoBuilder.ToImmutable(),
closureDebugInfoBuilder.ToImmutable(),
stateMachineTypeOpt,
lazyVariableSlotAllocator,
diagsForCurrentMethod,
_debugDocumentProvider,
importChain,
_emittingPdb,
_emitTestCoverageData,
dynamicAnalysisSpans,
entryPointOpt: null);
_moduleBeingBuiltOpt.SetMethodBody(methodSymbol.PartialDefinitionPart ?? methodSymbol, emittedBody);
}
_diagnostics.AddRange(diagsForCurrentMethod);
}
finally
{
lambdaDebugInfoBuilder.Free();
closureDebugInfoBuilder.Free();
}
}
finally
{
diagsForCurrentMethod.Free();
compilationState.CurrentImportChain = oldImportChain;
}
}
// internal for testing
internal static BoundStatement LowerBodyOrInitializer(
MethodSymbol method,
int methodOrdinal,
BoundStatement body,
SynthesizedSubmissionFields previousSubmissionFields,
TypeCompilationState compilationState,
bool instrumentForDynamicAnalysis,
DebugDocumentProvider debugDocumentProvider,
ref ImmutableArray<SourceSpan> dynamicAnalysisSpans,
DiagnosticBag diagnostics,
ref VariableSlotAllocator lazyVariableSlotAllocator,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
out StateMachineTypeSymbol stateMachineTypeOpt)
{
Debug.Assert(compilationState.ModuleBuilderOpt != null);
stateMachineTypeOpt = null;
if (body.HasErrors)
{
return body;
}
try
{
var loweredBody = LocalRewriter.Rewrite(
method.DeclaringCompilation,
method,
methodOrdinal,
method.ContainingType,
body,
compilationState,
previousSubmissionFields: previousSubmissionFields,
allowOmissionOfConditionalCalls: true,
instrumentForDynamicAnalysis: instrumentForDynamicAnalysis,
debugDocumentProvider: debugDocumentProvider,
dynamicAnalysisSpans: ref dynamicAnalysisSpans,
diagnostics: diagnostics,
sawLambdas: out bool sawLambdas,
sawLocalFunctions: out bool sawLocalFunctions,
sawAwaitInExceptionHandler: out bool sawAwaitInExceptionHandler);
if (loweredBody.HasErrors)
{
return loweredBody;
}
if (sawAwaitInExceptionHandler)
{
// If we have awaits in handlers, we need to
// replace handlers with synthetic ones which can be consumed by async rewriter.
// The reason why this rewrite happens before the lambda rewrite
// is that we may need access to exception locals and it would be fairly hard to do
// if these locals are captured into closures (possibly nested ones).
loweredBody = AsyncExceptionHandlerRewriter.Rewrite(
method,
method.ContainingType,
loweredBody,
compilationState,
diagnostics);
}
if (loweredBody.HasErrors)
{
return loweredBody;
}
if (lazyVariableSlotAllocator == null)
{
lazyVariableSlotAllocator = compilationState.ModuleBuilderOpt.TryCreateVariableSlotAllocator(method, method, diagnostics);
}
BoundStatement bodyWithoutLambdas = loweredBody;
if (sawLambdas || sawLocalFunctions)
{
bodyWithoutLambdas = LambdaRewriter.Rewrite(
loweredBody,
method.ContainingType,
method.ThisParameter,
method,
methodOrdinal,
null,
lambdaDebugInfoBuilder,
closureDebugInfoBuilder,
lazyVariableSlotAllocator,
compilationState,
diagnostics,
assignLocals: null);
}
if (bodyWithoutLambdas.HasErrors)
{
return bodyWithoutLambdas;
}
BoundStatement bodyWithoutIterators = IteratorRewriter.Rewrite(bodyWithoutLambdas, method, methodOrdinal, lazyVariableSlotAllocator, compilationState, diagnostics,
out IteratorStateMachine iteratorStateMachine);
if (bodyWithoutIterators.HasErrors)
{
return bodyWithoutIterators;
}
BoundStatement bodyWithoutAsync = AsyncRewriter.Rewrite(bodyWithoutIterators, method, methodOrdinal, lazyVariableSlotAllocator, compilationState, diagnostics,
out AsyncStateMachine asyncStateMachine);
Debug.Assert((object)iteratorStateMachine == null || (object)asyncStateMachine == null);
stateMachineTypeOpt = (StateMachineTypeSymbol)iteratorStateMachine ?? asyncStateMachine;
return bodyWithoutAsync;
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
return new BoundBadStatement(body.Syntax, ImmutableArray.Create<BoundNode>(body), hasErrors: true);
}
}
/// <summary>
/// entryPointOpt is only considered for synthesized methods (to recognize the synthesized MoveNext method for async Main)
/// </summary>
private static MethodBody GenerateMethodBody(
PEModuleBuilder moduleBuilder,
MethodSymbol method,
int methodOrdinal,
BoundStatement block,
ImmutableArray<LambdaDebugInfo> lambdaDebugInfo,
ImmutableArray<ClosureDebugInfo> closureDebugInfo,
StateMachineTypeSymbol stateMachineTypeOpt,
VariableSlotAllocator variableSlotAllocatorOpt,
DiagnosticBag diagnostics,
DebugDocumentProvider debugDocumentProvider,
ImportChain importChainOpt,
bool emittingPdb,
bool emitTestCoverageData,
ImmutableArray<SourceSpan> dynamicAnalysisSpans,
SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt)
{
// Note: don't call diagnostics.HasAnyErrors() in release; could be expensive if compilation has many warnings.
Debug.Assert(!diagnostics.HasAnyErrors(), "Running code generator when errors exist might be dangerous; code generator not expecting errors");
var compilation = moduleBuilder.Compilation;
var localSlotManager = new LocalSlotManager(variableSlotAllocatorOpt);
var optimizations = compilation.Options.OptimizationLevel;
ILBuilder builder = new ILBuilder(moduleBuilder, localSlotManager, optimizations);
DiagnosticBag diagnosticsForThisMethod = DiagnosticBag.GetInstance();
try
{
StateMachineMoveNextBodyDebugInfo moveNextBodyDebugInfoOpt = null;
var codeGen = new CodeGen.CodeGenerator(method, block, builder, moduleBuilder, diagnosticsForThisMethod, optimizations, emittingPdb);
if (diagnosticsForThisMethod.HasAnyErrors())
{
// we are done here. Since there were errors we should not emit anything.
return null;
}
bool isAsyncStateMachine;
MethodSymbol kickoffMethod;
if (method is SynthesizedStateMachineMethod stateMachineMethod &&
method.Name == WellKnownMemberNames.MoveNextMethodName)
{
kickoffMethod = stateMachineMethod.StateMachineType.KickoffMethod;
Debug.Assert(kickoffMethod != null);
isAsyncStateMachine = kickoffMethod.IsAsync;
// Async void method may be partial. Debug info needs to be associated with the emitted definition,
// but the kickoff method is the method implementation (the part with body).
kickoffMethod = kickoffMethod.PartialDefinitionPart ?? kickoffMethod;
}
else
{
kickoffMethod = null;
isAsyncStateMachine = false;
}
if (isAsyncStateMachine)
{
codeGen.Generate(out int asyncCatchHandlerOffset, out var asyncYieldPoints, out var asyncResumePoints);
// The exception handler IL offset is used by the debugger to treat exceptions caught by the marked catch block as "user unhandled".
// This is important for async void because async void exceptions generally result in the process being terminated,
// but without anything useful on the call stack. Async Task methods on the other hand return exceptions as the result of the Task.
// So it is undesirable to consider these exceptions "user unhandled" since there may well be user code that is awaiting the task.
// This is a heuristic since it's possible that there is no user code awaiting the task.
// We do the same for async Main methods, since it is unlikely that user code will be awaiting the Task:
// AsyncForwardEntryPoint <Main> -> kick-off method Main -> MoveNext.
bool isAsyncMainMoveNext = entryPointOpt?.UserMain.Equals(kickoffMethod) == true;
moveNextBodyDebugInfoOpt = new AsyncMoveNextBodyDebugInfo(
kickoffMethod,
catchHandlerOffset: (kickoffMethod.ReturnsVoid || isAsyncMainMoveNext) ? asyncCatchHandlerOffset : -1,
asyncYieldPoints,
asyncResumePoints);
}
else
{
codeGen.Generate();
if ((object)kickoffMethod != null)
{
moveNextBodyDebugInfoOpt = new IteratorMoveNextBodyDebugInfo(kickoffMethod);
}
}
// Compiler-generated MoveNext methods have hoisted local scopes.
// These are built by call to CodeGen.Generate.
var stateMachineHoistedLocalScopes = ((object)kickoffMethod != null) ?
builder.GetHoistedLocalScopes() : default(ImmutableArray<StateMachineHoistedLocalScope>);
// Translate the imports even if we are not writing PDBs. The translation has an impact on generated metadata
// and we don't want to emit different metadata depending on whether or we emit with PDB stream.
// TODO (https://github.com/dotnet/roslyn/issues/2846): This will need to change for member initializers in partial class.
var importScopeOpt = importChainOpt?.Translate(moduleBuilder, diagnosticsForThisMethod);
var localVariables = builder.LocalSlotManager.LocalsInOrder();
if (localVariables.Length > 0xFFFE)
{
diagnosticsForThisMethod.Add(ErrorCode.ERR_TooManyLocals, method.Locations.First());
}
if (diagnosticsForThisMethod.HasAnyErrors())
{
// we are done here. Since there were errors we should not emit anything.
return null;
}
// We will only save the IL builders when running tests.
if (moduleBuilder.SaveTestData)
{
moduleBuilder.SetMethodTestData(method, builder.GetSnapshot());
}
var stateMachineHoistedLocalSlots = default(ImmutableArray<EncHoistedLocalInfo>);
var stateMachineAwaiterSlots = default(ImmutableArray<Cci.ITypeReference>);
if (optimizations == OptimizationLevel.Debug && (object)stateMachineTypeOpt != null)
{
Debug.Assert(method.IsAsync || method.IsIterator);
GetStateMachineSlotDebugInfo(moduleBuilder, moduleBuilder.GetSynthesizedFields(stateMachineTypeOpt), variableSlotAllocatorOpt, diagnosticsForThisMethod, out stateMachineHoistedLocalSlots, out stateMachineAwaiterSlots);
Debug.Assert(!diagnostics.HasAnyErrors());
}
DynamicAnalysisMethodBodyData dynamicAnalysisDataOpt = null;
if (emitTestCoverageData)
{
Debug.Assert(debugDocumentProvider != null);
dynamicAnalysisDataOpt = new DynamicAnalysisMethodBodyData(dynamicAnalysisSpans);
}
return new MethodBody(
builder.RealizedIL,
builder.MaxStack,
method.PartialDefinitionPart ?? method,
variableSlotAllocatorOpt?.MethodId ?? new DebugId(methodOrdinal, moduleBuilder.CurrentGenerationOrdinal),
localVariables,
builder.RealizedSequencePoints,
debugDocumentProvider,
builder.RealizedExceptionHandlers,
builder.GetAllScopes(),
builder.HasDynamicLocal,
importScopeOpt,
lambdaDebugInfo,
closureDebugInfo,
stateMachineTypeOpt?.Name,
stateMachineHoistedLocalScopes,
stateMachineHoistedLocalSlots,
stateMachineAwaiterSlots,
moveNextBodyDebugInfoOpt,
dynamicAnalysisDataOpt);
}
finally
{
// Basic blocks contain poolable builders for IL and sequence points. Free those back
// to their pools.
builder.FreeBasicBlocks();
// Remember diagnostics.
diagnostics.AddRange(diagnosticsForThisMethod);
diagnosticsForThisMethod.Free();
}
}
private static void GetStateMachineSlotDebugInfo(
PEModuleBuilder moduleBuilder,
IEnumerable<Cci.IFieldDefinition> fieldDefs,
VariableSlotAllocator variableSlotAllocatorOpt,
DiagnosticBag diagnostics,
out ImmutableArray<EncHoistedLocalInfo> hoistedVariableSlots,
out ImmutableArray<Cci.ITypeReference> awaiterSlots)
{
var hoistedVariables = ArrayBuilder<EncHoistedLocalInfo>.GetInstance();
var awaiters = ArrayBuilder<Cci.ITypeReference>.GetInstance();
foreach (StateMachineFieldSymbol field in fieldDefs)
{
int index = field.SlotIndex;
if (field.SlotDebugInfo.SynthesizedKind == SynthesizedLocalKind.AwaiterField)
{
Debug.Assert(index >= 0);
while (index >= awaiters.Count)
{
awaiters.Add(null);
}
awaiters[index] = moduleBuilder.EncTranslateLocalVariableType(field.Type, diagnostics);
}
else if (!field.SlotDebugInfo.Id.IsNone)
{
Debug.Assert(index >= 0 && field.SlotDebugInfo.SynthesizedKind.IsLongLived());
while (index >= hoistedVariables.Count)
{
// Empty slots may be present if variables were deleted during EnC.
hoistedVariables.Add(new EncHoistedLocalInfo(true));
}
hoistedVariables[index] = new EncHoistedLocalInfo(field.SlotDebugInfo, moduleBuilder.EncTranslateLocalVariableType(field.Type, diagnostics));
}
}
// Fill in empty slots for variables deleted during EnC that are not followed by an existing variable:
if (variableSlotAllocatorOpt != null)
{
int previousAwaiterCount = variableSlotAllocatorOpt.PreviousAwaiterSlotCount;
while (awaiters.Count < previousAwaiterCount)
{
awaiters.Add(null);
}
int previousAwaiterSlotCount = variableSlotAllocatorOpt.PreviousHoistedLocalSlotCount;
while (hoistedVariables.Count < previousAwaiterSlotCount)
{
hoistedVariables.Add(new EncHoistedLocalInfo(true));
}
}
hoistedVariableSlots = hoistedVariables.ToImmutableAndFree();
awaiterSlots = awaiters.ToImmutableAndFree();
}
// NOTE: can return null if the method has no body.
internal static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
return BindMethodBody(method, compilationState, diagnostics, out _, out _, out _);
}
// NOTE: can return null if the method has no body.
private static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, DiagnosticBag diagnostics,
out ImportChain importChain, out bool originalBodyNested,
out MethodBodySemanticModel.InitialState forSemanticModel)
{
originalBodyNested = false;
importChain = null;
forSemanticModel = default;
BoundBlock body;
var sourceMethod = method as SourceMemberMethodSymbol;
if ((object)sourceMethod != null)
{
CSharpSyntaxNode syntaxNode = sourceMethod.SyntaxNode;
var constructorSyntax = syntaxNode as ConstructorDeclarationSyntax;
// Static constructor can't have any this/base call
if (method.MethodKind == MethodKind.StaticConstructor &&
constructorSyntax?.Initializer != null)
{
diagnostics.Add(
ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall,
constructorSyntax.Initializer.ThisOrBaseKeyword.GetLocation(),
constructorSyntax.Identifier.ValueText);
}
ExecutableCodeBinder bodyBinder = sourceMethod.TryGetBodyBinder();
if (sourceMethod.IsExtern)
{
if (bodyBinder == null)
{
// Generate warnings only if we are not generating ERR_ExternHasBody or ERR_ExternHasConstructorInitializer errors
GenerateExternalMethodWarnings(sourceMethod, diagnostics);
}
return null;
}
if (sourceMethod.IsDefaultValueTypeConstructor())
{
// No body for default struct constructor.
return null;
}
if (bodyBinder != null)
{
importChain = bodyBinder.ImportChain;
bodyBinder.ValidateIteratorMethods(diagnostics);
BoundNode methodBody = bodyBinder.BindMethodBody(syntaxNode, diagnostics);
BoundNode methodBodyForSemanticModel = methodBody;
NullableWalker.SnapshotManager snapshotManager = null;
ImmutableDictionary<Symbol, Symbol> remappedSymbols = null;
if (bodyBinder.Compilation.NullableSemanticAnalysisEnabled)
{
// Currently, we're passing an empty DiagnosticBag here because the flow analysis pass later will
// also run the nullable walker, and issue duplicate warnings. We should try to only run the pass
// once.
// https://github.com/dotnet/roslyn/issues/35041
methodBodyForSemanticModel = NullableWalker.AnalyzeAndRewrite(bodyBinder.Compilation, method, methodBody, bodyBinder, new DiagnosticBag(), createSnapshots: true, out snapshotManager, ref remappedSymbols);
}
forSemanticModel = new MethodBodySemanticModel.InitialState(syntaxNode, methodBodyForSemanticModel, bodyBinder, snapshotManager, remappedSymbols);
switch (methodBody.Kind)
{
case BoundKind.ConstructorMethodBody:
var constructor = (BoundConstructorMethodBody)methodBody;
body = constructor.BlockBody ?? constructor.ExpressionBody;
if (constructor.Initializer != null)
{
ReportCtorInitializerCycles(method, constructor.Initializer.Expression, compilationState, diagnostics);
if (body == null)
{
body = new BoundBlock(constructor.Syntax, constructor.Locals, ImmutableArray.Create<BoundStatement>(constructor.Initializer));
}
else
{
body = new BoundBlock(constructor.Syntax, constructor.Locals, ImmutableArray.Create<BoundStatement>(constructor.Initializer, body));
originalBodyNested = true;
}
return body;
}
else
{
Debug.Assert(constructor.Locals.IsEmpty);
}
break;
case BoundKind.NonConstructorMethodBody:
var nonConstructor = (BoundNonConstructorMethodBody)methodBody;
body = nonConstructor.BlockBody ?? nonConstructor.ExpressionBody;
break;
case BoundKind.Block:
body = (BoundBlock)methodBody;
break;
default:
throw ExceptionUtilities.UnexpectedValue(methodBody.Kind);
}
}
else
{
var property = sourceMethod.AssociatedSymbol as SourcePropertySymbol;
if ((object)property != null && property.IsAutoProperty)
{
return MethodBodySynthesizer.ConstructAutoPropertyAccessorBody(sourceMethod);
}
return null;
}
}
else
{
// synthesized methods should return their bound bodies
body = null;
}
if (method.MethodKind == MethodKind.Destructor && body != null)
{
return MethodBodySynthesizer.ConstructDestructorBody(method, body);
}
var constructorInitializer = BindImplicitConstructorInitializerIfAny(method, compilationState, diagnostics);
ImmutableArray<BoundStatement> statements;
if (constructorInitializer == null)
{
if (body != null)
{
return body;
}
statements = ImmutableArray<BoundStatement>.Empty;
}
else if (body == null)
{
statements = ImmutableArray.Create(constructorInitializer);
}
else
{
statements = ImmutableArray.Create(constructorInitializer, body);
originalBodyNested = true;
}
return BoundBlock.SynthesizedNoLocals(method.GetNonNullSyntaxNode(), statements);
}
private static BoundStatement BindImplicitConstructorInitializerIfAny(MethodSymbol method, TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
// delegates have constructors but not constructor initializers
if (method.MethodKind == MethodKind.Constructor && !method.ContainingType.IsDelegateType() && !method.IsExtern)
{
var compilation = method.DeclaringCompilation;
var initializerInvocation = BindImplicitConstructorInitializer(method, diagnostics, compilation);
if (initializerInvocation != null)
{
ReportCtorInitializerCycles(method, initializerInvocation, compilationState, diagnostics);
// Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation.
var constructorInitializer = new BoundExpressionStatement(initializerInvocation.Syntax, initializerInvocation) { WasCompilerGenerated = method.IsImplicitlyDeclared };
Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer.");
return constructorInitializer;
}
}
return null;
}
private static void ReportCtorInitializerCycles(MethodSymbol method, BoundExpression initializerInvocation, TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
var ctorCall = initializerInvocation as BoundCall;
if (ctorCall != null && !ctorCall.HasAnyErrors && ctorCall.Method != method && TypeSymbol.Equals(ctorCall.Method.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything2))
{
// Detect and report indirect cycles in the ctor-initializer call graph.
compilationState.ReportCtorInitializerCycles(method, ctorCall.Method, ctorCall.Syntax, diagnostics);
}
}
/// <summary>
/// Bind the implicit constructor initializer of a constructor symbol.
/// </summary>
/// <param name="constructor">Constructor method.</param>
/// <param name="diagnostics">Accumulates errors (e.g. access "this" in constructor initializer).</param>
/// <param name="compilation">Used to retrieve binder.</param>
/// <returns>A bound expression for the constructor initializer call.</returns>
internal static BoundExpression BindImplicitConstructorInitializer(
MethodSymbol constructor, DiagnosticBag diagnostics, CSharpCompilation compilation)
{
// Note that the base type can be null if we're compiling System.Object in source.
NamedTypeSymbol baseType = constructor.ContainingType.BaseTypeNoUseSiteDiagnostics;
SourceMemberMethodSymbol sourceConstructor = constructor as SourceMemberMethodSymbol;
Debug.Assert(((ConstructorDeclarationSyntax)sourceConstructor?.SyntaxNode)?.Initializer == null);
// The common case is that the type inherits directly from object.
// Also, we might be trying to generate a constructor for an entirely compiler-generated class such
// as a closure class; in that case it is vexing to try to find a suitable binder for the non-existing
// constructor syntax so that we can do unnecessary overload resolution on the non-existing initializer!
// Simply take the early out: bind directly to the parameterless object ctor rather than attempting
// overload resolution.
if ((object)baseType != null)
{
if (baseType.SpecialType == SpecialType.System_Object)
{
return GenerateBaseParameterlessConstructorInitializer(constructor, diagnostics);
}
else if (baseType.IsErrorType() || baseType.IsStatic)
{
// If the base type is bad and there is no initializer then we can just bail.
// We have no expressions we need to analyze to report errors on.
return null;
}
}
// Now, in order to do overload resolution, we're going to need a binder. There are
// two possible situations:
//
// class D1 : B { }
// class D2 : B { D2(int x) { } }
//
// In the first case the binder needs to be the binder associated with
// the *body* of D1 because if the base class ctor is protected, we need
// to be inside the body of a derived class in order for it to be in the
// accessibility domain of the protected base class ctor.
//
// In the second case the binder could be the binder associated with
// the body of D2; since the implicit call to base() will have no arguments
// there is no need to look up "x".
Binder outerBinder;
if ((object)sourceConstructor == null)
{
// The constructor is implicit. We need to get the binder for the body
// of the enclosing class.
CSharpSyntaxNode containerNode = constructor.GetNonNullSyntaxNode();
SyntaxToken bodyToken = GetImplicitConstructorBodyToken(containerNode);
outerBinder = compilation.GetBinderFactory(containerNode.SyntaxTree).GetBinder(containerNode, bodyToken.Position);
}
else
{
// We have a ctor in source but no explicit constructor initializer. We can't just use the binder for the
// type containing the ctor because the ctor might be marked unsafe. Use the binder for the parameter list
// as an approximation - the extra symbols won't matter because there are no identifiers to bind.
outerBinder = compilation.GetBinderFactory(sourceConstructor.SyntaxTree).GetBinder(((ConstructorDeclarationSyntax)sourceConstructor.SyntaxNode).ParameterList);
}
// wrap in ConstructorInitializerBinder for appropriate errors
// Handle scoping for possible pattern variables declared in the initializer
Binder initializerBinder = outerBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.ConstructorInitializer, constructor);
return initializerBinder.BindConstructorInitializer(null, constructor, diagnostics);
}
private static SyntaxToken GetImplicitConstructorBodyToken(CSharpSyntaxNode containerNode)
{
return ((BaseTypeDeclarationSyntax)containerNode).OpenBraceToken;
}
internal static BoundCall GenerateBaseParameterlessConstructorInitializer(MethodSymbol constructor, DiagnosticBag diagnostics)
{
NamedTypeSymbol baseType = constructor.ContainingType.BaseTypeNoUseSiteDiagnostics;
MethodSymbol baseConstructor = null;
LookupResultKind resultKind = LookupResultKind.Viable;
Location diagnosticsLocation = constructor.Locations.IsEmpty ? NoLocation.Singleton : constructor.Locations[0];
foreach (MethodSymbol ctor in baseType.InstanceConstructors)
{
if (ctor.ParameterCount == 0)
{
baseConstructor = ctor;
break;
}
}
// UNDONE: If this happens then something is deeply wrong. Should we give a better error?
if ((object)baseConstructor == null)
{
diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, diagnosticsLocation, baseType, /*desired param count*/ 0);
return null;
}
if (Binder.ReportUseSiteDiagnostics(baseConstructor, diagnostics, diagnosticsLocation))
{
return null;
}
// UNDONE: If this happens then something is deeply wrong. Should we give a better error?
bool hasErrors = false;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (!AccessCheck.IsSymbolAccessible(baseConstructor, constructor.ContainingType, ref useSiteDiagnostics))
{
diagnostics.Add(ErrorCode.ERR_BadAccess, diagnosticsLocation, baseConstructor);
resultKind = LookupResultKind.Inaccessible;
hasErrors = true;
}
if (!useSiteDiagnostics.IsNullOrEmpty())
{
diagnostics.Add(diagnosticsLocation, useSiteDiagnostics);
}
CSharpSyntaxNode syntax = constructor.GetNonNullSyntaxNode();
BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true };
return new BoundCall(
syntax: syntax,
receiverOpt: receiver,
method: baseConstructor,
arguments: ImmutableArray<BoundExpression>.Empty,
argumentNamesOpt: ImmutableArray<string>.Empty,
argumentRefKindsOpt: ImmutableArray<RefKind>.Empty,
isDelegateCall: false,
expanded: false,
invokedAsExtensionMethod: false,
argsToParamsOpt: ImmutableArray<int>.Empty,
resultKind: resultKind,
binderOpt: null,
type: baseConstructor.ReturnType,
hasErrors: hasErrors)
{ WasCompilerGenerated = true };
}
private static void GenerateExternalMethodWarnings(SourceMemberMethodSymbol methodSymbol, DiagnosticBag diagnostics)
{
if (methodSymbol.GetAttributes().IsEmpty && !methodSymbol.ContainingType.IsComImport)
{
// external method with no attributes
var errorCode = (methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.StaticConstructor) ?
ErrorCode.WRN_ExternCtorNoImplementation :
ErrorCode.WRN_ExternMethodNoImplementation;
diagnostics.Add(errorCode, methodSymbol.Locations[0], methodSymbol);
}
}
/// <summary>
/// Returns true if the method is a constructor and has a this() constructor initializer.
/// </summary>
private static bool HasThisConstructorInitializer(MethodSymbol method)
{
if ((object)method != null && method.MethodKind == MethodKind.Constructor)
{
SourceMemberMethodSymbol sourceMethod = method as SourceMemberMethodSymbol;
if ((object)sourceMethod != null)
{
ConstructorDeclarationSyntax constructorSyntax = sourceMethod.SyntaxNode as ConstructorDeclarationSyntax;
if (constructorSyntax != null)
{
ConstructorInitializerSyntax initializerSyntax = constructorSyntax.Initializer;
if (initializerSyntax != null)
{
return initializerSyntax.Kind() == SyntaxKind.ThisConstructorInitializer;
}
}
}
}
return false;
}
private static Cci.DebugSourceDocument CreateDebugDocumentForFile(string normalizedPath)
{
return new Cci.DebugSourceDocument(normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeCSharp);
}
private static bool PassesFilter(Predicate<Symbol> filterOpt, Symbol symbol)
{
return (filterOpt == null) || filterOpt(symbol);
}
}
}
| 49.645 | 238 | 0.572767 | [
"Apache-2.0"
] | 20chan/roslyn | src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs | 99,292 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using LamedalCore;
using LamedalCore.zz;
namespace Lamedal_UIWinForms.UControl.form1.FormCreator
{
public sealed partial class FormCreator_SelectClasses_Form : System.Windows.Forms.Form
{
private readonly Component _parent;
private readonly Lamedal_WinForms IamWindows = Lamedal_WinForms.Instance; // Set reference to Blueprint Windows lib
private string _className;
public FormCreator_SelectClasses_Form(Component parent)
{
_parent = parent;
InitializeComponent();
Setup(parent);
}
public string ClassName
{
get { return _className; }
}
public Dictionary<string, Tuple<Type, Attribute>> TypeAttributeDictionary
{
get { return _typeAttributeDictionary; }
}
private Dictionary<string, Tuple<Type, Attribute>> _typeAttributeDictionary;
public void Setup(Component component)
{
// Populate the list of classes that can be generated
Assembly assembly = LamedalCore_.Instance.Types.Assembly.From_Object(component);
List<string> typeNameList;
if (IamWindows.libUI.WinForms.FormGenerate.AssemblyTypes(assembly, out typeNameList, out _typeAttributeDictionary))
{
typeNameList.zTo_IList(listBox_Classes.Items);
listBox_Classes.SelectedIndex = 0;
}
}
private void listBox_Classes_SelectedIndexChanged(object sender, EventArgs e)
{
_className = listBox_Classes.Text;
}
}
}
| 32.301887 | 127 | 0.658879 | [
"MIT"
] | LouwrensP/Lamedal_WinForms | src/UControl/form1/FormCreator/FormCreator_SelectClasses_Form.cs | 1,714 | C# |
using OmniPay.Core.Utils;
namespace OmniPay.Wechatpay.Domain
{
public class AppPayModel:BasePayModel
{
public AppPayModel()
{
TradeType = "APP";
}
/// <summary>
/// 交易类型
/// </summary>
public string TradeType { get; set; }
/// <summary>
/// 机器IP
/// </summary>
public string SpbillCreateIp { get; set; }
/// <summary>
/// 用户标识
/// </summary>
public string OpenId { get; set; }
/// <summary>
/// 场景信息
/// </summary>
public string SceneInfo { get; set; }
}
}
| 21.733333 | 50 | 0.455521 | [
"MIT"
] | hueifeng/AspNetCore.Free.Pay | src/OmniPay.Wechatpay/Domain/AppPayModel.cs | 682 | C# |
using System.Collections.Generic;
using System.IO;
namespace LibCore
{
public static class Paths
{
public static string [] Split (string path)
{
List<string> components = new List<string> ();
foreach (string component in path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
{
if (! string.IsNullOrEmpty(component))
{
if ((components.Count == 0)
&& path.StartsWith(@"\\"))
{
components.Add(@"\\" + component);
}
else
{
components.Add(component);
}
}
}
return components.ToArray();
}
public static string Combine (string [] components)
{
string path = null;
foreach (string component in components)
{
if (! string.IsNullOrEmpty(component))
{
if (string.IsNullOrEmpty(path))
{
path = component;
}
else if (path.EndsWith(":"))
{
path = path + Path.DirectorySeparatorChar + component;
}
else
{
path = Path.Combine(path, component);
}
}
}
return path;
}
public static string ChangeExtension (string path, string extension)
{
string [] components = Split(path);
components[components.Length - 1] = Path.GetFileNameWithoutExtension(components[components.Length - 1]) + extension;
return Combine(components);
}
public static bool IsChild (string baseFolder, string filename)
{
return filename.ToLowerInvariant().StartsWith(baseFolder.ToLowerInvariant());
}
}
} | 21.214286 | 119 | 0.637037 | [
"MIT-0"
] | business-sims-toolkit/business-sims-toolkit | dev/libraries/core/LibCore/Paths.cs | 1,487 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mono.Cecil;
namespace Mono.Documentation.Updater.Frameworks
{
/// <summary>
/// Represents a set of assemblies that we want to document
/// </summary>
public class AssemblySet : IDisposable
{
static readonly BaseAssemblyResolver resolver = new Frameworks.MDocResolver ();
static IAssemblyResolver cachedResolver;
static IMetadataResolver metadataResolver;
HashSet<string> assemblyPaths = new HashSet<string> ();
Dictionary<string, bool> assemblyPathsMap = new Dictionary<string, bool> ();
HashSet<string> assemblySearchPaths = new HashSet<string> ();
HashSet<string> forwardedTypes = new HashSet<string> ();
IEnumerable<string> importPaths;
public IEnumerable<DocumentationImporter> Importers { get; private set; }
FrameworkEntry fx;
public FrameworkEntry Framework
{
get => fx;
set
{
fx = value;
fx.AddAssemblySet (this);
}
}
/// <summary>This is meant only for unit test access</summary>
public IDictionary<string, bool> AssemblyMapsPath
{
get => assemblyPathsMap;
}
public AssemblySet (IEnumerable<string> paths) : this ("Default", paths, new string[0]) { }
public AssemblySet (string name, IEnumerable<string> paths, IEnumerable<string> resolverSearchPaths, IEnumerable<string> imports = null, string version = null, string id = null)
{
cachedResolver = cachedResolver ?? new CachedResolver (resolver);
metadataResolver = metadataResolver ?? new Frameworks.MDocMetadataResolver (cachedResolver);
Name = name;
Version = version;
Id = id;
foreach (var path in paths)
{
assemblyPaths.Add (path);
string pathName = Path.GetFileName (path);
if (!assemblyPathsMap.ContainsKey (pathName))
assemblyPathsMap.Add (pathName, true);
}
// add default search paths
var assemblyDirectories = paths
.Where (p => p.Contains (Path.DirectorySeparatorChar))
.Select (p => Path.GetDirectoryName (p));
foreach (var searchPath in resolverSearchPaths.Union (assemblyDirectories))
assemblySearchPaths.Add (searchPath);
char oppositeSeparator = Path.DirectorySeparatorChar == '/' ? '\\' : '/';
Func<string, string> sanitize = p =>
p.Replace (oppositeSeparator, Path.DirectorySeparatorChar);
foreach (var searchPath in assemblySearchPaths.Select (sanitize))
resolver.AddSearchDirectory (searchPath);
this.importPaths = imports;
if (this.importPaths != null)
{
this.Importers = this.importPaths.Select (p => MDocUpdater.Instance.GetImporter (p, supportsEcmaDoc: false)).ToArray ();
}
else
this.Importers = new DocumentationImporter[0];
}
public string Name { get; private set; }
public string Version { get; private set; }
public string Id { get; private set; }
IEnumerable<AssemblyDefinition> assemblies;
public IEnumerable<AssemblyDefinition> Assemblies
{
get
{
if (this.assemblies == null)
this.assemblies = this.LoadAllAssemblies ().Where (a => a != null).ToArray ();
return this.assemblies;
}
}
public IEnumerable<string> AssemblyPaths { get { return this.assemblyPaths; } }
/// <summary>Adds all subdirectories to the search directories for the resolver to look in.</summary>
public void RecurseSearchDirectories ()
{
var directories = resolver
.GetSearchDirectories ()
.Select (d => new DirectoryInfo (d))
.Where (d => d.Exists)
.Select (d => d.FullName)
.Distinct ()
.ToDictionary (d => d, d => d);
var subdirs = directories.Keys
.SelectMany (d => Directory.GetDirectories (d, ".", SearchOption.AllDirectories))
.Where (d => !directories.ContainsKey (d));
foreach (var dir in subdirs)
resolver.AddSearchDirectory (dir);
}
/// <returns><c>true</c>, if in set was contained in the set of assemblies, <c>false</c> otherwise.</returns>
/// <param name="name">An assembly file name</param>
public bool Contains (string name)
{
return assemblyPathsMap.ContainsKey (name);//assemblyPaths.Any (p => Path.GetFileName (p) == name);
}
/// <summary>Tells whether an already enumerated AssemblyDefinition, contains the type.</summary>
/// <param name="name">Type name</param>
public bool ContainsForwardedType (string name)
{
return forwardedTypes.Contains (name);
}
public void Dispose ()
{
this.assemblies = null;
cachedResolver.Dispose();
}
public override string ToString ()
{
return string.Format ("[AssemblySet: Name={0}, Assemblies={1}]", Name, assemblyPaths.Count);
}
IEnumerable<AssemblyDefinition> LoadAllAssemblies ()
{
foreach (var path in this.assemblyPaths) {
var assembly = MDocUpdater.Instance.LoadAssembly (path, metadataResolver, cachedResolver);
if (assembly != null) {
foreach (var type in assembly.MainModule.ExportedTypes.Where (t => t.IsForwarder).Select (t => t.FullName))
forwardedTypes.Add (type);
}
yield return assembly;
}
}
}
}
| 36.75 | 185 | 0.59915 | [
"MIT"
] | jmarolf/api-doc-tools | mdoc/Mono.Documentation/Updater/Frameworks/AssemblySet.cs | 5,882 | C# |
//
// RatingMenuItem.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Mike Gemuende <mike@gemuende.de>
//
// Copyright (C) 2007 Novell, Inc.
// Copyright (C) 2010 Mike Gemuende
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace FSpot.Widgets
{
public class RatingMenuItem : Hyena.Widgets.RatingMenuItem
{
private RatingEntry entry;
public RatingMenuItem () : base (new FSpot.Widgets.RatingEntry ())
{
entry = this.RatingEntry as FSpot.Widgets.RatingEntry;
}
public RatingMenuItem (object parent) : this ()
{
if (parent is FullScreenView) {
entry.Value = (int)(parent as FullScreenView).View.Item.Current.Rating;
} else if (App.Instance.Organizer.Selection.Count == 1) {
entry.Value = (int)App.Instance.Organizer.Selection[0].Rating;
}
}
protected RatingMenuItem (IntPtr raw) : base (raw)
{
}
}
}
| 34.644068 | 87 | 0.684932 | [
"MIT"
] | Sanva/f-spot | src/Clients/MainApp/FSpot.Widgets/RatingMenuItem.cs | 2,044 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyTrademark("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#endif
// 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)]
[assembly: AssemblyVersion("1.8.1.0")]
[assembly: AssemblyFileVersion("1.8.1.0")]
| 34.04 | 78 | 0.773208 | [
"MIT"
] | Greybird/azure-documentdb-datamigrationtool | Solution Items/CommonAssemblyInfo.cs | 852 | C# |
using net.sxtrader.bftradingstrategies.SXALInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace net.sxtrader.pinnacleif
{
public sealed partial class PinnacleKom : ISXAL
{
public double MinStake
{
get
{
return 5.0;
}
}
public bool SupportsBelowMinStakeBetting
{
get
{
return false;
}
}
public bool cancelBet(long betId)
{
throw new NotImplementedException();
}
public void getAccounFounds(out double availBalance, out double currentBalance, out double creditLimit)
{
string currency = string.Empty;
internalGetAccounFounds(out availBalance, out currentBalance, out creditLimit, out currency);
}
public SXALMarket[] getAllMarkets(int?[] eventids, DateTime fromDate, DateTime toDate)
{
return internalGetAllMarkets(eventids, fromDate, toDate);
}
public SXALBet getBetDetail(long betId)
{
throw new NotImplementedException();
}
public SXALMUBet[] getBetMU(long betId)
{
throw new NotImplementedException();
}
public SXALMUBet[] getBets(DateTime dts)
{
return internalGetBets(dts);
}
public SXALMUBet[] getBetsMU(long marketId)
{
throw new NotImplementedException();
}
public string getCurrency()
{
string currency = string.Empty;
double availBalance, currentBalance, creditLimit;
availBalance = currentBalance = creditLimit = 0;
internalGetAccounFounds(out availBalance, out currentBalance, out creditLimit, out currency);
return currency;
}
public string getExchangeName()
{
return "Pinnacle";
}
public SXALMarketLite getMarketInfo(long marketId)
{
throw new NotImplementedException();
}
public SXALMarketPrices getMarketPrices(long marketId, bool canThrowThrottleExceeded)
{
throw new NotImplementedException();
}
public SXALSelectionIdEnum getReverseSelectionId(long selectionId, SXALMarket m)
{
throw new NotImplementedException();
}
public long getSelectionId(SXALSelectionIdEnum selectionToGet, SXALMarket m)
{
throw new NotImplementedException();
}
public long getSelectionIdByName(string name, SXALMarket m)
{
throw new NotImplementedException();
}
public SXALSelection[] getSelections(SXALMarket market)
{
throw new NotImplementedException();
}
public decimal getValidOddIncrement(decimal odds)
{
throw new NotImplementedException();
}
public SXALEventType[] loadEvents()
{
return internalLoadEvents();
}
public bool login(string usr, string pwd)
{
_usr = usr;
_pwd = pwd;
return login();
}
public SXALBet placeBackBet(long marketId, long selectionId, int asianId, bool keepBet, double price, double money, bool isInplay)
{
throw new NotImplementedException();
}
public SXALBet placeLayBet(long marketId, long selectionId, int asianId, bool keepBet, double price, double money, bool isInplay)
{
throw new NotImplementedException();
}
public SXALMarket translateHorseMarket(SXALMarket market)
{
throw new NotImplementedException();
}
public decimal validateOdd(decimal odds)
{
throw new NotImplementedException();
}
}
}
| 27.232877 | 138 | 0.589034 | [
"MIT"
] | SXTrader/SXTrader | BFTradingStrategies/PinnacleIF/PinnacleKom.ISXAL.cs | 3,978 | C# |
using PG.Commons.Xml.Values;
namespace PG.StarWarsGame.Commons.Xml.Tags.Engine.FoC
{
public sealed class OcclusionSilhouettesEnabledXmlTagDefinition : AXmlTagDefinition
{
private const string KEY_ID = "Occlusion_Silhouettes_Enabled";
private const XmlValueType PG_TYPE = XmlValueType.Boolean;
private const XmlValueTypeInternal INTERNAL_TYPE = XmlValueTypeInternal.Undefined;
private const bool IS_SINGLETON = true;
public override string Id => KEY_ID;
public override XmlValueType Type => PG_TYPE;
public override XmlValueTypeInternal TypeInternal => INTERNAL_TYPE;
public override bool IsSingleton => IS_SINGLETON;
}
} | 41.058824 | 90 | 0.744986 | [
"MIT"
] | AlamoEngine-Tools/PetroglyphTools | PG.StarWarsGame/PG.StarWarsGame/Commons/Xml/Tags/Engine/FoC/OcclusionSilhouettesEnabledXmlTagDefinition.cs | 698 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='HTMLImageElementFactory.xml' path='doc/member[@name="HTMLImageElementFactory"]/*' />
[Guid("3050F38F-98B5-11CF-BB82-00AA00BDCE0B")]
public partial struct HTMLImageElementFactory
{
}
| 37.4 | 145 | 0.778966 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/MsHTML/HTMLImageElementFactory.cs | 563 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Web.Hosting;
using Microsoft.SourceBrowser.Common;
namespace Microsoft.SourceBrowser.SourceIndexServer.Models
{
public class Index : IDisposable
{
public const int MaxRawResults = 100;
private static Index instance;
private static readonly object gate = new object();
internal void ClearAll()
{
assemblies.Clear();
projects.Clear();
symbols.Clear();
guids.Clear();
projectToAssemblyIndexMap.Clear();
msbuildProperties.Clear();
msbuildItems.Clear();
msbuildTargets.Clear();
indexFinishedPopulating = false;
progress = 0.0;
huffman = null;
}
public List<AssemblyInfo> assemblies = new List<AssemblyInfo>();
public List<string> projects = new List<string>();
public List<IndexEntry> symbols = new List<IndexEntry>();
public List<string> guids = new List<string>();
public Dictionary<string, int> projectToAssemblyIndexMap = new Dictionary<string, int>();
public List<string> msbuildProperties = new List<string>();
public List<string> msbuildItems = new List<string>();
public List<string> msbuildTargets = new List<string>();
public List<string> msbuildTasks = new List<string>();
public Huffman huffman;
public bool indexFinishedPopulating = false;
public double progress = 0.0;
public string loadErrorMessage = null;
public static Index Instance
{
get
{
if (instance == null)
{
lock (gate)
{
if (instance == null)
{
instance = new Index();
var rootPath = HostingEnvironment.ApplicationPhysicalPath;
Task.Run(() => IndexLoader.ReadIndex(instance, rootPath));
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
}
}
}
return instance;
}
}
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
if (instance != null)
{
instance.Dispose();
instance = null;
}
}
public Query Get(string queryString)
{
if (!indexFinishedPopulating)
{
string message = "Index is being rebuilt... " + string.Format("{0:0%}", progress);
if (loadErrorMessage != null)
{
message = message + "<br />" + loadErrorMessage;
}
return Query.Empty(message);
}
if (queryString.Length < 3)
{
return Query.Empty("Enter at least three characters for type or member name");
}
var query = new Query(queryString);
if (query.IsAssemblySearch())
{
FindAssemblies(query, defaultToAll: true);
}
else if (query.SymbolKinds.Contains(SymbolKindText.MSBuildProperty))
{
FindMSBuildProperties(query, defaultToAll: true);
}
else if (query.SymbolKinds.Contains(SymbolKindText.MSBuildItem))
{
FindMSBuildItems(query, defaultToAll: true);
}
else if (query.SymbolKinds.Contains(SymbolKindText.MSBuildTarget))
{
FindMSBuildTargets(query, defaultToAll: true);
}
else if (query.SymbolKinds.Contains(SymbolKindText.MSBuildTask))
{
FindMSBuildTasks(query, defaultToAll: true);
}
else
{
FindSymbols(query);
FindAssemblies(query);
FindProjects(query);
FindGuids(query);
FindMSBuildProperties(query);
FindMSBuildItems(query);
FindMSBuildTargets(query);
FindMSBuildTasks(query);
}
return query;
}
public AssemblyInfo FindAssembly(string assemblyName)
{
int i = SortedSearch.FindItem(assemblies, assemblyName, a => a.AssemblyName);
return assemblies[i];
}
public int GetReferencingAssembliesCount(string assemblyName)
{
var assemblyInfo = FindAssembly(assemblyName);
return assemblyInfo.ReferencingAssembliesCount;
}
public void FindAssemblies(Query query, bool defaultToAll = false)
{
string assemblyName = query.GetSearchTermForAssemblySearch();
if (assemblyName == null)
{
if (defaultToAll)
{
query.AddResultAssemblies(GetAllListedAssemblies());
}
return;
}
bool isQuoted = false;
assemblyName = Query.StripQuotes(assemblyName, out isQuoted);
var search = new SortedSearch(i => this.assemblies[i].AssemblyName, this.assemblies.Count);
int low, high;
search.FindBounds(assemblyName, out low, out high);
if (high >= low)
{
var result = Enumerable
.Range(low, high - low + 1)
.Where(i => !isQuoted || assemblies[i].AssemblyName.Length == assemblyName.Length)
.Select(i => assemblies[i])
.Where(a => a.ProjectKey != -1)
.Take(MaxRawResults)
.ToList();
query.AddResultAssemblies(result);
}
}
private IEnumerable<AssemblyInfo> GetAllListedAssemblies()
{
return this.assemblies.Where(a => a.ProjectKey != -1);
}
public void FindSymbols(Query query)
{
foreach (var interpretation in query.Interpretations)
{
FindSymbols(query, interpretation);
}
if (query.ResultSymbols.Any())
{
query.ResultSymbols.Sort((l, r) => SymbolSorter(l, r, query));
}
}
private void FindSymbols(Query query, Interpretation interpretation)
{
string searchTerm = interpretation.CoreSearchTerm;
var search = new SortedSearch(i => symbols[i].Name, symbols.Count);
int low, high;
search.FindBounds(searchTerm, out low, out high);
if (high < low)
{
return;
}
query.PotentialRawResults = high - low + 1;
var result = Enumerable
.Range(low, high - low + 1)
.Where(i => !interpretation.IsVerbatim || symbols[i].Name.Length == searchTerm.Length)
.Select(i => symbols[i].GetDeclaredSymbolInfo(huffman, assemblies, projects))
.Where(query.Filter)
.Where(interpretation.Filter)
.Take(MaxRawResults)
.ToList();
foreach (var entry in result)
{
entry.MatchLevel = MatchLevel(entry.Name, searchTerm);
}
query.AddResultSymbols(result);
}
private void FindProjects(Query query)
{
string searchTerm = query.GetSearchTermForProjectSearch();
if (searchTerm == null)
{
return;
}
var search = new SortedSearch(i => projects[i], projects.Count);
int low, high;
search.FindBounds(searchTerm, out low, out high);
if (high >= low)
{
var result = Enumerable
.Range(low, high - low + 1)
.Select(i => assemblies[projectToAssemblyIndexMap[projects[i]]])
.Take(MaxRawResults)
.ToList();
query.AddResultProjects(result);
}
}
private void FindGuids(Query query)
{
string searchTerm = query.OriginalString;
searchTerm = searchTerm.TrimStart('{', '(');
searchTerm = searchTerm.TrimEnd('}', ')');
var result = FindInList(searchTerm, guids, defaultToAll: false);
if (result != null && result.Any())
{
query.AddResultGuids(result.ToList());
}
}
private void FindMSBuildProperties(Query query, bool defaultToAll = false)
{
var result = FindInList(query.GetSearchTermForMSBuildSearch(), msbuildProperties, defaultToAll);
if (result != null && result.Any())
{
query.AddResultMSBuildProperties(result.ToList());
}
}
private void FindMSBuildItems(Query query, bool defaultToAll = false)
{
var result = FindInList(query.GetSearchTermForMSBuildSearch(), msbuildItems, defaultToAll);
if (result != null && result.Any())
{
query.AddResultMSBuildItems(result.ToList());
}
}
private void FindMSBuildTargets(Query query, bool defaultToAll = false)
{
var result = FindInList(query.GetSearchTermForMSBuildSearch(), msbuildTargets, defaultToAll);
if (result != null && result.Any())
{
query.AddResultMSBuildTargets(result.ToList());
}
}
private void FindMSBuildTasks(Query query, bool defaultToAll = false)
{
var result = FindInList(query.GetSearchTermForMSBuildSearch(), msbuildTasks, defaultToAll);
if (result != null && result.Any())
{
query.AddResultMSBuildTasks(result.ToList());
}
}
private IEnumerable<string> FindInList(string searchTerm, List<string> list, bool defaultToAll)
{
if (string.IsNullOrEmpty(searchTerm))
{
if (defaultToAll)
{
return list;
}
else
{
return null;
}
}
var search = new SortedSearch(i => list[i], list.Count);
int low, high;
search.FindBounds(searchTerm, out low, out high);
if (high >= low)
{
var result = Enumerable
.Range(low, high - low + 1)
.Select(i => list[i])
.Take(MaxRawResults);
return result;
}
return null;
}
public List<DeclaredSymbolInfo> FindSymbols(string queryString)
{
var query = new Query(queryString);
FindSymbols(query);
return query.ResultSymbols;
}
/// <summary>
/// This defines the ordering of results based on the kind of symbol and other heuristics
/// </summary>
private int SymbolSorter(DeclaredSymbolInfo left, DeclaredSymbolInfo right, Query query)
{
if (left == right)
{
return 0;
}
if (left == null || right == null)
{
return 1;
}
var comparison = left.MatchLevel.CompareTo(right.MatchLevel);
if (comparison != 0)
{
return comparison;
}
comparison = left.KindRank.CompareTo(right.KindRank);
if (comparison != 0)
{
return comparison;
}
if (left.Name != null && right.Name != null)
{
comparison = left.Name.CompareTo(right.Name);
if (comparison != 0)
{
return comparison;
}
}
comparison = left.AssemblyNumber.CompareTo(right.AssemblyNumber);
if (comparison != 0)
{
return comparison;
}
comparison = StringComparer.Ordinal.Compare(left.Description, right.Description);
return comparison;
}
/// <summary>
/// This defines the ordering of the results, assigning weight to different types of matches
/// </summary>
private ushort MatchLevel(string candidate, string query)
{
int indexOf = candidate.IndexOf(query);
int indexOfIgnoreCase = candidate.IndexOf(query, StringComparison.OrdinalIgnoreCase);
if (indexOf == 0)
{
if (candidate.Length == query.Length)
{
// candidate == query
return 1;
}
else
{
// candidate.StartsWith(query)
return 3;
}
}
else if (indexOf > 0)
{
if (indexOfIgnoreCase == 0)
{
if (candidate.Length == query.Length)
{
return 2;
}
else
{
return 4;
}
}
else
{
return 5;
}
}
else // indexOf < 0
{
if (indexOfIgnoreCase == 0)
{
if (candidate.Length == query.Length)
{
// query.Equals(candidate, StringComparison.OrdinalIgnoreCase)
return 2;
}
else
{
// candidate.StartsWith(query, StringComparison.OrdinalIgnoreCase)
return 4;
}
}
else
{
return 7;
}
}
}
public void Dispose()
{
if (huffman == null || symbols == null || assemblies == null || projects == null)
{
return;
}
for (int i = 0; i < this.symbols.Count; i++)
{
if (this.symbols[i].Description != IntPtr.Zero)
{
Marshal.FreeHGlobal(this.symbols[i].Description);
}
}
this.huffman = null;
this.symbols = null;
this.assemblies = null;
this.projects = null;
}
~Index()
{
Dispose();
}
}
} | 33.174468 | 109 | 0.469792 | [
"Apache-2.0"
] | csharp-playground/source-browser | src/SourceIndexServer/Models/Index.cs | 15,594 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using BitHub.Data;
using Microsoft.AspNetCore.Authorization;
namespace BitHub.Controllers
{
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(policy: "SignedIn")]
public async Task<IActionResult> SignOut()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToPage("/Index");
}
}
} | 27.263158 | 113 | 0.682432 | [
"MIT"
] | WEIJUNCAI/MyBitHub | src/Controllers/AccountController.cs | 1,038 | C# |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Org.Apache.REEF.IO.Tests")]
[assembly: AssemblyDescription("Tests for the IO Library for REEF")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Apache Software Foundation.")]
[assembly: AssemblyProduct("Org.Apache.REEF.IO.Tests")]
[assembly: AssemblyCopyright("The Apache Software Foundation")]
[assembly: AssemblyTrademark("The Apache Software Foundation")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.16.0.0")]
[assembly: AssemblyFileVersion("0.16.0.0")]
[assembly: Guid("a22b790a-0432-4395-9949-bf8e3958f061")] | 47.125 | 69 | 0.750663 | [
"Apache-2.0"
] | afchung/reef | lang/cs/Org.Apache.REEF.IO.Tests/Properties/AssemblyInfo.cs | 1,479 | 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("RFID_USB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RFID_USB")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("ca3944f5-8f62-44e9-8b33-ced52de2fa3b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.540541 | 84 | 0.743701 | [
"MIT"
] | stephan1827/RFID-DotNET | 5E9000.29/RFID_USB/RFID_USB/Properties/AssemblyInfo.cs | 1,392 | 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
namespace Dnn.PersonaBar.Security.Components.Checks
{
using System;
using DotNetNuke.Entities.Portals;
public class CheckSiteRegistration : IAuditCheck
{
public string Id => "CheckSiteRegistration";
public bool LazyLoad => false;
public CheckResult Execute()
{
var result = new CheckResult(SeverityEnum.Unverified, this.Id);
try
{
var portalController = new PortalController();
result.Severity = SeverityEnum.Pass;
foreach (PortalInfo portal in portalController.GetPortals())
{
// check for public registration
if (portal.UserRegistration == 2)
{
result.Severity = SeverityEnum.Warning;
result.Notes.Add("Portal:" + portal.PortalName);
}
}
}
catch (Exception)
{
throw;
}
return result;
}
}
}
| 29.790698 | 76 | 0.540203 | [
"MIT"
] | Mariusz11711/DNN | Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Security/Checks/CheckSiteRegistration.cs | 1,283 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class RemoteAttributeValidationTest : IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>>
{
private static readonly Assembly _resourcesAssembly =
typeof(RemoteAttributeValidationTest).GetTypeInfo().Assembly;
public RemoteAttributeValidationTest(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture)
{
Client = fixture.CreateDefaultClient();
}
public HttpClient Client { get; }
[Theory]
[InlineData("Area1", "/Area1")]
[InlineData("Root", "")]
public async Task RemoteAttribute_LeadsToExpectedValidationAttributes(string areaName, string pathSegment)
{
// Arrange
var outputFile = "compiler/resources/BasicWebSite." + areaName + ".RemoteAttribute_Home.Create.html";
var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
var url = "http://localhost" + pathSegment + "/RemoteAttribute_Home/Create";
// Act
var response = await Client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
Assert.Equal("utf-8", response.Content.Headers.ContentType.CharSet);
var responseContent = await response.Content.ReadAsStringAsync();
ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent);
}
[Theory]
[InlineData("", "\"/RemoteAttribute_Verify/IsIdAvailable rejects UserId1: 'Joe1'.\"")]
[InlineData("/Area1", "false")]
[InlineData("/Area2",
"\"/Area2/RemoteAttribute_Verify/IsIdAvailable rejects 'Joe4' with 'Joe1', 'Joe2', and 'Joe3'.\"")]
public async Task RemoteAttribute_VerificationAction_GetReturnsExpectedJson(
string pathSegment,
string expectedContent)
{
// Arrange
var url = "http://localhost" + pathSegment +
"/RemoteAttribute_Verify/IsIdAvailable?UserId1=Joe1&UserId2=Joe2&UserId3=Joe3&UserId4=Joe4";
// Act
var response = await Client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
Assert.Equal("utf-8", response.Content.Headers.ContentType.CharSet);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, responseContent);
}
[Theory]
[InlineData("", "\"/RemoteAttribute_Verify/IsIdAvailable rejects UserId1: 'Jane1'.\"")]
[InlineData("/Area1", "false")]
public async Task RemoteAttribute_VerificationAction_PostReturnsExpectedJson(
string pathSegment,
string expectedContent)
{
// Arrange
var url = "http://localhost" + pathSegment + "/RemoteAttribute_Verify/IsIdAvailable";
var contentDictionary = new Dictionary<string, string>
{
{ "UserId1", "Jane1" },
{ "UserId2", "Jane2" },
{ "UserId3", "Jane3" },
{ "UserId4", "Jane4" },
};
var content = new FormUrlEncodedContent(contentDictionary);
// Act
var response = await Client.PostAsync(url, content);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
Assert.Equal("utf-8", response.Content.Headers.ContentType.CharSet);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedContent, responseContent);
}
}
}
| 42.588235 | 122 | 0.641114 | [
"MIT"
] | 48355746/AspNetCore | src/Mvc/test/Mvc.FunctionalTests/RemoteAttributeValidationTest.cs | 4,344 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace NavigationTransitions.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 22.416667 | 98 | 0.685874 | [
"MIT"
] | oddbear/XamarinNavigationTransitions | iOS/AppDelegate.cs | 540 | C# |
namespace Helpers
{
public static class Version
{
public const string Name = "0.1.0";
public const string Package = "org.n42.xamarin.helpers";
}
}
| 19.555556 | 64 | 0.613636 | [
"MIT"
] | fmierlo/Xamarin.Helpers | Helpers/Version.cs | 178 | 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.AwsNative.ElasticBeanstalk.Outputs
{
[OutputType]
public sealed class EnvironmentOptionSetting
{
public readonly string Namespace;
public readonly string OptionName;
public readonly string? ResourceName;
public readonly string? Value;
[OutputConstructor]
private EnvironmentOptionSetting(
string @namespace,
string optionName,
string? resourceName,
string? value)
{
Namespace = @namespace;
OptionName = optionName;
ResourceName = resourceName;
Value = value;
}
}
}
| 25.315789 | 81 | 0.643451 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/ElasticBeanstalk/Outputs/EnvironmentOptionSetting.cs | 962 | C# |
using System;
using Application.Interfaces;
namespace Infrastructure.Services
{
public class DateTimeService : IDateTime
{
public DateTime Now => DateTime.Now;
}
} | 18.4 | 44 | 0.711957 | [
"MIT"
] | kerem-acer/basic-cms | src/Infrastructure/Services/DateTimeService.cs | 184 | C# |
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Settings.Common.Domain;
namespace Settings.DataAccess
{
public static class DbInitializer
{
public static void Initialize(SettingsDbContext context, bool refreshData)
{
if(refreshData)
{
var settings = context.Settings.ToList();
foreach(var setting in settings)
{
context.Remove(setting);
}
context.SaveChanges();
var envs = context.Environments.ToList();
foreach (var env in envs)
{
context.Remove(env);
}
context.SaveChanges();
var apps = context.Applications.ToList();
foreach (var app in apps)
{
context.Remove(app);
}
context.SaveChanges();
}
//TODO: Need to add some contraints here and/or make sure they are created
//1. Unique on application name and environment name
context.Database.EnsureCreated();
if(!context.Applications.Any())
{
var appGlobal = new Application
{
Name = "Global"
};
var app_global_engineering = new Application
{
Name = "Engineering",
Parent = appGlobal
};
var app_global_engineering_userportal = new Application
{
Name = "UserPortal",
Parent = app_global_engineering
};
var app_global_engineering_userportal_dataintegration = new Application
{
Name = "DataIntegration",
Parent = app_global_engineering_userportal
};
var app_global_engineering_paymentsapi = new Application
{
Name = "PaymentsApi",
Parent = app_global_engineering
};
context.Applications.Add(appGlobal);
context.Applications.Add(app_global_engineering);
context.Applications.Add(app_global_engineering_userportal);
context.Applications.Add(app_global_engineering_userportal_dataintegration);
context.Applications.Add(app_global_engineering_paymentsapi);
context.SaveChanges();
var envAll = new Environment
{
Name = "All",
};
var envProduction = new Environment
{
Name = "Production",
Parent = envAll
};
var envDevelopment = new Environment
{
Name = "Development",
Parent = envAll
};
var envDevelopmentJose = new Environment
{
Name = "Development-Jose",
Parent = envDevelopment
};
var envStaging = new Environment
{
Name = "Staging",
Parent = envAll
};
context.Environments.Add(envAll);
context.Environments.Add(envProduction);
context.Environments.Add(envDevelopment);
context.Environments.Add(envDevelopmentJose);
context.Environments.Add(envStaging);
context.SaveChanges();
var config_global_all = JsonConvert.SerializeObject(new
{
CompanyName = "TestCompanyName",
Website = "www.testcompanyname.com",
ContactNumber = "1-800-222-2222"
});
var config_userportal_all = JsonConvert.SerializeObject(new {
PasswordExpirationDays = 90, //add
ContactNumber = "1-800-222-1111", //override
AdminRoles = new JArray("LocalAdmin", "SuperAdmin") //add
});
var config_userportal_production = JsonConvert.SerializeObject(new
{
DbConnection = "production.dbserver;database=userportal", //add
Website = "userportal.testcompanyname.com", //override
});
var config_userportal_development = JsonConvert.SerializeObject(new
{
DbConnection = "development.dbserver;database=userportal", //add
Website = "development.userportal.testcompanyname.com" //override
});
var config_userportal_developmentJose = JsonConvert.SerializeObject(new
{
DbConnection = "localhost;database=userportal", //add
Website = "localhost:8080", //override
InDevelopmentFeatureConfig = "test_value" //add
});
var config_userportal_stage = JsonConvert.SerializeObject(new
{
DbConnection = "stage.dbserver;database=userportal", //add
Website = "stage.userportal.testcompanyname.com" //override
});
//Note that this is same environment as above,
//but now data integration application
var config_userportal__dataintegration_development =
JsonConvert.SerializeObject(new
{
MessageQueueConnection = "RabbitMq.development" //add
});
context.Settings.Add(new Setting
{
Application = appGlobal,
Environment = envAll,
Contents = config_global_all
});
context.Settings.Add(new Setting
{
Application = app_global_engineering_userportal,
Environment = envAll,
Contents = config_userportal_all
});
context.Settings.Add(new Setting
{
Application = app_global_engineering_userportal,
Environment = envProduction,
Contents = config_userportal_production
});
context.Settings.Add(new Setting
{
Application = app_global_engineering_userportal,
Environment = envStaging,
Contents = config_userportal_stage
});
context.Settings.Add(new Setting
{
Application = app_global_engineering_userportal,
Environment = envDevelopment,
Contents = config_userportal_development
});
context.Settings.Add(new Setting
{
Application = app_global_engineering_userportal,
Environment = envDevelopmentJose,
Contents = config_userportal_developmentJose
});
context.Settings.Add(new Setting()
{
Application = app_global_engineering_userportal_dataintegration,
Environment = envDevelopment,
Contents = config_userportal__dataintegration_development
});
context.SaveChanges();
}
}
}
}
| 41.361502 | 112 | 0.433939 | [
"Apache-2.0"
] | jopache/Settings | src/Settings.DataAccess/DbInitializer.cs | 8,812 | C# |
using System.Runtime.InteropServices;
namespace Linearstar.Windows.RawInput.Native
{
/// <summary>
/// RID_DEVICE_INFO_KEYBOARD
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct RawInputKeyboardInfo
{
readonly int dwType;
readonly int dwSubType;
readonly int dwKeyboardMode;
readonly int dwNumberOfFunctionKeys;
readonly int dwNumberOfIndicators;
readonly int dwNumberOfKeysTotal;
/// <summary>
/// dwType
/// </summary>
public int KeyboardType => dwType;
/// <summary>
/// dwSubType
/// </summary>
public int KeyboardSubType => dwSubType;
/// <summary>
/// dwKeyboardMode
/// </summary>
public int KeyboardMode => dwKeyboardMode;
/// <summary>
/// dwNumberOfFunctionKeys
/// </summary>
public int FunctionKeyCount => dwNumberOfFunctionKeys;
/// <summary>
/// dwNumberOfIndicators
/// </summary>
public int IndicatorCount => dwNumberOfIndicators;
/// <summary>
/// dwNumberOfKeysTotal
/// </summary>
public int TotalKeyCount => dwNumberOfKeysTotal;
}
}
| 25.428571 | 62 | 0.586677 | [
"MIT"
] | digtive/antrian | plugins/Numeric Keypad Detector/RawInput.Sharp/Native/RawInputKeyboardInfo.cs | 1,248 | C# |
// ****************************************************************************
// <copyright file="HandPresentEventArgs.cs" company="IntuiLab">
// INTUILAB CONFIDENTIAL
//_____________________
// [2002] - [2015] IntuiLab SA
// All Rights Reserved.
// NOTICE: All information contained herein is, and remains
// the property of IntuiLab SA. The intellectual and technical
// concepts contained herein are proprietary to IntuiLab SA
// and may be covered by U.S. and other country Patents, patents
// in process, and are protected by trade secret or copyright law.
// Dissemination of this information or reproduction of this
// material is strictly forbidden unless prior written permission
// is obtained from IntuiLab SA.
// </copyright>
// ****************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LeapPlugin.Events
{
#region Delegate
public delegate void HandPresentEventHandler(object sender, HandPresentEventArgs e);
#endregion
/// <summary>
/// Evènement levé lorsqu'une main est détectée ou lorsqu'elle n'est plus présente
/// </summary>
public class HandPresentEventArgs : EventArgs
{
private bool m_isHandPresent;
/// <summary>
/// Valeur : true si une main est détectée, false au moment où elle part
/// </summary>
public bool IsHandPresent
{
get
{
return m_isHandPresent;
}
}
public HandPresentEventArgs(bool isHandPresent)
{
m_isHandPresent = isHandPresent;
}
}
}
| 32.290909 | 91 | 0.580518 | [
"MIT"
] | intuilab/LeapIA | Leap/Events/HandPresentEventArgs.cs | 1,784 | C# |
using System;
namespace Musoq.Parser.Nodes
{
public class LessNode : BinaryNode
{
public LessNode(Node left, Node right) : base(left, right)
{
Id = CalculateId(this);
}
public override string Id { get; }
public override Type ReturnType => typeof(bool);
public override void Accept(IExpressionVisitor visitor)
{
visitor.Visit(this);
}
public override string ToString()
{
return $"{Left.ToString()} < {Right.ToString()}";
}
}
} | 22.64 | 66 | 0.553004 | [
"MIT"
] | Eibwen/Musoq | Musoq.Parser/Nodes/LessNode.cs | 568 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.IO;
using Microsoft.OData.Edm;
using Microsoft.OpenApi.Extensions;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.OpenApi.OData.Tests
{
public class EdmModelOpenApiExtensionsTest
{
private ITestOutputHelper _output;
public EdmModelOpenApiExtensionsTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void ConvertToOpenApiThrowsArgumentNullModel()
{
// Arrange
IEdmModel model = null;
// Act & Assert
Assert.Throws<ArgumentNullException>("model", () => model.ConvertToOpenApi());
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void EmptyEdmModelToOpenApiJsonWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.EmptyModel;
var openApiConvertSettings = new OpenApiConvertSettings();
openApiConvertSettings.OpenApiSpecVersion = specVersion;
// Act
string json = WriteEdmModelAsOpenApi(model, OpenApiFormat.Json, openApiConvertSettings);
_output.WriteLine(json);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("Empty.OpenApi.V2.json").ChangeLineBreaks(), json);
}
else
{
Assert.Equal(Resources.GetString("Empty.OpenApi.json").ChangeLineBreaks(), json);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void EmptyEdmModelToOpenApiYamlWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.EmptyModel;
var openApiConvertSettings = new OpenApiConvertSettings();
openApiConvertSettings.OpenApiSpecVersion = specVersion;
// Act
string yaml = WriteEdmModelAsOpenApi(model, OpenApiFormat.Yaml, openApiConvertSettings);
_output.WriteLine(yaml);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("Empty.OpenApi.V2.yaml").ChangeLineBreaks(), yaml);
}
else
{
Assert.Equal(Resources.GetString("Empty.OpenApi.yaml").ChangeLineBreaks(), yaml);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void BasicEdmModelToOpenApiJsonWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.BasicEdmModel;
var openApiConvertSettings = new OpenApiConvertSettings();
openApiConvertSettings.OpenApiSpecVersion = specVersion;
// Act
string json = WriteEdmModelAsOpenApi(model, OpenApiFormat.Json, openApiConvertSettings);
_output.WriteLine(json);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("Basic.OpenApi.V2.json").ChangeLineBreaks(), json);
}
else
{
Assert.Equal(Resources.GetString("Basic.OpenApi.json").ChangeLineBreaks(), json);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void BasicEdmModelToOpenApiYamlWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.BasicEdmModel;
var openApiConvertSettings = new OpenApiConvertSettings();
openApiConvertSettings.OpenApiSpecVersion = specVersion;
// Act
string yaml = WriteEdmModelAsOpenApi(model, OpenApiFormat.Yaml, openApiConvertSettings);
_output.WriteLine(yaml);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("Basic.OpenApi.V2.yaml").ChangeLineBreaks(), yaml);
}
else
{
Assert.Equal(Resources.GetString("Basic.OpenApi.yaml").ChangeLineBreaks(), yaml);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void MultipleSchemasEdmModelToOpenApiJsonWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.MultipleSchemasEdmModel;
var openApiConvertSettings = new OpenApiConvertSettings();
openApiConvertSettings.OpenApiSpecVersion = specVersion;
// Act
string json = WriteEdmModelAsOpenApi(model, OpenApiFormat.Json, openApiConvertSettings);
_output.WriteLine(json);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("Multiple.Schema.OpenApi.V2.json").ChangeLineBreaks(), json);
}
else
{
Assert.Equal(Resources.GetString("Multiple.Schema.OpenApi.json").ChangeLineBreaks(), json);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void MultipleSchemasEdmModelToOpenApiYamlWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.MultipleSchemasEdmModel;
var openApiConvertSettings = new OpenApiConvertSettings();
openApiConvertSettings.OpenApiSpecVersion = specVersion;
// Act
string yaml = WriteEdmModelAsOpenApi(model, OpenApiFormat.Yaml, openApiConvertSettings);
_output.WriteLine(yaml);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("Multiple.Schema.OpenApi.V2.yaml").ChangeLineBreaks(), yaml);
}
else
{
Assert.Equal(Resources.GetString("Multiple.Schema.OpenApi.yaml").ChangeLineBreaks(), yaml);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void TripServiceMetadataToOpenApiJsonWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.TripServiceModel;
OpenApiConvertSettings settings = new OpenApiConvertSettings
{
EnableKeyAsSegment = true,
Version = new Version(1, 0, 1),
ServiceRoot = new Uri("http://services.odata.org/TrippinRESTierService"),
IEEE754Compatible = true,
OpenApiSpecVersion = specVersion
};
// Act
string json = WriteEdmModelAsOpenApi(model, OpenApiFormat.Json, settings);
_output.WriteLine(json);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("TripService.OpenApi.V2.json").ChangeLineBreaks(), json);
}
else
{
Assert.Equal(Resources.GetString("TripService.OpenApi.json").ChangeLineBreaks(), json);
}
}
[Theory]
[InlineData(OpenApiSpecVersion.OpenApi2_0)]
[InlineData(OpenApiSpecVersion.OpenApi3_0)]
public void TripServiceMetadataToOpenApiYamlWorks(OpenApiSpecVersion specVersion)
{
// Arrange
IEdmModel model = EdmModelHelper.TripServiceModel;
OpenApiConvertSettings settings = new OpenApiConvertSettings
{
EnableKeyAsSegment = true,
Version = new Version(1, 0, 1),
ServiceRoot = new Uri("http://services.odata.org/TrippinRESTierService"),
IEEE754Compatible = true,
OpenApiSpecVersion = specVersion
};
// Act
string yaml = WriteEdmModelAsOpenApi(model, OpenApiFormat.Yaml, settings);
_output.WriteLine(yaml);
// Assert
if (specVersion == OpenApiSpecVersion.OpenApi2_0)
{
Assert.Equal(Resources.GetString("TripService.OpenApi.V2.yaml").ChangeLineBreaks(), yaml);
}
else
{
Assert.Equal(Resources.GetString("TripService.OpenApi.yaml").ChangeLineBreaks(), yaml);
}
}
private static string WriteEdmModelAsOpenApi(IEdmModel model, OpenApiFormat target,
OpenApiConvertSettings settings = null)
{
settings = settings ?? new OpenApiConvertSettings();
var document = model.ConvertToOpenApi(settings);
Assert.NotNull(document); // guard
MemoryStream stream = new MemoryStream();
document.Serialize(stream, settings.OpenApiSpecVersion, target);
stream.Flush();
stream.Position = 0;
return new StreamReader(stream).ReadToEnd();
}
}
}
| 37.639847 | 110 | 0.597822 | [
"MIT"
] | Bhaskers-Blu-Org2/OpenAPI.NET.OData | test/Microsoft.OpenAPI.OData.Reader.Tests/EdmModelOpenApiExtensionsTest.cs | 9,826 | C# |
// ----------------------------------------------------------------------------------
// <copyright file="Index.cs" company="NMemory Team">
// Copyright (C) NMemory Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// ----------------------------------------------------------------------------------
namespace NMemory.Indexes
{
using System.Collections.Generic;
using NMemory.DataStructures;
using NMemory.Tables;
public class Index<TEntity, TKey> : IndexBase<TEntity, TKey>
where TEntity : class
{
private IDataStructure<TKey, TEntity> dataStructure;
#region Ctor
internal Index(
ITable<TEntity> table,
IKeyInfo<TEntity, TKey> keyInfo,
IDataStructure<TKey, TEntity> dataStructure)
: base(table, keyInfo)
{
this.dataStructure = dataStructure;
this.Rebuild();
}
#endregion
internal override IDataStructure<TKey, TEntity> DataStructure
{
get { return dataStructure; }
}
public override IEnumerable<TEntity> Select(TKey key)
{
return this.dataStructure.Select(key);
}
public override IEnumerable<TEntity> SelectAll()
{
return this.dataStructure.SelectAll();
}
public override void Insert(TEntity entity)
{
TKey key = Key(entity);
dataStructure.Insert(key, entity);
}
public override void Delete(TEntity entity)
{
TKey i = Key(entity);
this.dataStructure.Delete(i, entity);
}
#region Properties
/// <summary>
/// Gets a value that indicates whether the index structure supports interval search.
/// </summary>
public override bool SupportsIntervalSearch
{
get { return dataStructure.SupportsIntervalSearch; }
}
#endregion
}
}
| 33.031915 | 93 | 0.595813 | [
"MIT"
] | AntonD-W/nmemory | Main/Source/NMemory.Shared/Indexes/Index.cs | 3,107 | C# |
namespace Connector.DotNettySocket
{
/// <summary>
/// WebSocket客户端
/// </summary>
public interface IWebSocketClient : IBaseTcpSocketClient, ISendString
{
}
} | 18.4 | 73 | 0.652174 | [
"Apache-2.0"
] | wayne2006/Connector | src/WebSocket/IWebSocketClient.cs | 192 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.SecurityToken")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Security Token Service. The AWS Security Token Service (AWS STS) enables you to provide trusted users with temporary credentials that provide controlled access to your AWS resources.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.102.22")] | 48.28125 | 266 | 0.754693 | [
"Apache-2.0"
] | jiabiao/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/SecurityToken/Properties/AssemblyInfo.cs | 1,545 | C# |
namespace RobotSharp.WebServer.Helpers
{
public enum PinType
{
DcPower3_3,
DcPrower5,
Ground,
Other
}
} | 14.8 | 39 | 0.554054 | [
"Unlicense"
] | cyrilbec/RobotSharp | samples/RobotSharp.WebServer/Helpers/PinType.cs | 150 | C# |
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Domain
{
/// <summary>
/// AlipayMarketingVoucherConfirmModel Data Structure.
/// </summary>
[Serializable]
public class AlipayMarketingVoucherConfirmModel : AopObject
{
/// <summary>
/// 用于决定在用户确认领券后是否重定向。可枚举:true表示需要重定向,false表示不需要重定向,不区分大小写
/// </summary>
[XmlElement("need_redirect")]
public bool NeedRedirect { get; set; }
/// <summary>
/// 外部业务单号。用作幂等控制。同一个template_id、user_id、out_biz_no返回相同的发券码
/// </summary>
[XmlElement("out_biz_no")]
public string OutBizNo { get; set; }
/// <summary>
/// 重定向地址,用于接收支付宝返回的领取码
/// </summary>
[XmlElement("redirect_uri")]
public string RedirectUri { get; set; }
/// <summary>
/// 券模板ID
/// </summary>
[XmlElement("template_id")]
public string TemplateId { get; set; }
/// <summary>
/// 指定用户确认页面的主题名称。目前提供5套主题,分别为:red, blue, yellow, green, orange
/// </summary>
[XmlElement("theme")]
public string Theme { get; set; }
/// <summary>
/// 支付宝用户ID
/// </summary>
[XmlElement("user_id")]
public string UserId { get; set; }
}
}
| 26.632653 | 71 | 0.560153 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Domain/AlipayMarketingVoucherConfirmModel.cs | 1,555 | 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 clouddirectory-2016-05-10.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.CloudDirectory.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CloudDirectory.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateTypedLinkFacet Request Marshaller
/// </summary>
public class UpdateTypedLinkFacetRequestMarshaller : IMarshaller<IRequest, UpdateTypedLinkFacetRequest> , 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((UpdateTypedLinkFacetRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateTypedLinkFacetRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CloudDirectory");
request.Headers["Content-Type"] = "application/x-amz-json-";
request.HttpMethod = "PUT";
string uriResourcePath = "/amazonclouddirectory/2017-01-11/typedlink/facet";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAttributeUpdates())
{
context.Writer.WritePropertyName("AttributeUpdates");
context.Writer.WriteArrayStart();
foreach(var publicRequestAttributeUpdatesListValue in publicRequest.AttributeUpdates)
{
context.Writer.WriteObjectStart();
var marshaller = TypedLinkFacetAttributeUpdateMarshaller.Instance;
marshaller.Marshall(publicRequestAttributeUpdatesListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetIdentityAttributeOrder())
{
context.Writer.WritePropertyName("IdentityAttributeOrder");
context.Writer.WriteArrayStart();
foreach(var publicRequestIdentityAttributeOrderListValue in publicRequest.IdentityAttributeOrder)
{
context.Writer.Write(publicRequestIdentityAttributeOrderListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetName())
{
context.Writer.WritePropertyName("Name");
context.Writer.Write(publicRequest.Name);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
if(publicRequest.IsSetSchemaArn())
request.Headers["x-amz-data-partition"] = publicRequest.SchemaArn;
return request;
}
private static UpdateTypedLinkFacetRequestMarshaller _instance = new UpdateTypedLinkFacetRequestMarshaller();
internal static UpdateTypedLinkFacetRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateTypedLinkFacetRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.871212 | 155 | 0.615523 | [
"Apache-2.0"
] | HaiNguyenMediaStep/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/Internal/MarshallTransformations/UpdateTypedLinkFacetRequestMarshaller.cs | 4,999 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal abstract partial class AbstractSyntacticSingleKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext>
{
private readonly bool _isValidInPreprocessorContext;
protected internal SyntaxKind KeywordKind { get; }
internal bool ShouldFormatOnCommit { get; }
protected AbstractSyntacticSingleKeywordRecommender(
SyntaxKind keywordKind,
bool isValidInPreprocessorContext = false,
bool shouldFormatOnCommit = false)
{
this.KeywordKind = keywordKind;
_isValidInPreprocessorContext = isValidInPreprocessorContext;
this.ShouldFormatOnCommit = shouldFormatOnCommit;
}
protected virtual Task<bool> IsValidContextAsync(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return Task.FromResult(IsValidContext(position, context, cancellationToken));
}
protected virtual bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => false;
public async Task<IEnumerable<RecommendedKeyword>> RecommendKeywordsAsync(
int position,
CSharpSyntaxContext context,
CancellationToken cancellationToken)
{
var syntaxKind = await this.RecommendKeywordAsync(position, context, cancellationToken).ConfigureAwait(false);
if (syntaxKind.HasValue)
{
return SpecializedCollections.SingletonEnumerable(
new RecommendedKeyword(SyntaxFacts.GetText(syntaxKind.Value),
shouldFormatOnCommit: this.ShouldFormatOnCommit,
matchPriority: ShouldPreselect(context, cancellationToken) ? SymbolMatchPriority.Keyword : MatchPriority.Default));
}
return null;
}
protected virtual bool ShouldPreselect(CSharpSyntaxContext context, CancellationToken cancellationToken) => false;
internal async Task<IEnumerable<RecommendedKeyword>> RecommendKeywordsAsync_Test(int position, CSharpSyntaxContext context)
{
var syntaxKind = await this.RecommendKeywordAsync(position, context, CancellationToken.None).ConfigureAwait(false);
if (syntaxKind.HasValue)
{
var matchPriority = ShouldPreselect(context, CancellationToken.None) ? SymbolMatchPriority.Keyword : MatchPriority.Default;
return SpecializedCollections.SingletonEnumerable(
new RecommendedKeyword(SyntaxFacts.GetText(syntaxKind.Value), matchPriority: matchPriority));
}
return null;
}
private async Task<SyntaxKind?> RecommendKeywordAsync(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// NOTE: The collector ensures that we're not in "NonUserCode" like comments, strings, inactive code
// for perf reasons.
var syntaxTree = context.SemanticModel.SyntaxTree;
if (!_isValidInPreprocessorContext &&
context.IsPreProcessorDirectiveContext)
{
return null;
}
if (!await IsValidContextAsync(position, context, cancellationToken).ConfigureAwait(false))
{
return null;
}
return this.KeywordKind;
}
}
}
| 43.822222 | 161 | 0.688641 | [
"Apache-2.0"
] | 20chan/roslyn | src/Features/CSharp/Portable/Completion/KeywordRecommenders/AbstractSyntacticSingleKeywordRecommender.cs | 3,946 | C# |
using System.Collections.Generic;
using System.Linq;
using Bio;
using Bio.Algorithms.Assembly.Padena;
using NUnit.Framework;
namespace Bio.Padena.Tests
{
/// <summary>
/// Test for Step 4 in Parallel De Novo Assembly
/// This step performs error correction on the input graph.
/// It removes redundant paths in the graph.
/// </summary>
[TestFixture]
public class RedundantPathsPurgerTests : ParallelDeNovoAssembler
{
/// <summary>
/// Test Step 4 - Redundant Paths Purger class
/// </summary>
[Test]
public void TestRedundantPathsPurger()
{
const int KmerLength = 5;
const int RedundantThreshold = 10;
List<ISequence> readSeqs = TestInputs.GetRedundantPathReads();
this.SequenceReads.Clear();
this.SetSequenceReads(readSeqs);
this.KmerLength = KmerLength;
this.RedundantPathLengthThreshold = RedundantThreshold;
this.RedundantPathsPurger = new RedundantPathsPurger(RedundantThreshold);
this.CreateGraph();
long graphCount = this.Graph.NodeCount;
long graphEdges = this.Graph.GetNodes().Select(n => n.ExtensionsCount).Sum();
this.RemoveRedundancy();
long redundancyRemovedGraphCount = this.Graph.NodeCount;
long redundancyRemovedGraphEdge = this.Graph.GetNodes().Select(n => n.ExtensionsCount).Sum();
// Compare the two graphs
Assert.AreEqual(5, graphCount - redundancyRemovedGraphCount);
Assert.AreEqual(12, graphEdges - redundancyRemovedGraphEdge);
}
}
}
| 35.297872 | 105 | 0.643761 | [
"Apache-2.0"
] | dotnetbio/bio | Tests/Bio.Padena.Tests/RedundantPathsPurgerTests.cs | 1,661 | C# |
namespace Mendz.ETL
{
/// <summary>
/// Defines a targetable source.
/// </summary>
public interface ITargetable
{
/// <summary>
/// When implemented by a source adapter,
/// returns an instance of its target adapter counterpart
/// with the source adapter's document specification copied over.
/// </summary>
/// <returns>The source adapter's target adapter counterpart.</returns>
ITargetAdapter ToTargetAdapter();
}
}
| 29.529412 | 79 | 0.613546 | [
"Apache-2.0"
] | etmendz/Mendz.ETL | Mendz.ETL/ITargetable.cs | 504 | C# |
using Common.LogicObject;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
/// <summary>
/// Resources Utility
/// </summary>
public static class ResUtility
{
static ResUtility()
{
}
public static string GetExtIconFileName(string fileName)
{
string result = "generic";
string fileExt = Path.GetExtension(fileName);
switch (fileExt.ToLower())
{
case ".doc":
case ".docx":
result = "doc";
break;
case ".xls":
case ".xlsx":
result = "xls";
break;
case ".ppt":
case ".pptx":
result = "ppt";
break;
case ".odt":
result = "odt";
break;
case ".ods":
result = "ods";
break;
case ".odp":
result = "odp";
break;
case ".pdf":
result = "pdf";
break;
case ".txt":
result = "txt";
break;
case ".gif":
result = "gif";
break;
case ".jpg":
result = "jpg";
break;
case ".png":
result = "png";
break;
case ".svg":
result = "svg";
break;
case ".tif":
result = "tif";
break;
case ".mp3":
result = "mp3";
break;
case ".wav":
case ".wma":
result = "music";
break;
case ".avi":
result = "avi";
break;
case ".mp4":
case ".wmv":
case ".mov":
result = "video";
break;
case ".zip":
result = "zip";
break;
case ".rar":
result = "rar";
break;
}
result += ".png";
return result;
}
public static string GetExtIconText(string fileName)
{
string result = Resources.Lang.FileExtIconText_generic;
string fileExt = Path.GetExtension(fileName);
switch (fileExt.ToLower())
{
case ".doc":
case ".docx":
result = Resources.Lang.FileExtIconText_doc;
break;
case ".xls":
case ".xlsx":
result = Resources.Lang.FileExtIconText_xls;
break;
case ".ppt":
case ".pptx":
result = Resources.Lang.FileExtIconText_ppt;
break;
case ".odt":
result = Resources.Lang.FileExtIconText_odt;
break;
case ".ods":
result = Resources.Lang.FileExtIconText_ods;
break;
case ".odp":
result = Resources.Lang.FileExtIconText_odp;
break;
case ".pdf":
result = Resources.Lang.FileExtIconText_pdf;
break;
case ".txt":
result = Resources.Lang.FileExtIconText_txt;
break;
case ".gif":
result = Resources.Lang.FileExtIconText_gif;
break;
case ".jpg":
result = Resources.Lang.FileExtIconText_jpg;
break;
case ".png":
result = Resources.Lang.FileExtIconText_png;
break;
case ".svg":
result = Resources.Lang.FileExtIconText_svg;
break;
case ".tif":
result = Resources.Lang.FileExtIconText_tif;
break;
case ".mp3":
result = Resources.Lang.FileExtIconText_mp3;
break;
case ".wav":
result = Resources.Lang.FileExtIconText_wav;
break;
case ".wma":
result = Resources.Lang.FileExtIconText_wma;
break;
case ".avi":
result = Resources.Lang.FileExtIconText_avi;
break;
case ".mp4":
result = Resources.Lang.FileExtIconText_mp4;
break;
case ".wmv":
result = Resources.Lang.FileExtIconText_wmv;
break;
case ".mov":
result = Resources.Lang.FileExtIconText_mov;
break;
case ".zip":
result = Resources.Lang.FileExtIconText_zip;
break;
case ".rar":
result = Resources.Lang.FileExtIconText_rar;
break;
}
return result;
}
public static string GetErrMsgOfAttFileErrState(AttFileErrState errState)
{
string errMsg = "";
switch (errState)
{
case AttFileErrState.LoadDataFailed:
errMsg = "載入資料失敗";
break;
case AttFileErrState.LoadMultiLangDataFailed:
errMsg = "載入多語系資料失敗";
break;
case AttFileErrState.AttachFileIsRequired:
errMsg = "請上傳檔案";
break;
case AttFileErrState.InvalidFileExt:
errMsg = "不允許的檔案類型";
break;
case AttFileErrState.NoInitialize:
errMsg = "請先執行初始化";
break;
case AttFileErrState.DeleteDataFailed:
errMsg = "刪除附件失敗";
break;
case AttFileErrState.DeletePhysicalFileFailed:
errMsg = "刪除實體檔案失敗";
break;
case AttFileErrState.SavePhysicalFileFailed:
errMsg = "儲存實體檔案失敗";
break;
case AttFileErrState.InsertDataFailed:
errMsg = "新增附件資料失敗";
break;
case AttFileErrState.InsertMultiLangDataFailed:
errMsg = "新增附件多語系資料失敗";
break;
case AttFileErrState.UpdateDataFailed:
errMsg = "更新附件資料失敗";
break;
case AttFileErrState.UpdateMultiLangDataFailed:
errMsg = "更新附件多語系資料失敗";
break;
case AttFileErrState.AttIdIsRequired:
errMsg = "請提供 AttId";
break;
}
return errMsg;
}
} | 29.337778 | 77 | 0.439176 | [
"MIT"
] | lozenlin/SampleCMS | Source/Root/App_Code/ResUtility.cs | 6,799 | C# |
/*
* eZmax API Definition (Full)
*
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.7
* Contact: support-api@ezmax.ca
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = eZmaxApi.Client.OpenAPIDateConverter;
namespace eZmaxApi.Model
{
/// <summary>
/// Payload for GET /1/object/ezsigntemplatedocument/{pkiEzsigntemplatedocument}/getEzsigntemplateformfieldgroups
/// </summary>
[DataContract(Name = "ezsigntemplatedocument-getEzsigntemplateformfieldgroups-v1-Response-mPayload")]
public partial class EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload : IEquatable<EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload" /> class.
/// </summary>
[JsonConstructorAttribute]
protected EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload() { }
/// <summary>
/// Initializes a new instance of the <see cref="EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload" /> class.
/// </summary>
/// <param name="aObjEzsigntemplateformfieldgroup">aObjEzsigntemplateformfieldgroup (required).</param>
public EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload(List<EzsigntemplateformfieldgroupResponseCompound> aObjEzsigntemplateformfieldgroup = default(List<EzsigntemplateformfieldgroupResponseCompound>))
{
// to ensure "aObjEzsigntemplateformfieldgroup" is required (not null)
if (aObjEzsigntemplateformfieldgroup == null)
{
throw new ArgumentNullException("aObjEzsigntemplateformfieldgroup is a required property for EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload and cannot be null");
}
this.AObjEzsigntemplateformfieldgroup = aObjEzsigntemplateformfieldgroup;
}
/// <summary>
/// Gets or Sets AObjEzsigntemplateformfieldgroup
/// </summary>
[DataMember(Name = "a_objEzsigntemplateformfieldgroup", IsRequired = true, EmitDefaultValue = false)]
public List<EzsigntemplateformfieldgroupResponseCompound> AObjEzsigntemplateformfieldgroup { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload {\n");
sb.Append(" AObjEzsigntemplateformfieldgroup: ").Append(AObjEzsigntemplateformfieldgroup).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload);
}
/// <summary>
/// Returns true if EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload instances are equal
/// </summary>
/// <param name="input">Instance of EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload input)
{
if (input == null)
{
return false;
}
return
(
this.AObjEzsigntemplateformfieldgroup == input.AObjEzsigntemplateformfieldgroup ||
this.AObjEzsigntemplateformfieldgroup != null &&
input.AObjEzsigntemplateformfieldgroup != null &&
this.AObjEzsigntemplateformfieldgroup.SequenceEqual(input.AObjEzsigntemplateformfieldgroup)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AObjEzsigntemplateformfieldgroup != null)
{
hashCode = (hashCode * 59) + this.AObjEzsigntemplateformfieldgroup.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 43.12766 | 234 | 0.674396 | [
"MIT"
] | ezmaxinc/eZmax-SDK-csharp-netcore | src/eZmaxApi/Model/EzsigntemplatedocumentGetEzsigntemplateformfieldgroupsV1ResponseMPayload.cs | 6,081 | C# |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using Witsml;
using Witsml.Extensions;
using Witsml.ServiceReference;
using WitsmlExplorer.Api.Jobs;
using WitsmlExplorer.Api.Models;
using WitsmlExplorer.Api.Query;
using WitsmlExplorer.Api.Services;
namespace WitsmlExplorer.Api.Workers
{
public class CreateWellWorker : BaseWorker<CreateWellJob>, IWorker
{
private readonly IWitsmlClient witsmlClient;
public JobType JobType => JobType.CreateWell;
public CreateWellWorker(IWitsmlClientProvider witsmlClientProvider)
{
witsmlClient = witsmlClientProvider.GetClient();
}
public override async Task<(WorkerResult, RefreshAction)> Execute(CreateWellJob job)
{
var well = job.Well;
Verify(well);
var wellToCreate = WellQueries.CreateWitsmlWell(well);
var result = await witsmlClient.AddToStoreAsync(wellToCreate);
if (result.IsSuccessful)
{
Log.Information("{JobType} - Job successful", GetType().Name);
await WaitUntilWellHasBeenCreated(well);
var workerResult = new WorkerResult(witsmlClient.GetServerHostname(), true, $"Well created ({well.Name} [{well.Uid}])");
var refreshAction = new RefreshWell(witsmlClient.GetServerHostname(), well.Uid, RefreshType.Add);
return (workerResult, refreshAction);
}
var description = new EntityDescription { WellName = well.Name };
Log.Error("Job failed. An error occurred when creating well: {Well}", job.Well.PrintProperties());
return (new WorkerResult(witsmlClient.GetServerHostname(), false, "Failed to create well", result.Reason, description), null);
}
private async Task WaitUntilWellHasBeenCreated(Well well)
{
var isWellCreated = false;
var query = WellQueries.GetWitsmlWellByUid(well.Uid);
var maxRetries = 30;
while (!isWellCreated)
{
if (--maxRetries == 0)
{
throw new InvalidOperationException($"Not able to read newly created well with name {well.Name} (id={well.Uid})");
}
Thread.Sleep(1000);
var wellResult = await witsmlClient.GetFromStoreAsync(query, new OptionsIn(ReturnElements.IdOnly));
isWellCreated = wellResult.Wells.Any();
}
}
private static void Verify(Well well)
{
if (string.IsNullOrEmpty(well.Uid)) throw new InvalidOperationException($"{nameof(well.Uid)} cannot be empty");
if (string.IsNullOrEmpty(well.Name)) throw new InvalidOperationException($"{nameof(well.Name)} cannot be empty");
if (string.IsNullOrEmpty(well.TimeZone)) throw new InvalidOperationException($"{nameof(well.TimeZone)} cannot be empty");
}
}
}
| 41.680556 | 138 | 0.641786 | [
"Apache-2.0"
] | AtleH/witsml-explorer | Src/WitsmlExplorer.Api/Workers/CreateWellWorker.cs | 3,001 | C# |
/*
* ARXivar Workflow API
*
* ARXivar Workflow API
*
* OpenAPI spec version: v1
* Contact: info@abletech.it
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = IO.Swagger.Workflow.Client.SwaggerDateConverter;
namespace IO.Swagger.Workflow.Model
{
/// <summary>
/// OperationConfigurationExecuteSqlQueryRm
/// </summary>
[DataContract]
public partial class OperationConfigurationExecuteSqlQueryRm : OperationsConfigurationRm, IEquatable<OperationConfigurationExecuteSqlQueryRm>
{
/// <summary>
/// Initializes a new instance of the <see cref="OperationConfigurationExecuteSqlQueryRm" /> class.
/// </summary>
/// <param name="sqlInfo">sqlInfo (required).</param>
public OperationConfigurationExecuteSqlQueryRm(SqlQueryConfigurationInfoRm sqlInfo = default(SqlQueryConfigurationInfoRm), int? operationType = default(int?), OperationRetryConfigurationRm retryConfiguration = default(OperationRetryConfigurationRm), EventInfoRm onErrorEventConfiguration = default(EventInfoRm), EventInfoRm onFailedEventConfiguration = default(EventInfoRm), bool? invalidateOtherOperations = default(bool?), string userDescription = default(string)) : base(operationType, retryConfiguration, onErrorEventConfiguration, onFailedEventConfiguration, invalidateOtherOperations, userDescription)
{
// to ensure "sqlInfo" is required (not null)
if (sqlInfo == null)
{
throw new InvalidDataException("sqlInfo is a required property for OperationConfigurationExecuteSqlQueryRm and cannot be null");
}
else
{
this.SqlInfo = sqlInfo;
}
}
/// <summary>
/// Gets or Sets SqlInfo
/// </summary>
[DataMember(Name="sqlInfo", EmitDefaultValue=false)]
public SqlQueryConfigurationInfoRm SqlInfo { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OperationConfigurationExecuteSqlQueryRm {\n");
sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n");
sb.Append(" SqlInfo: ").Append(SqlInfo).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public override string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as OperationConfigurationExecuteSqlQueryRm);
}
/// <summary>
/// Returns true if OperationConfigurationExecuteSqlQueryRm instances are equal
/// </summary>
/// <param name="input">Instance of OperationConfigurationExecuteSqlQueryRm to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OperationConfigurationExecuteSqlQueryRm input)
{
if (input == null)
return false;
return base.Equals(input) &&
(
this.SqlInfo == input.SqlInfo ||
(this.SqlInfo != null &&
this.SqlInfo.Equals(input.SqlInfo))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = base.GetHashCode();
if (this.SqlInfo != null)
hashCode = hashCode * 59 + this.SqlInfo.GetHashCode();
return hashCode;
}
}
}
}
| 38.130081 | 615 | 0.621109 | [
"Apache-2.0"
] | zanardini/ARXivarNext-WebApi | ARXivarNext-ConsumingWebApi/IO.Swagger.Workflow/Model/OperationConfigurationExecuteSqlQueryRm.cs | 4,690 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReturningPassingDataLecture
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("You’re learning how to program!");
Console.WriteLine(ReturnCongratsMessage());
Console.WriteLine("You’re doing so well!");
Console.WriteLine(ReturnCongratsMessage());
Console.WriteLine("You’re going to be rich!");
Console.WriteLine(ReturnCongratsMessage());
Console.ReadKey();
}
static string ReturnCongratsMessage()
{
return "Congratulations!";
}
}
}
| 22.454545 | 65 | 0.611336 | [
"MIT"
] | PacktPublishing/Learn-How-to-Code-Using-C-The-Basics-of-Programming | CODES/CSharpSourceCode/Lecture Code/19 ReturningPassingDataLecture/ReturningPassingDataLecture/Program.cs | 749 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Text;
namespace EvieCompilerSystem.InputOutput
{
/// <summary>
/// Functions to encode and decode values behind NaN tags in 64-bit blocks
/// </summary>
public static class NanTags
{
const ulong NAN_FLAG = 0x7FF8000000000000; // Bits to make a quiet NaN
const ulong UPPER_FOUR = 0x8007000000000000; // mask for top 4 available bits
const ulong LOWER_32 = 0x00000000FFFFFFFF; // low 32 bits
const ulong LOWER_48 = 0x0000FFFFFFFFFFFF; // 48 bits for pointers, all non TAG data
const ulong ALLOC_FLAG = 0x8000000000000000; // Tags are arranged so GC types have this bit set
// Mask with "UPPER_FOUR" then check against these:
const ulong TAG_NAR = 0;
const ulong TAG_VAR_REF = (ulong)DataType.VariableRef << 32;
const ulong TAG_OPCODE = (ulong)DataType.Opcode << 32;
const ulong TAG_INT32_VAL = (ulong)DataType.ValInt32 << 32;
const ulong TAG_UINT32_VAL = (ulong)DataType.ValUInt32 << 32;
const ulong TAG_SMALL_STR = (ulong)DataType.ValSmallString << 32;
const ulong TAG_PTR_DEBUG = (ulong)DataType.PtrStaticString << 32; // it is a pointer, but it's not allocated
const ulong TAG_UNUSED_VAL_1 = (ulong)DataType.UNUSED_VAL_1 << 32;
const ulong TAG_PTR_SET = (ulong)DataType.PtrSet << 32;
const ulong TAG_PTR_VECTOR = (ulong)DataType.PtrVector << 32;
const ulong TAG_PTR_STR = (ulong)DataType.PtrString << 32;
const ulong TAG_PTR_TABLE = (ulong)DataType.PtrHashtable << 32;
const ulong TAG_PTR_GRID = (ulong)DataType.PtrGrid << 32;
const ulong TAG_UNUSED_PTR_1 = (ulong)DataType.UNUSED_PTR_1 << 32;
const ulong TAG_UNUSED_PTR_2 = (ulong)DataType.UNUSED_PTR_2 << 32;
const ulong TAG_UNUSED_PTR_3 = (ulong)DataType.UNUSED_PTR_3 << 32;
/// <summary>
/// Read tagged type
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe DataType TypeOf(double unknown)
{
var bits = *(ulong*)&unknown;
if ((bits & NAN_FLAG) != NAN_FLAG) return DataType.Number;
var tag = (bits & UPPER_FOUR) >> 32;
return (DataType)tag;
}
/// <summary>
/// Returns true if this token is a pointer to allocated data.
/// Returns false if this token is a direct value
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsAllocated(double token)
{
var bits = *(ulong*)&token;
return (ALLOC_FLAG & bits) > 0;
}
/// <summary>
/// Return the tag bits for a DataType
/// </summary>
public static ulong TagFor(DataType type)
{
switch (type)
{
case DataType.NoValue: return TAG_NAR;
case DataType.VariableRef: return TAG_VAR_REF;
case DataType.Opcode: return TAG_OPCODE;
case DataType.ValInt32: return TAG_INT32_VAL;
case DataType.ValUInt32: return TAG_UINT32_VAL;
case DataType.ValSmallString: return TAG_SMALL_STR;
case DataType.PtrStaticString: return TAG_PTR_DEBUG;
case DataType.PtrString: return TAG_PTR_STR;
case DataType.PtrHashtable: return TAG_PTR_TABLE;
case DataType.PtrGrid: return TAG_PTR_GRID;
case DataType.PtrSet: return TAG_PTR_SET;
case DataType.PtrVector: return TAG_PTR_VECTOR;
case DataType.UNUSED_PTR_1: return TAG_UNUSED_PTR_1;
case DataType.UNUSED_PTR_2: return TAG_UNUSED_PTR_2;
case DataType.UNUSED_PTR_3: return TAG_UNUSED_PTR_3;
case DataType.UNUSED_VAL_1: return TAG_UNUSED_VAL_1;
default:
throw new Exception("Invalid data type");
}
}
/// <summary>
/// Value tagged as an non return type
/// </summary>
public static unsafe double VoidReturn()
{
unchecked
{
ulong encoded = NAN_FLAG | TAG_NAR | (ulong)NonValueType.Void;
return *(double*)&encoded;//BitConverter.Int64BitsToDouble((long)encoded);
}
}
/// <summary>
/// Encode a tagged non-value tag
/// </summary>
public static unsafe double EncodeNonValue(NonValueType type)
{
unchecked
{
ulong encoded = NAN_FLAG | TAG_NAR | ((ulong)type);
return *(double*)&encoded;
}
}
/// <summary>
/// Read the tag from a non value tag
/// </summary>
public static unsafe NonValueType DecodeNonValue(double encoded) {
unchecked
{
int tag = (int)((*(ulong*)&encoded) & LOWER_32);
return (NonValueType)tag;
}
}
/// <summary>
/// Encode an op-code with up to 2x16 bit params
/// </summary>
/// <param name="codeClass">Kind of op code</param>
/// <param name="codeAction">The action to perform in the class</param>
/// <param name="p1">First parameter, if used</param>
/// <param name="p2">Second parameter if used</param>
public static unsafe double EncodeOpcode(char codeClass, char codeAction, ushort p1, ushort p2)
{
unchecked
{
byte cc = (byte)codeClass;
byte ca = (byte)codeAction;
ulong encoded =
NAN_FLAG
| TAG_OPCODE
| ((ulong)cc << 40)
| ((ulong)ca << 32)
| ((ulong)p1 << 16)
| p2
;
return *(double*)&encoded;
}
}
/// <summary>
/// Encode an op-code with up to 2x16 bit params
/// </summary>
/// <param name="codeClass">Kind of op code</param>
/// <param name="codeAction">The action to perform in the class</param>
/// <param name="p1">First parameter, if used</param>
/// <param name="p2">Second parameter if used</param>
public static unsafe double EncodeOpcode(char codeClass, byte codeAction, ushort p1, ushort p2)
{
unchecked
{
byte cc = (byte)codeClass;
byte ca = codeAction;
ulong encoded =
NAN_FLAG
| TAG_OPCODE
| ((ulong)cc << 40)
| ((ulong)ca << 32)
| ((ulong)p1 << 16)
| p2
;
return *(double*)&encoded;
}
}
/// <summary>
/// Encode an op-code with one 32 bit param
/// </summary>
/// <param name="codeClass">Kind of op code</param>
/// <param name="codeAction">The action to perform in the class</param>
/// <param name="p1">First parameter, if used</param>
public static double EncodeLongOpcode(char codeClass, char codeAction, uint p1)
{
unchecked
{
byte cc = (byte)codeClass;
byte ca = (byte)codeAction;
ulong encoded =
NAN_FLAG
| TAG_OPCODE
| ((ulong)cc << 40)
| ((ulong)ca << 32)
| p1
;
return BitConverter.Int64BitsToDouble((long)encoded);
}
}
/// <summary>
/// Read an opcode out of a tagged nan
/// </summary>
/// <param name="encoded">The tagged value</param>
/// <param name="codeClass">class of op code</param>
/// <param name="codeAction">action of op code</param>
/// <param name="p1">first param</param>
/// <param name="p2">second param</param>
public static unsafe void DecodeOpCode(double encoded, out char codeClass, out char codeAction, out ushort p1, out ushort p2)
{
unchecked
{
var enc = LOWER_48 & (*(ulong*)&encoded);
codeClass = (char)(enc >> 40);
codeAction = (char)(0xFF & (enc >> 32));
p1 = (ushort)(enc >> 16);
p2 = (ushort)enc;
}
}
/// <summary>
/// Read an opcode out of a tagged nan, combining the two parameters into a single longer one
/// </summary>
/// <param name="encoded">The tagged value</param>
/// <param name="codeClass">class of op code</param>
/// <param name="codeAction">action of op code</param>
/// <param name="p1">first param and second param combined</param>
public static unsafe void DecodeLongOpCode(double encoded, out char codeClass, out char codeAction, out uint p1)
{
unchecked
{
var enc = LOWER_48 & (*(ulong*)&encoded);
codeClass = (char)(enc >> 40);
codeAction = (char)(0xFF & (enc >> 32));
p1 = (uint)enc;
}
}
/// <summary>
/// Crush and encode a name (such as a function or variable name) as a variable ref
/// </summary>
/// <param name="fullName">Full name of the identifier</param>
/// <param name="crushedName">Output crushed name</param>
/// <returns>Encoded data</returns>
public static unsafe double EncodeVariableRef(string fullName, out uint crushedName)
{
unchecked
{
crushedName = prospector32s(fullName.ToCharArray(), (uint)fullName.Length);
ulong raw = NAN_FLAG | TAG_VAR_REF | crushedName;
return *(double*)&raw;
}
}
/// <summary>
/// Encode an already crushed name as a variable ref
/// </summary>
public static unsafe double EncodeVariableRef(uint crushedName)
{
uint nse = crushedName;
ulong raw = NAN_FLAG | TAG_VAR_REF | nse;
return *(double*)&raw;
}
/// <summary>
/// Get hash code of names, as created by variable reference op codes
/// </summary>
public static uint GetCrushedName(string fullName) {
unchecked
{
return prospector32s(fullName.ToCharArray(), (uint)fullName.Length);
}
}
/// <summary>
/// Extract an encoded reference name from a double
/// </summary>
public static unsafe uint DecodeVariableRef(double encoded)
{
unchecked{
var raw = LOWER_32 & (*(ulong*)&encoded);
return (uint)raw;
}
}
/// <summary>
/// Encode a pointer with a type
/// </summary>
public static double EncodePointer(long target, DataType type)
{
unchecked
{
return BitConverter.Int64BitsToDouble((long)(NAN_FLAG | TagFor(type) | ((ulong)target & LOWER_48)));
}
}
/// <summary>
/// Decode a pointer and type
/// </summary>
public static unsafe void DecodePointer(double encoded, out long target, out DataType type)
{
unchecked
{
type = TypeOf(encoded);
target = (long)((*(ulong*)&encoded) & LOWER_48);
}
}
/// <summary>
/// Decode a pointer
/// </summary>
public static unsafe long DecodePointer(double encoded)
{
unchecked
{
return (long)((*(ulong*)&encoded) & LOWER_48);
}
}
/// <summary>
/// Encode an int32
/// </summary>
public static double EncodeInt32(int original)
{
unchecked
{
return BitConverter.Int64BitsToDouble((long)(NAN_FLAG | TAG_INT32_VAL | ((ulong)original & LOWER_32)));
}
}
/// <summary>
/// Decode an int32
/// </summary>
public static unsafe int DecodeInt32(double encoded)
{
unchecked
{
return (int)((*(ulong*)&encoded) & LOWER_32);
}
}
/// <summary>
/// Encode an unsigned int32
/// </summary>
public static double EncodeUInt32(uint original)
{
unchecked
{
return BitConverter.Int64BitsToDouble((long)(NAN_FLAG | TAG_UINT32_VAL | (original & LOWER_32)));
}
}
/// <summary>
/// Decode an unsigned int32
/// </summary>
public static unsafe uint DecodeUInt32(double encoded)
{
unchecked
{
return (uint)((*(ulong*)&encoded) & LOWER_32);
}
}
/// <summary>
/// Low bias 32 bit hash
/// </summary>
static uint prospector32s(char[] buf, uint key)
{
unchecked
{
uint hash = key;
for (int i = 0; i < buf.Length; i++)
{
hash += buf[i];
hash ^= hash >> 16;
hash *= 0x7feb352d;
hash ^= hash >> 15;
hash *= 0x846ca68b;
hash ^= hash >> 16;
}
hash ^= (uint)buf.Length;
hash ^= hash >> 16;
hash *= 0x7feb352d;
hash ^= hash >> 15;
hash *= 0x846ca68b;
hash ^= hash >> 16;
return hash + key;
}
}
/// <summary>
/// Encode a boolean. We use Int32, 0 = false
/// </summary>
public static double EncodeBool(bool b)
{
return EncodeInt32(b ? -1 : 0);
}
/// <summary>
/// Decode a short string
/// </summary>
public static unsafe string DecodeShortStr(double token)
{
var sb = new StringBuilder(6);
var bits = *(ulong*)&token;
for (int i = 5; i >= 0; i--)
{
var cv = (bits >> (i * 8)) & 0xFF;
if (cv == 0) break;
sb.Append((char)cv);
}
return sb.ToString();
}
/// <summary>
/// Encode a string of 6 characters or less
/// </summary>
public static unsafe double EncodeShortStr(string str)
{
unchecked{
var len = str.Length;
if (len > 6) throw new Exception();
var tag = NAN_FLAG | TAG_SMALL_STR;
for (int i = 0; i < len; i++)
{
var bv = (byte)str[i];
var ulv = (ulong)bv;
tag |= ulv << ((5 - i) * 8);
}
return *(double*)&tag;
}
}
/// <summary>
/// Get raw data of tags
/// </summary>
public static unsafe ulong DecodeRaw(double d)
{
return *(ulong*)&d;
}
/// <summary>
/// Diagnostic description of a token
/// </summary>
public static string Describe(double token)
{
var type = TypeOf(token);
switch (type){
case DataType.NoValue: return "Non value";
case DataType.Opcode: return "Opcode";
case DataType.VariableRef: return "VariableNameRef ["+DecodeVariableRef(token)+"]";
case DataType.PtrString: return "Pointer: String ["+DecodePointer(token)+"]";
case DataType.PtrStaticString: return "Pointer: Static Str ["+DecodePointer(token)+"]";
case DataType.PtrHashtable: return "Pointer: Hashtable ["+DecodePointer(token)+"]";
case DataType.PtrGrid: return "Pointer: Grid ["+DecodePointer(token)+"]";
case DataType.PtrVector: return "Pointer: Linked List ["+DecodePointer(token)+"]";
case DataType.UNUSED_PTR_2: return "Pointer: String Array ["+DecodePointer(token)+"]";
case DataType.UNUSED_PTR_3: return "Pointer: Double Array ["+DecodePointer(token)+"]";
case DataType.PtrSet: return "Pointer: String Set ["+DecodePointer(token)+"]";
case DataType.UNUSED_PTR_1: return "Pointer: Int32 Set ["+DecodePointer(token)+"]";
case DataType.Number: return "Double ["+token+"]";
case DataType.ValInt32: return "Int32 ["+DecodeInt32(token)+"]";
case DataType.ValUInt32: return "UInt32 [" + DecodeUInt32(token) + "]";
case DataType.ValSmallString: return "Short String [" + DecodeShortStr(token) + "]";
case DataType.UNUSED_VAL_1: return "UNUSED TOKEN";
default:
return "Invalid token";
}
}
}
} | 35.601215 | 133 | 0.504577 | [
"MIT"
] | i-e-b/CompiledScript | EvieCompilerSystem/InputOutput/NanTags.cs | 17,589 | C# |
using NUnit.Framework;
using QuestPDF.Elements;
using QuestPDF.Infrastructure;
using QuestPDF.UnitTests.TestEngine;
namespace QuestPDF.UnitTests
{
[TestFixture]
public class BackgroundTests
{
[Test]
public void Measure_ShouldHandleNullChild() => new Background().MeasureWithoutChild();
[Test]
public void Draw_ShouldHandleNullChild()
{
TestPlan
.For(x => new Background
{
Color = "#F00"
})
.DrawElement(new Size(400, 300))
.ExpectCanvasDrawRectangle(new Position(0, 0), new Size(400, 300), "#F00")
.CheckDrawResult();
}
[Test]
public void Draw_ShouldHandleChild()
{
TestPlan
.For(x => new Background
{
Color = "#F00",
Child = x.CreateChild("a")
})
.DrawElement(new Size(400, 300))
.ExpectCanvasDrawRectangle(new Position(0, 0), new Size(400, 300), "#F00")
.ExpectChildDraw("a", new Size(400, 300))
.CheckDrawResult();
}
}
} | 29.119048 | 94 | 0.500409 | [
"MIT"
] | lmingle/library | QuestPDF.UnitTests/BackgroundTests.cs | 1,225 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.ConnectedVMwarevSphere.Models;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Resources;
namespace Azure.ResourceManager.ConnectedVMwarevSphere
{
/// <summary> A class representing collection of VMwareHost and their operations over its parent. </summary>
public partial class VMwareHostCollection : ArmCollection, IEnumerable<VMwareHost>, IAsyncEnumerable<VMwareHost>
{
private readonly ClientDiagnostics _vMwareHostHostsClientDiagnostics;
private readonly HostsRestOperations _vMwareHostHostsRestClient;
/// <summary> Initializes a new instance of the <see cref="VMwareHostCollection"/> class for mocking. </summary>
protected VMwareHostCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="VMwareHostCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal VMwareHostCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_vMwareHostHostsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ConnectedVMwarevSphere", VMwareHost.ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(VMwareHost.ResourceType, out string vMwareHostHostsApiVersion);
_vMwareHostHostsRestClient = new HostsRestOperations(_vMwareHostHostsClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, vMwareHostHostsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceGroup.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceGroup.ResourceType), nameof(id));
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Create
/// <summary> Create Or Update host. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="hostName"> Name of the host. </param>
/// <param name="body"> Request payload. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public async virtual Task<VMwareHostCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, string hostName, VMwareHostData body = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _vMwareHostHostsRestClient.CreateAsync(Id.SubscriptionId, Id.ResourceGroupName, hostName, body, cancellationToken).ConfigureAwait(false);
var operation = new VMwareHostCreateOrUpdateOperation(Client, _vMwareHostHostsClientDiagnostics, Pipeline, _vMwareHostHostsRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, hostName, body).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Create
/// <summary> Create Or Update host. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="hostName"> Name of the host. </param>
/// <param name="body"> Request payload. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public virtual VMwareHostCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, string hostName, VMwareHostData body = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _vMwareHostHostsRestClient.Create(Id.SubscriptionId, Id.ResourceGroupName, hostName, body, cancellationToken);
var operation = new VMwareHostCreateOrUpdateOperation(Client, _vMwareHostHostsClientDiagnostics, Pipeline, _vMwareHostHostsRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, hostName, body).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Get
/// <summary> Implements host GET method. </summary>
/// <param name="hostName"> Name of the host. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public async virtual Task<Response<VMwareHost>> GetAsync(string hostName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.Get");
scope.Start();
try
{
var response = await _vMwareHostHostsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, hostName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _vMwareHostHostsClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VMwareHost(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Get
/// <summary> Implements host GET method. </summary>
/// <param name="hostName"> Name of the host. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public virtual Response<VMwareHost> Get(string hostName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.Get");
scope.Start();
try
{
var response = _vMwareHostHostsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, hostName, cancellationToken);
if (response.Value == null)
throw _vMwareHostHostsClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VMwareHost(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_ListByResourceGroup
/// <summary> List of hosts in a resource group. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="VMwareHost" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<VMwareHost> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<VMwareHost>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.GetAll");
scope.Start();
try
{
var response = await _vMwareHostHostsRestClient.ListByResourceGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VMwareHost(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<VMwareHost>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.GetAll");
scope.Start();
try
{
var response = await _vMwareHostHostsRestClient.ListByResourceGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VMwareHost(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_ListByResourceGroup
/// <summary> List of hosts in a resource group. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="VMwareHost" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<VMwareHost> GetAll(CancellationToken cancellationToken = default)
{
Page<VMwareHost> FirstPageFunc(int? pageSizeHint)
{
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.GetAll");
scope.Start();
try
{
var response = _vMwareHostHostsRestClient.ListByResourceGroup(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VMwareHost(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<VMwareHost> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.GetAll");
scope.Start();
try
{
var response = _vMwareHostHostsRestClient.ListByResourceGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VMwareHost(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Get
/// <summary> Checks to see if the resource exists in azure. </summary>
/// <param name="hostName"> Name of the host. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string hostName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(hostName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Get
/// <summary> Checks to see if the resource exists in azure. </summary>
/// <param name="hostName"> Name of the host. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public virtual Response<bool> Exists(string hostName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(hostName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Get
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="hostName"> Name of the host. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public async virtual Task<Response<VMwareHost>> GetIfExistsAsync(string hostName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.GetIfExists");
scope.Start();
try
{
var response = await _vMwareHostHostsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, hostName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<VMwareHost>(null, response.GetRawResponse());
return Response.FromValue(new VMwareHost(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/hosts/{hostName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
/// OperationId: Hosts_Get
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="hostName"> Name of the host. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="hostName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="hostName"/> is null. </exception>
public virtual Response<VMwareHost> GetIfExists(string hostName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(hostName, nameof(hostName));
using var scope = _vMwareHostHostsClientDiagnostics.CreateScope("VMwareHostCollection.GetIfExists");
scope.Start();
try
{
var response = _vMwareHostHostsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, hostName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<VMwareHost>(null, response.GetRawResponse());
return Response.FromValue(new VMwareHost(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<VMwareHost> IEnumerable<VMwareHost>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<VMwareHost> IAsyncEnumerable<VMwareHost>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 55.783641 | 246 | 0.654385 | [
"MIT"
] | danielortega-msft/azure-sdk-for-net | sdk/connectedvmwarevsphere/Azure.ResourceManager.ConnectedVMwarevSphere/src/Generated/VMwareHostCollection.cs | 21,142 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// AOP API: alipay.eco.edu.kt.student.query
/// </summary>
public class AlipayEcoEduKtStudentQueryRequest : IAlipayRequest<AlipayEcoEduKtStudentQueryResponse>
{
/// <summary>
/// 学生信息查询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return returnUrl;
}
public void SetTerminalType(string terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return terminalType;
}
public void SetTerminalInfo(string terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return terminalInfo;
}
public void SetProdCode(string prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return prodCode;
}
public string GetApiName()
{
return "alipay.eco.edu.kt.student.query";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.445455 | 103 | 0.595967 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayEcoEduKtStudentQueryRequest.cs | 2,591 | C# |
using System;
using Android.App;
using Android.Content;
using Android.Locations;
using Android.Runtime;
using Android.Views;
using Android.Preferences;
using System.Collections.Generic;
using Android.Widget;
using Android.OS;
using System.Json;
using Android.Gms.Location.Places.UI;
using Android;
using Android.Content.PM;
using Android.Support.V4.App;
namespace Elected.Droid
{
[Activity (Label = "Elected!", MainLauncher = true, Icon = "@drawable/elected")]
public class MainActivity : Activity, JsonParser.IPhotosLoadedListner
{
private ISharedPreferences mPreferences;
private string address;
private TextView addressView;
private ListView listViewReps;
private TextView listViewEmptyView;
private TextView listViewEmptyViewElecs;
private ListView listViewElecs;
private RepresentativeAdapter adapterReps;
private BaseAdapter adapterElecs;
public static JsonParser parser;
public static List<Representative> Representatives = new List<Representative>();
public static List<Election> Elections = new List<Election>();
private Button showReps;
private Button showElecs;
private readonly int PLACE_PICKER_ID = 9999;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
checkPermissions();
ShowDisclaimer();
parser = new JsonParser(this);
mPreferences = PreferenceManager.GetDefaultSharedPreferences(this);
address = mPreferences.GetString("address", "1600 Pennsylvania AVE NW Washington DC");
// Get our button from the layout resource,
// and attach an event to it
Button buttonSetAddress = FindViewById<Button>(Resource.Id.buttonChangeAddress);
addressView = FindViewById<TextView>(Resource.Id.textViewAddress);
listViewReps = FindViewById<ListView>(Resource.Id.listView1);
adapterReps = new RepresentativeAdapter(this, Representatives);
listViewReps.Adapter = adapterReps;
adapterElecs = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, Elections);
listViewEmptyView = FindViewById<TextView>(Resource.Id.listViewEmptyView);
listViewReps.EmptyView = listViewEmptyView;
addressView.Text = address;
listViewElecs = FindViewById<ListView>(Resource.Id.listView2);
listViewEmptyViewElecs = FindViewById<TextView>(Resource.Id.listViewEmptyViewElecs);
listViewReps.ItemClick += RepsListView_ItemClick;
listViewElecs.ItemClick += ListViewElecs_ItemClick;
buttonSetAddress.Click += delegate
{
var builder = new PlacePicker.IntentBuilder();
StartActivityForResult(builder.Build(this), PLACE_PICKER_ID);
};
showReps = FindViewById<Button>(Resource.Id.buttonShowReps);
showReps.Click += delegate
{
showRepData();
};
showElecs = FindViewById<Button>(Resource.Id.buttonShowElecs);
showElecs.Click += delegate
{
showElectionData();
};
}
private void ListViewElecs_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
int index = e.Position;
string electionId = Elections[index].id;
if (!string.IsNullOrEmpty(electionId))
{
Intent intent = new Intent(this, typeof(ElectionDetailActivity));
intent.PutExtra("index", electionId);
StartActivity(intent);
}
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if (requestCode == PLACE_PICKER_ID && resultCode == Result.Ok)
{
var placePicked = PlacePicker.GetPlace(data, this);
address = placePicked.AddressFormatted.ToString();
addressView.Text = address;
ISharedPreferencesEditor editor = mPreferences.Edit();
editor.PutString("address", address);
editor.Commit();
loadRepData();
loadElectionData();
}
base.OnActivityResult(requestCode, resultCode, data);
}
private void RepsListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
int index = e.Position;
Intent intent = new Intent(this, typeof(RepresentativeDetailActivity));
intent.PutExtra("index", index);
StartActivity(intent);
}
private async void loadRepData()
{
JsonValue jsonResponse = await VoterHttpRequest.FetchRepresentativesAsync(address, this);
if (jsonResponse != null)
{
Representatives = parser.ParseRepresentativeJson(jsonResponse);
} else
{
Toast.MakeText(this, "no result retrieved", ToastLength.Long).Show();
}
adapterReps.setDataSet(Representatives);
showRepData();
}
private void showRepData()
{
showReps.SetBackgroundColor(Android.Graphics.Color.CadetBlue);
showElecs.SetBackgroundColor(Android.Graphics.Color.Black);
listViewReps.Visibility = Android.Views.ViewStates.Visible;
listViewElecs.Visibility = ViewStates.Gone;
}
private async void loadElectionData()
{
JsonValue jsonResponse = await VoterHttpRequest.FetchVoterInfoAsync(address, this);
if (jsonResponse != null)
{
Elections = parser.ParseElectionJson(jsonResponse);
adapterElecs = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, Elections);
listViewElecs.Adapter = adapterElecs;
listViewElecs.Visibility = ViewStates.Gone;
}
else
{
Elections = new List<Election> { new Election { name = "no election data found", date = "election info may not be available more than 2-4 weeks prior" } };
adapterElecs = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, Elections);
listViewElecs.Adapter = adapterElecs;
listViewElecs.Visibility = ViewStates.Gone;
}
}
private void showElectionData()
{
showReps.SetBackgroundColor(Android.Graphics.Color.Black);
showElecs.SetBackgroundColor(Android.Graphics.Color.CadetBlue);
listViewReps.Visibility = Android.Views.ViewStates.Gone;
listViewElecs.Visibility = ViewStates.Visible;
}
public void OnPhotosLoaded(List<Representative> data)
{
Representatives = data;
adapterReps.setDataSet(Representatives);
}
private void checkPermissions()
{
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessNetworkState,
Manifest.Permission.WriteExternalStorage }, 9999);
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
if (CheckSelfPermission(Manifest.Permission.AccessNetworkState) == (int)Permission.Granted &&
CheckSelfPermission(Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
{
loadRepData();
loadElectionData();
}
//base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void ShowDisclaimer()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage("Elected! displays data from an online resource. Elected! does not create, edit, maintain, or check this data. " +
"This data is provide on a volunteer basis by individual districts. Some areas may require the address of a registered voter be used. " +
"Thank you for checking out Elected! Please share with your friends and use your power to vote.");
builder.SetPositiveButton("Dismiss", (s,e) => { });
AlertDialog ad = builder.Create();
ad.Show();
}
}
}
| 40.171296 | 171 | 0.62925 | [
"MIT"
] | rznazn/Elected | Elected/Elected.Android/MainActivity.cs | 8,679 | C# |
using HarmonyLib;
using PlayerTrade.Trade;
using RimWorld;
namespace PlayerTrade.Patches
{
[HarmonyPatch(typeof(Tradeable), "Interactive", MethodType.Getter)]
public static class Patch_Tradeable_Interactive
{
private static void Postfix(ref bool __result)
{
if (TradeSession.trader is PlayerTrader)
{
__result = true; // force
}
}
}
}
| 22.578947 | 71 | 0.615385 | [
"MIT"
] | mitchfizz05/RimLink | Source/PlayerTrade/PlayerTrade/Patches/Patch_Tradeable_Interactive.cs | 431 | C# |
#pragma checksum "..\..\MainWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "BAB5AE8810E9AC47D5BB1A30D6AAF47B38666A27"
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
using MultiPNG2Gif;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace MultiPNG2Gif {
/// <summary>
/// MainWindow
/// </summary>
public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 20 "..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.CheckBox ofap;
#line default
#line hidden
#line 21 "..\..\MainWindow.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox sprite_name;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/MultiPNG2Gif;component/mainwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\MainWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
#line 8 "..\..\MainWindow.xaml"
((MultiPNG2Gif.MainWindow)(target)).Loaded += new System.Windows.RoutedEventHandler(this.Window_Loaded);
#line default
#line hidden
return;
case 2:
#line 18 "..\..\MainWindow.xaml"
((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Click);
#line default
#line hidden
return;
case 3:
this.ofap = ((System.Windows.Controls.CheckBox)(target));
return;
case 4:
this.sprite_name = ((System.Windows.Controls.ComboBox)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 37.709402 | 141 | 0.629193 | [
"MIT"
] | dima13230/neira-engine | MultiPNG2Gif/obj/Debug/MainWindow.g.cs | 4,548 | C# |
using UnityEngine;
using System;
using System.Collections.Generic;
namespace DragonU3DSDK
{
public class TimerManager : Manager<TimerManager>
{
List<Action<float>> timerDelegates = new List<Action<float>>();
List<Action<float>> updateList = new List<Action<float>>();
public void AddDelegate(Action<float> action)
{
if (action != null)
{
timerDelegates.Add(action);
}
}
void Update()
{
if (timerDelegates.Count > 0)
{
var deltaTime = Time.deltaTime;
updateList.Clear();
for (int i = 0; i < timerDelegates.Count; i++)
{
updateList.Add(timerDelegates[i]);
}
for (int i = 0; i < updateList.Count; i++)
{
updateList[i]?.Invoke(deltaTime);
}
}
}
}
}
| 25.179487 | 71 | 0.470468 | [
"Unlicense"
] | ouyangwenyuan/OhMyFramework | UnityProject/Assets/Runtime/Framework/Timer/TimerManager.cs | 984 | C# |
using System;
using System.Web.Mvc;
using System.Web.Routing;
using Sitecore.Abstractions;
using Sitecore.Pipelines;
namespace CoreySmith.Feature.Forms.Pipelines.Initialize
{
public class RegisterJssRocksRoutes
{
private readonly BaseSettings _settings;
public RegisterJssRocksRoutes(BaseSettings settings)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
public void Process(PipelineArgs args)
{
if (_settings.GetBoolSetting(Constants.UseWebApiSetting, false)) return;
RegisterRoutes(RouteTable.Routes);
}
private static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"JssRocksForm",
"jssrocksapi/form",
new { controller = "JssRocksForm", action = "Form" });
}
}
}
| 24.575758 | 80 | 0.709001 | [
"MIT"
] | coreyasmith/jss-anti-forgery-tokens | src/Feature/Forms/website/Pipelines/Initialize/RegisterJssRocksRoutes.cs | 813 | C# |
using System.IO;
using System.Text;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Helpers;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Toolchains.CsProj;
using BenchmarkDotNet.Toolchains.DotNetCli;
namespace BenchmarkDotNet.Toolchains.MonoAotLLVM
{
public class MonoAotLLVMGenerator : CsProjGenerator
{
private readonly string CustomRuntimePack;
private readonly string AotCompilerPath;
private readonly MonoAotCompilerMode AotCompilerMode;
public MonoAotLLVMGenerator(string targetFrameworkMoniker, string cliPath, string packagesPath, string customRuntimePack, string aotCompilerPath, MonoAotCompilerMode aotCompilerMode)
: base(targetFrameworkMoniker, cliPath, packagesPath, runtimeFrameworkVersion: null)
{
CustomRuntimePack = customRuntimePack;
AotCompilerPath = aotCompilerPath;
AotCompilerMode = aotCompilerMode;
}
protected override void GenerateProject(BuildPartition buildPartition, ArtifactsPaths artifactsPaths, ILogger logger)
{
BenchmarkCase benchmark = buildPartition.RepresentativeBenchmarkCase;
var projectFile = GetProjectFilePath(benchmark.Descriptor.Type, logger);
string useLLVM = AotCompilerMode == MonoAotCompilerMode.llvm ? "true" : "false";
using (var file = new StreamReader(File.OpenRead(projectFile.FullName)))
{
var (customProperties, sdkName) = GetSettingsThatNeedsToBeCopied(file, projectFile);
string content = new StringBuilder(ResourceHelper.LoadTemplate("MonoAOTLLVMCsProj.txt"))
.Replace("$PLATFORM$", buildPartition.Platform.ToConfig())
.Replace("$CODEFILENAME$", Path.GetFileName(artifactsPaths.ProgramCodePath))
.Replace("$CSPROJPATH$", projectFile.FullName)
.Replace("$TFM$", TargetFrameworkMoniker)
.Replace("$PROGRAMNAME$", artifactsPaths.ProgramName)
.Replace("$COPIEDSETTINGS$", customProperties)
.Replace("$CONFIGURATIONNAME$", buildPartition.BuildConfiguration)
.Replace("$SDKNAME$", sdkName)
.Replace("$RUNTIMEPACK$", CustomRuntimePack ?? "")
.Replace("$COMPILERBINARYPATH$", AotCompilerPath)
.Replace("$RUNTIMEIDENTIFIER$", CustomDotNetCliToolchainBuilder.GetPortableRuntimeIdentifier())
.Replace("$USELLVM$", useLLVM)
.ToString();
File.WriteAllText(artifactsPaths.ProjectFilePath, content);
}
}
protected override string GetExecutablePath(string binariesDirectoryPath, string programName)
=> Portability.RuntimeInformation.IsWindows()
? Path.Combine(binariesDirectoryPath, $"{programName}.exe")
: Path.Combine(binariesDirectoryPath, programName);
protected override string GetBinariesDirectoryPath(string buildArtifactsDirectoryPath, string configuration)
=> Path.Combine(buildArtifactsDirectoryPath, "bin", TargetFrameworkMoniker, CustomDotNetCliToolchainBuilder.GetPortableRuntimeIdentifier(), "publish");
}
}
| 50.861538 | 190 | 0.683908 | [
"MIT"
] | AndyAyersMS/BenchmarkDotNet | src/BenchmarkDotNet/Toolchains/MonoAotLLVM/MonoAotLLVMGenerator.cs | 3,308 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System.Net;
using Microsoft.Azure.Documents;
/// <summary>
/// The cosmos container response
/// </summary>
public class ContainerResponse : Response<ContainerProperties>
{
/// <summary>
/// Create a <see cref="ContainerResponse"/> as a no-op for mock testing
/// </summary>
protected ContainerResponse()
: base()
{
}
/// <summary>
/// A private constructor to ensure the factory is used to create the object.
/// This will prevent memory leaks when handling the HttpResponseMessage
/// </summary>
internal ContainerResponse(
HttpStatusCode httpStatusCode,
Headers headers,
ContainerProperties containerProperties,
Container container)
{
this.StatusCode = httpStatusCode;
this.Headers = headers;
this.Resource = containerProperties;
this.Container = container;
}
/// <summary>
/// The reference to the cosmos container. This allows additional operations on the container
/// or for easy access to other references like Items, StoredProcedures, etc..
/// </summary>
public virtual Container Container { get; private set; }
/// <inheritdoc/>
public override Headers Headers { get; }
/// <inheritdoc/>
public override ContainerProperties Resource { get; }
/// <inheritdoc/>
public override HttpStatusCode StatusCode { get; }
/// <inheritdoc/>
public override double RequestCharge => this.Headers?.RequestCharge ?? 0;
/// <inheritdoc/>
public override string ActivityId => this.Headers?.ActivityId;
/// <inheritdoc/>
public override string ETag => this.Headers?.ETag;
/// <inheritdoc/>
internal override string MaxResourceQuota => this.Headers?.GetHeaderValue<string>(HttpConstants.HttpHeaders.MaxResourceQuota);
/// <inheritdoc/>
internal override string CurrentResourceQuotaUsage => this.Headers?.GetHeaderValue<string>(HttpConstants.HttpHeaders.CurrentResourceQuotaUsage);
/// <summary>
/// Get <see cref="Cosmos.Container"/> implicitly from <see cref="ContainerResponse"/>
/// </summary>
/// <param name="response">ContainerResponse</param>
public static implicit operator Container(ContainerResponse response)
{
return response.Container;
}
}
} | 35.474359 | 152 | 0.5927 | [
"MIT"
] | CasP0/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Resource/Container/ContainerResponse.cs | 2,767 | C# |
// ISayCommand.cs
// Copyright (c) 2014+ by Michael Penner. All rights reserved.
namespace EamonRT.Framework.Commands
{
/// <summary></summary>
public interface ISayCommand : ICommand
{
/// <summary></summary>
string OriginalPhrase { get; set; }
/// <summary></summary>
string PrintedPhrase { get; set; }
/// <summary></summary>
string ProcessedPhrase { get; set; }
}
}
| 19.666667 | 64 | 0.62954 | [
"MIT"
] | TheRealEamonCS/Eamon-CS | System/EamonRT/Framework/Commands/Player/Miscellaneous/ISayCommand.cs | 415 | C# |
using JustFight.Tank;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Systems;
namespace JustFight.Bullet {
class BulletLiftTimeSystem : SystemBase {
BeginInitializationEntityCommandBufferSystem m_entityCommandBufferSystem;
protected override void OnCreate () {
m_entityCommandBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem> ();
}
protected override void OnUpdate () {
var ecb = m_entityCommandBufferSystem.CreateCommandBuffer ().AsParallelWriter ();
var dT = Time.DeltaTime;
Dependency = Entities.ForEach ((Entity entity, int entityInQueryIndex, ref BulletDestroyTime destroyTimeCmpt) => {
destroyTimeCmpt.value -= dT;
if (destroyTimeCmpt.value <= 0)
ecb.DestroyEntity (entityInQueryIndex, entity);
}).ScheduleParallel (Dependency);
m_entityCommandBufferSystem.AddJobHandleForProducer (Dependency);
}
}
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateBefore (typeof (StepPhysicsWorld))]
class BulletDisableCollisionSystem : SystemBase {
struct BulletDisableCollisionJob : IBodyPairsJob {
[ReadOnly]
public ComponentDataFromEntity<BulletTeam> bulletTeamFromEntity;
public void Execute (ref ModifiableBodyPair pair) {
bool isEntityABullet = bulletTeamFromEntity.HasComponent (pair.EntityA);
bool isEntityBBullet = bulletTeamFromEntity.HasComponent (pair.EntityB);
// 自己的子弹之间不会碰撞
if (isEntityABullet && isEntityBBullet) {
if (bulletTeamFromEntity[pair.EntityA].hull == bulletTeamFromEntity[pair.EntityB].hull)
pair.Disable ();
}
// 自己与自己的子弹不会碰撞
else if (isEntityABullet || isEntityBBullet) {
var bulletEntity = isEntityABullet ? pair.EntityA : pair.EntityB;
var theOtherEntity = isEntityABullet ? pair.EntityB : pair.EntityA;
if (bulletTeamFromEntity[pair.EntityA].hull == theOtherEntity)
pair.Disable ();
}
}
}
BuildPhysicsWorld m_buildPhysicsWorld;
StepPhysicsWorld m_stepPhysicsWorld;
protected override void OnCreate () {
m_buildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld> ();
m_stepPhysicsWorld = World.GetOrCreateSystem<StepPhysicsWorld> ();
}
protected override void OnUpdate () {
if (m_stepPhysicsWorld.Simulation.Type == SimulationType.NoPhysics) return;
// TODO: 有GC等官方示例更新
SimulationCallbacks.Callback callback = (ref ISimulation simulation, ref PhysicsWorld world, JobHandle inDeps) => {
inDeps.Complete();
return new BulletDisableCollisionJob { bulletTeamFromEntity = GetComponentDataFromEntity<BulletTeam> () }.Schedule (simulation, ref world, inDeps);
};
m_stepPhysicsWorld.EnqueueCallback (SimulationCallbacks.Phase.PostCreateDispatchPairs, callback);
}
}
[UpdateInGroup (typeof (FixedStepSimulationSystemGroup))]
[UpdateAfter (typeof (ExportPhysicsWorld))]
[UpdateBefore (typeof (EndFramePhysicsSystem))]
class BulletHitSystem : SystemBase {
[BurstCompile]
struct HitJob : ICollisionEventsJob {
[ReadOnly]
public ComponentDataFromEntity<TankHullTeam> hullTeamFromEntity;
[ReadOnly]
public ComponentDataFromEntity<BulletTeam> bulletTeamFromEntity;
public ComponentDataFromEntity<BulletDamage> bulletDamageFromEntity;
public ComponentDataFromEntity<BulletDestroyTime> bulletDestroyTimeFromEntity;
public ComponentDataFromEntity<HealthPoint> healthFromEntity;
void DisableBullet (Entity bulletEntity) {
bulletDamageFromEntity[bulletEntity] = new BulletDamage { value = 0 };
var destroyTimeCmpt = bulletDestroyTimeFromEntity[bulletEntity];
destroyTimeCmpt.value = math.min (destroyTimeCmpt.value, 0.3f);
bulletDestroyTimeFromEntity[bulletEntity] = destroyTimeCmpt;
}
public void Execute (CollisionEvent collisionEvent) {
// TODO: shit
var entityA = collisionEvent.EntityA;
var entityB = collisionEvent.EntityB;
bool isEntityABullet = bulletDamageFromEntity.HasComponent (entityA);
bool isEntityBBullet = bulletDamageFromEntity.HasComponent (entityB);
var bulletEntity = isEntityABullet ? entityA : entityB;
var hullEntity = isEntityABullet ? entityB : entityA;
var bulletBodyId = isEntityABullet ? collisionEvent.BodyIndexA : collisionEvent.BodyIndexB;
if (healthFromEntity.HasComponent (hullEntity) && bulletTeamFromEntity[bulletEntity].id != hullTeamFromEntity[hullEntity].id) {
var dmgCmpt = bulletDamageFromEntity[bulletEntity];
var healthCmpt = healthFromEntity[hullEntity];
healthCmpt.value -= dmgCmpt.value;
healthFromEntity[hullEntity] = healthCmpt;
}
if (isEntityABullet) DisableBullet (entityA);
if (isEntityBBullet) DisableBullet (entityB);
}
}
BuildPhysicsWorld buildPhysicsWorldSystem;
StepPhysicsWorld stepPhysicsWorldSystem;
EndFramePhysicsSystem endFramePhysicsSystem;
protected override void OnCreate () {
buildPhysicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld> ();
stepPhysicsWorldSystem = World.GetOrCreateSystem<StepPhysicsWorld> ();
endFramePhysicsSystem = World.GetOrCreateSystem<EndFramePhysicsSystem> ();
}
protected override void OnUpdate () {
Dependency = new HitJob {
hullTeamFromEntity = GetComponentDataFromEntity<TankHullTeam> (true),
bulletTeamFromEntity = GetComponentDataFromEntity<BulletTeam> (true),
bulletDamageFromEntity = GetComponentDataFromEntity<BulletDamage> (),
bulletDestroyTimeFromEntity = GetComponentDataFromEntity<BulletDestroyTime> (),
healthFromEntity = GetComponentDataFromEntity<HealthPoint> ()
}.Schedule (stepPhysicsWorldSystem.Simulation, ref buildPhysicsWorldSystem.PhysicsWorld, Dependency);
endFramePhysicsSystem.AddInputDependency (Dependency);
}
}
} | 52.837209 | 163 | 0.657277 | [
"MIT"
] | HeBomou/Just-Fight | Assets/Scripts/Bullet/BulletSystems.cs | 6,878 | C# |
using DCL.Helpers;
using System;
using UnityEngine;
public class PrivateChatHUDView : ChatHUDView
{
string ENTRY_PATH_SENT = "ChatEntrySent";
string ENTRY_PATH_RECEIVED = "ChatEntryReceived";
string ENTRY_PATH_SEPARATOR = "ChatEntrySeparator";
public override void AddEntry(ChatEntry.Model chatEntryModel, bool setScrollPositionToBottom = false)
{
AddSeparatorEntryIfNeeded(chatEntryModel);
var chatEntryGO = Instantiate(Resources.Load(chatEntryModel.subType == ChatEntry.Model.SubType.PRIVATE_TO ? ENTRY_PATH_SENT : ENTRY_PATH_RECEIVED) as GameObject, chatEntriesContainer);
ChatEntry chatEntry = chatEntryGO.GetComponent<ChatEntry>();
chatEntry.SetFadeout(false);
chatEntry.Populate(chatEntryModel);
chatEntry.OnTriggerHover += OnMessageTriggerHover;
chatEntry.OnCancelHover += OnMessageCancelHover;
entries.Add(chatEntry);
Utils.ForceUpdateLayout(transform as RectTransform, delayed: false);
if (setScrollPositionToBottom)
scrollRect.verticalNormalizedPosition = 0;
}
protected override void OnMessageTriggerHover(ChatEntry chatEntry)
{
(messageHoverPanel.transform as RectTransform).pivot = new Vector2(chatEntry.model.subType == ChatEntry.Model.SubType.PRIVATE_TO ? 1 : 0, 0.5f);
base.OnMessageTriggerHover(chatEntry);
}
private void AddSeparatorEntryIfNeeded(ChatEntry.Model chatEntryModel)
{
DateTime entryDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
entryDateTime = GetDateTimeFromUnixTimestampMilliseconds(chatEntryModel.timestamp);
if (!dateSeparators.Exists(separator =>
separator.model.date.Year == entryDateTime.Year &&
separator.model.date.Month == entryDateTime.Month &&
separator.model.date.Day == entryDateTime.Day))
{
var chatEntrySeparatorGO = Instantiate(Resources.Load(ENTRY_PATH_SEPARATOR) as GameObject, chatEntriesContainer);
DateSeparatorEntry dateSeparatorEntry = chatEntrySeparatorGO.GetComponent<DateSeparatorEntry>();
dateSeparatorEntry.Populate(new DateSeparatorEntry.Model
{
date = entryDateTime
});
dateSeparators.Add(dateSeparatorEntry);
}
}
private DateTime GetDateTimeFromUnixTimestampMilliseconds(ulong milliseconds)
{
System.DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return result.AddMilliseconds(milliseconds);
}
} | 40.68254 | 192 | 0.711666 | [
"Apache-2.0"
] | 0xBlockchainx0/unity-renderer | unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/PrivateChatWindow/PrivateChatHUDView.cs | 2,563 | C# |
using Accounting.dbSource;
using AccountingNote.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormAccounting0728
{
public partial class UserList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!AuthManager.Islogined())
{
return;
}
var cUser = AuthManager.GetCurrentUser();
this.GridView1.DataSource = AccountingManager.GetAccountingList(cUser.ID);
this.GridView1.DataBind();
}
}
} | 25.115385 | 86 | 0.641654 | [
"MIT"
] | A6228774/AccountingNote0729 | AccountingNote0729/WebFormAccounting0728/UserList.aspx.cs | 655 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public enum FrequencyType
{
High,
Middle,
Low
}
public enum SourceType
{
Mono,
Stereo
}
[System.Serializable]
public class AudioInfo
{
public FrequencyType Type;
public Transform Target;
public GameObject AudioObject;
public AudioClip Mono;
public AudioClip Stereo;
[HideInInspector]
public AudioSource Source;
}
public class AudioController : SingletonMonoBehavior<AudioController>
{
[SerializeField]
private List<AudioInfo> _audioClips = new List<AudioInfo>();
public List<AudioInfo> AudioClips { get { return _audioClips; } }
private AudioFadeEffect _effect;
override protected void Awake()
{
base.Awake();
foreach (var audio in _audioClips)
{
SpawnAudioObject(audio);
}
_effect = GetComponent<AudioFadeEffect>();
}
/// <summary>
/// Targetの位置にAudioObjectを生成
/// </summary>
/// <param name="audio"></param>
private void SpawnAudioObject(AudioInfo audio)
{
var gameObject = Instantiate(audio.AudioObject, audio.Target);
var audioSource = gameObject.GetComponent<AudioSource>();
audioSource.clip = audio.Stereo;
audio.Source = audioSource;
}
/// <summary>
/// 指定された音源を再生
/// </summary>
/// <param name="type"></param>
private void Play(FrequencyType type)
{
var audioClip = _audioClips.Where(a => a.Type == type);
foreach (var audio in audioClip)
{
audio.Source.Play();
}
}
/// <summary>
/// 指定された音源を停止
/// </summary>
/// <param name="type"></param>
public void Stop(FrequencyType type)
{
var audioClip = _audioClips.Where(a => a.Type == type);
foreach (var audio in audioClip)
{
audio.Source.Stop();
}
}
/// <summary>
/// 指定された音源の音量を変更
/// </summary>
/// <param name="type"></param>
/// <param name="volume"></param>
public void ChangeVolume(FrequencyType type, float volume)
{
var audioClip = _audioClips.Where(a => a.Type == type);
foreach (var audio in audioClip)
{
audio.Source.volume = volume;
}
}
/// <summary>
/// 登録されている全ての音源を再生
/// </summary>
public void PlayAll()
{
foreach (var audio in _audioClips)
{
audio.Source.Play();
}
_effect.FadeStart(FadeType.FadeIn);
}
/// <summary>
/// 登録されている全ての音源を停止
/// </summary>
public void StopAll()
{
_effect.FadeStart(FadeType.FadeOut);
StartCoroutine(StopAllCoroutine());
}
private IEnumerator StopAllCoroutine()
{
yield return new WaitForSeconds(_effect.FadeOutTime);
foreach (var audio in _audioClips)
{
audio.Source.Stop();
}
}
/// <summary>
/// 音源をStereo or Monoに切り替える
/// </summary>
/// <param name="fType"></param>
/// <param name="sType"></param>
public void ChangeSourceType(FrequencyType fType, SourceType sType)
{
var audioClip = _audioClips.Where(a => a.Type == fType);
foreach (var audio in audioClip)
{
switch (sType)
{
case SourceType.Mono:
audio.Source.clip = audio.Mono;
break;
case SourceType.Stereo:
audio.Source.clip = audio.Stereo;
break;
default:
break;
}
audio.Source.Play();
}
}
public void EnableImage(FrequencyType type)
{
var audioClip = _audioClips.Where(a => a.Type == type);
foreach (var audio in audioClip)
{
audio.Source.GetComponent<IAudioObject>().Image.color = new Color(1, 1, 1, 1);
}
}
public void DisableImage(FrequencyType type)
{
var audioClip = _audioClips.Where(a => a.Type == type);
foreach (var audio in audioClip)
{
audio.Source.GetComponent<IAudioObject>().Image.color = new Color(0, 0, 0, 0);
}
}
}
| 24.181818 | 90 | 0.56532 | [
"MIT"
] | GoSato/UmweltExhibition | Umwelt_Edited/Assets/_GO/Scripts/AudioController.cs | 4,416 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Net.Security;
using System.Threading.Tasks;
using System.Net.Quic.Implementations;
using Xunit;
using System.Threading;
using System.Text;
namespace System.Net.Quic.Tests
{
public abstract class QuicTestBase<T>
where T : IQuicImplProviderFactory, new()
{
private static readonly IQuicImplProviderFactory s_factory = new T();
public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider();
public static bool IsSupported => ImplementationProvider.IsSupported;
public static SslApplicationProtocol ApplicationProtocol { get; } = new SslApplicationProtocol("quictest");
public SslServerAuthenticationOptions GetSslServerAuthenticationOptions()
{
return new SslServerAuthenticationOptions()
{
ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol },
ServerCertificate = System.Net.Test.Common.Configuration.Certificates.GetServerCertificate()
};
}
public SslClientAuthenticationOptions GetSslClientAuthenticationOptions()
{
return new SslClientAuthenticationOptions()
{
ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol },
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => { return true; }
};
}
internal QuicConnection CreateQuicConnection(IPEndPoint endpoint)
{
return new QuicConnection(ImplementationProvider, endpoint, GetSslClientAuthenticationOptions());
}
internal QuicListener CreateQuicListener()
{
return CreateQuicListener(new IPEndPoint(IPAddress.Loopback, 0));
}
internal QuicListener CreateQuicListener(IPEndPoint endpoint)
{
return new QuicListener(ImplementationProvider, endpoint, GetSslServerAuthenticationOptions());
}
internal async Task RunClientServer(Func<QuicConnection, Task> clientFunction, Func<QuicConnection, Task> serverFunction, int iterations = 1, int millisecondsTimeout = 10_000)
{
using QuicListener listener = CreateQuicListener();
var serverFinished = new ManualResetEventSlim();
var clientFinished = new ManualResetEventSlim();
for (int i = 0; i < iterations; ++i)
{
serverFinished.Reset();
clientFinished.Reset();
await new[]
{
Task.Run(async () =>
{
using QuicConnection serverConnection = await listener.AcceptConnectionAsync();
await serverFunction(serverConnection);
serverFinished.Set();
clientFinished.Wait();
await serverConnection.CloseAsync(0);
}),
Task.Run(async () =>
{
using QuicConnection clientConnection = CreateQuicConnection(listener.ListenEndPoint);
await clientConnection.ConnectAsync();
await clientFunction(clientConnection);
clientFinished.Set();
serverFinished.Wait();
await clientConnection.CloseAsync(0);
})
}.WhenAllOrAnyFailed(millisecondsTimeout);
}
}
internal static async Task<int> ReadAll(QuicStream stream, byte[] buffer)
{
Memory<byte> memory = buffer;
int bytesRead = 0;
while (true)
{
int res = await stream.ReadAsync(memory);
if (res == 0)
{
break;
}
bytesRead += res;
memory = memory[res..];
}
return bytesRead;
}
internal static void AssertArrayEqual(byte[] expected, byte[] actual)
{
for (int i = 0; i < expected.Length; ++i)
{
if (expected[i] == actual[i])
{
continue;
}
var message = $"Wrong data starting from idx={i}\n" +
$"Expected: {ToStringAroundIndex(expected, i)}\n" +
$"Actual: {ToStringAroundIndex(actual, i)}";
Assert.True(expected[i] == actual[i], message);
}
}
private static string ToStringAroundIndex(byte[] arr, int idx, int dl = 3, int dr = 7)
{
var sb = new StringBuilder(idx - (dl+1) >= 0 ? "[..., " : "[");
for (int i = idx - dl; i <= idx + dr; ++i)
{
if (i >= 0 && i < arr.Length)
{
sb.Append($"{arr[i]}, ");
}
}
sb.Append(idx + (dr+1) < arr.Length ? "...]" : "]");
return sb.ToString();
}
}
public interface IQuicImplProviderFactory
{
QuicImplementationProvider GetProvider();
}
public sealed class MsQuicProviderFactory : IQuicImplProviderFactory
{
public QuicImplementationProvider GetProvider() => QuicImplementationProviders.MsQuic;
}
public sealed class MockProviderFactory : IQuicImplProviderFactory
{
public QuicImplementationProvider GetProvider() => QuicImplementationProviders.Mock;
}
}
| 36.0375 | 183 | 0.565383 | [
"MIT"
] | BreyerW/runtime | src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs | 5,768 | C# |
using System;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayUserCharityRecordexistQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayUserCharityRecordexistQueryModel : AlipayObject
{
/// <summary>
/// 公益的业务类型(缺省是所有类型)
/// </summary>
[JsonProperty("biz_type")]
[XmlElement("biz_type")]
public long BizType { get; set; }
/// <summary>
/// 捐赠记录的结束时间(默认是查询当前自然年一年的记录)
/// </summary>
[JsonProperty("end_time")]
[XmlElement("end_time")]
public string EndTime { get; set; }
/// <summary>
/// 商户和支付宝交互时,用于代表支付宝分配给商户ID
/// </summary>
[JsonProperty("partner_id")]
[XmlElement("partner_id")]
public string PartnerId { get; set; }
/// <summary>
/// 捐赠记录的开始时间(默认是查询当前自然年一年的记录)
/// </summary>
[JsonProperty("start_time")]
[XmlElement("start_time")]
public string StartTime { get; set; }
/// <summary>
/// 蚂蚁统一会员ID
/// </summary>
[JsonProperty("user_id")]
[XmlElement("user_id")]
public string UserId { get; set; }
}
}
| 26.326531 | 70 | 0.563566 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayUserCharityRecordexistQueryModel.cs | 1,478 | C# |
/*++
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
Abstract:
Represents the node in the tree of type searches.
For example if
%a
%ab
%aa
%abc
you'd get a tree like
a
/ \
a b
\
c
--*/
using System.Collections.Generic;
namespace clogutils
{
public class CLogTypeSearchNode
{
public Dictionary<char, CLogTypeSearchNode> Nodes = new Dictionary<char, CLogTypeSearchNode>();
public CLogEncodingCLogTypeSearch UserNode { get; set; }
private static void Flatten(CLogTypeSearchNode node, List<CLogEncodingCLogTypeSearch> ret)
{
if (null != node.UserNode)
ret.Add(node.UserNode);
foreach (var n in node.Nodes)
{
Flatten(n.Value, ret);
}
}
public IEnumerable<CLogEncodingCLogTypeSearch> Flatten()
{
List<CLogEncodingCLogTypeSearch> ret = new List<CLogEncodingCLogTypeSearch>();
Flatten(this, ret);
return ret;
}
}
}
| 20.678571 | 103 | 0.549223 | [
"MIT"
] | microsoft/CLOG | src/clogutils/CLogTypeSearchNode.cs | 1,158 | C# |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// RadioGroup
/// </summary>
[DataContract]
public partial class RadioGroup : IEquatable<RadioGroup>, IValidatableObject
{
public RadioGroup()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="RadioGroup" /> class.
/// </summary>
/// <param name="ConditionalParentLabel">For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility..</param>
/// <param name="ConditionalParentLabelMetadata">ConditionalParentLabelMetadata.</param>
/// <param name="ConditionalParentValue">For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. .</param>
/// <param name="ConditionalParentValueMetadata">ConditionalParentValueMetadata.</param>
/// <param name="DocumentId">Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute..</param>
/// <param name="DocumentIdMetadata">DocumentIdMetadata.</param>
/// <param name="GroupName">The name of the group..</param>
/// <param name="GroupNameMetadata">GroupNameMetadata.</param>
/// <param name="OriginalValue">The initial value of the tab when it was sent to the recipient. .</param>
/// <param name="OriginalValueMetadata">OriginalValueMetadata.</param>
/// <param name="Radios">Specifies the locations and status for radio buttons that are grouped together..</param>
/// <param name="RecipientId">Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document..</param>
/// <param name="RecipientIdGuid">RecipientIdGuid.</param>
/// <param name="RecipientIdGuidMetadata">RecipientIdGuidMetadata.</param>
/// <param name="RecipientIdMetadata">RecipientIdMetadata.</param>
/// <param name="RequireAll">When set to **true** and shared is true, information must be entered in this field to complete the envelope. .</param>
/// <param name="RequireAllMetadata">RequireAllMetadata.</param>
/// <param name="RequireInitialOnSharedChange">Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field..</param>
/// <param name="RequireInitialOnSharedChangeMetadata">RequireInitialOnSharedChangeMetadata.</param>
/// <param name="Shared">When set to **true**, this custom tab is shared..</param>
/// <param name="SharedMetadata">SharedMetadata.</param>
/// <param name="ShareToRecipients">ShareToRecipients.</param>
/// <param name="ShareToRecipientsMetadata">ShareToRecipientsMetadata.</param>
/// <param name="TabType">TabType.</param>
/// <param name="TabTypeMetadata">TabTypeMetadata.</param>
/// <param name="TemplateLocked">When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. .</param>
/// <param name="TemplateLockedMetadata">TemplateLockedMetadata.</param>
/// <param name="TemplateRequired">When set to **true**, the sender may not remove the recipient. Used only when working with template recipients..</param>
/// <param name="TemplateRequiredMetadata">TemplateRequiredMetadata.</param>
/// <param name="Tooltip">Tooltip.</param>
/// <param name="TooltipMetadata">TooltipMetadata.</param>
/// <param name="Value">Specifies the value of the tab. .</param>
/// <param name="ValueMetadata">ValueMetadata.</param>
public RadioGroup(string ConditionalParentLabel = default(string), PropertyMetadata ConditionalParentLabelMetadata = default(PropertyMetadata), string ConditionalParentValue = default(string), PropertyMetadata ConditionalParentValueMetadata = default(PropertyMetadata), string DocumentId = default(string), PropertyMetadata DocumentIdMetadata = default(PropertyMetadata), string GroupName = default(string), PropertyMetadata GroupNameMetadata = default(PropertyMetadata), string OriginalValue = default(string), PropertyMetadata OriginalValueMetadata = default(PropertyMetadata), List<Radio> Radios = default(List<Radio>), string RecipientId = default(string), string RecipientIdGuid = default(string), PropertyMetadata RecipientIdGuidMetadata = default(PropertyMetadata), PropertyMetadata RecipientIdMetadata = default(PropertyMetadata), string RequireAll = default(string), PropertyMetadata RequireAllMetadata = default(PropertyMetadata), string RequireInitialOnSharedChange = default(string), PropertyMetadata RequireInitialOnSharedChangeMetadata = default(PropertyMetadata), string Shared = default(string), PropertyMetadata SharedMetadata = default(PropertyMetadata), string ShareToRecipients = default(string), PropertyMetadata ShareToRecipientsMetadata = default(PropertyMetadata), string TabType = default(string), PropertyMetadata TabTypeMetadata = default(PropertyMetadata), string TemplateLocked = default(string), PropertyMetadata TemplateLockedMetadata = default(PropertyMetadata), string TemplateRequired = default(string), PropertyMetadata TemplateRequiredMetadata = default(PropertyMetadata), string Tooltip = default(string), PropertyMetadata TooltipMetadata = default(PropertyMetadata), string Value = default(string), PropertyMetadata ValueMetadata = default(PropertyMetadata))
{
this.ConditionalParentLabel = ConditionalParentLabel;
this.ConditionalParentLabelMetadata = ConditionalParentLabelMetadata;
this.ConditionalParentValue = ConditionalParentValue;
this.ConditionalParentValueMetadata = ConditionalParentValueMetadata;
this.DocumentId = DocumentId;
this.DocumentIdMetadata = DocumentIdMetadata;
this.GroupName = GroupName;
this.GroupNameMetadata = GroupNameMetadata;
this.OriginalValue = OriginalValue;
this.OriginalValueMetadata = OriginalValueMetadata;
this.Radios = Radios;
this.RecipientId = RecipientId;
this.RecipientIdGuid = RecipientIdGuid;
this.RecipientIdGuidMetadata = RecipientIdGuidMetadata;
this.RecipientIdMetadata = RecipientIdMetadata;
this.RequireAll = RequireAll;
this.RequireAllMetadata = RequireAllMetadata;
this.RequireInitialOnSharedChange = RequireInitialOnSharedChange;
this.RequireInitialOnSharedChangeMetadata = RequireInitialOnSharedChangeMetadata;
this.Shared = Shared;
this.SharedMetadata = SharedMetadata;
this.ShareToRecipients = ShareToRecipients;
this.ShareToRecipientsMetadata = ShareToRecipientsMetadata;
this.TabType = TabType;
this.TabTypeMetadata = TabTypeMetadata;
this.TemplateLocked = TemplateLocked;
this.TemplateLockedMetadata = TemplateLockedMetadata;
this.TemplateRequired = TemplateRequired;
this.TemplateRequiredMetadata = TemplateRequiredMetadata;
this.Tooltip = Tooltip;
this.TooltipMetadata = TooltipMetadata;
this.Value = Value;
this.ValueMetadata = ValueMetadata;
}
/// <summary>
/// For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.
/// </summary>
/// <value>For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.</value>
[DataMember(Name="conditionalParentLabel", EmitDefaultValue=false)]
public string ConditionalParentLabel { get; set; }
/// <summary>
/// Gets or Sets ConditionalParentLabelMetadata
/// </summary>
[DataMember(Name="conditionalParentLabelMetadata", EmitDefaultValue=false)]
public PropertyMetadata ConditionalParentLabelMetadata { get; set; }
/// <summary>
/// For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.
/// </summary>
/// <value>For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. </value>
[DataMember(Name="conditionalParentValue", EmitDefaultValue=false)]
public string ConditionalParentValue { get; set; }
/// <summary>
/// Gets or Sets ConditionalParentValueMetadata
/// </summary>
[DataMember(Name="conditionalParentValueMetadata", EmitDefaultValue=false)]
public PropertyMetadata ConditionalParentValueMetadata { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
/// Gets or Sets DocumentIdMetadata
/// </summary>
[DataMember(Name="documentIdMetadata", EmitDefaultValue=false)]
public PropertyMetadata DocumentIdMetadata { get; set; }
/// <summary>
/// The name of the group.
/// </summary>
/// <value>The name of the group.</value>
[DataMember(Name="groupName", EmitDefaultValue=false)]
public string GroupName { get; set; }
/// <summary>
/// Gets or Sets GroupNameMetadata
/// </summary>
[DataMember(Name="groupNameMetadata", EmitDefaultValue=false)]
public PropertyMetadata GroupNameMetadata { get; set; }
/// <summary>
/// The initial value of the tab when it was sent to the recipient.
/// </summary>
/// <value>The initial value of the tab when it was sent to the recipient. </value>
[DataMember(Name="originalValue", EmitDefaultValue=false)]
public string OriginalValue { get; set; }
/// <summary>
/// Gets or Sets OriginalValueMetadata
/// </summary>
[DataMember(Name="originalValueMetadata", EmitDefaultValue=false)]
public PropertyMetadata OriginalValueMetadata { get; set; }
/// <summary>
/// Specifies the locations and status for radio buttons that are grouped together.
/// </summary>
/// <value>Specifies the locations and status for radio buttons that are grouped together.</value>
[DataMember(Name="radios", EmitDefaultValue=false)]
public List<Radio> Radios { get; set; }
/// <summary>
/// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.
/// </summary>
/// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value>
[DataMember(Name="recipientId", EmitDefaultValue=false)]
public string RecipientId { get; set; }
/// <summary>
/// Gets or Sets RecipientIdGuid
/// </summary>
[DataMember(Name="recipientIdGuid", EmitDefaultValue=false)]
public string RecipientIdGuid { get; set; }
/// <summary>
/// Gets or Sets RecipientIdGuidMetadata
/// </summary>
[DataMember(Name="recipientIdGuidMetadata", EmitDefaultValue=false)]
public PropertyMetadata RecipientIdGuidMetadata { get; set; }
/// <summary>
/// Gets or Sets RecipientIdMetadata
/// </summary>
[DataMember(Name="recipientIdMetadata", EmitDefaultValue=false)]
public PropertyMetadata RecipientIdMetadata { get; set; }
/// <summary>
/// When set to **true** and shared is true, information must be entered in this field to complete the envelope.
/// </summary>
/// <value>When set to **true** and shared is true, information must be entered in this field to complete the envelope. </value>
[DataMember(Name="requireAll", EmitDefaultValue=false)]
public string RequireAll { get; set; }
/// <summary>
/// Gets or Sets RequireAllMetadata
/// </summary>
[DataMember(Name="requireAllMetadata", EmitDefaultValue=false)]
public PropertyMetadata RequireAllMetadata { get; set; }
/// <summary>
/// Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.
/// </summary>
/// <value>Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.</value>
[DataMember(Name="requireInitialOnSharedChange", EmitDefaultValue=false)]
public string RequireInitialOnSharedChange { get; set; }
/// <summary>
/// Gets or Sets RequireInitialOnSharedChangeMetadata
/// </summary>
[DataMember(Name="requireInitialOnSharedChangeMetadata", EmitDefaultValue=false)]
public PropertyMetadata RequireInitialOnSharedChangeMetadata { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
/// Gets or Sets SharedMetadata
/// </summary>
[DataMember(Name="sharedMetadata", EmitDefaultValue=false)]
public PropertyMetadata SharedMetadata { get; set; }
/// <summary>
/// Gets or Sets ShareToRecipients
/// </summary>
[DataMember(Name="shareToRecipients", EmitDefaultValue=false)]
public string ShareToRecipients { get; set; }
/// <summary>
/// Gets or Sets ShareToRecipientsMetadata
/// </summary>
[DataMember(Name="shareToRecipientsMetadata", EmitDefaultValue=false)]
public PropertyMetadata ShareToRecipientsMetadata { get; set; }
/// <summary>
/// Gets or Sets TabType
/// </summary>
[DataMember(Name="tabType", EmitDefaultValue=false)]
public string TabType { get; set; }
/// <summary>
/// Gets or Sets TabTypeMetadata
/// </summary>
[DataMember(Name="tabTypeMetadata", EmitDefaultValue=false)]
public PropertyMetadata TabTypeMetadata { get; set; }
/// <summary>
/// When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. </value>
[DataMember(Name="templateLocked", EmitDefaultValue=false)]
public string TemplateLocked { get; set; }
/// <summary>
/// Gets or Sets TemplateLockedMetadata
/// </summary>
[DataMember(Name="templateLockedMetadata", EmitDefaultValue=false)]
public PropertyMetadata TemplateLockedMetadata { get; set; }
/// <summary>
/// When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateRequired", EmitDefaultValue=false)]
public string TemplateRequired { get; set; }
/// <summary>
/// Gets or Sets TemplateRequiredMetadata
/// </summary>
[DataMember(Name="templateRequiredMetadata", EmitDefaultValue=false)]
public PropertyMetadata TemplateRequiredMetadata { get; set; }
/// <summary>
/// Gets or Sets Tooltip
/// </summary>
[DataMember(Name="tooltip", EmitDefaultValue=false)]
public string Tooltip { get; set; }
/// <summary>
/// Gets or Sets TooltipMetadata
/// </summary>
[DataMember(Name="tooltipMetadata", EmitDefaultValue=false)]
public PropertyMetadata TooltipMetadata { get; set; }
/// <summary>
/// Specifies the value of the tab.
/// </summary>
/// <value>Specifies the value of the tab. </value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// Gets or Sets ValueMetadata
/// </summary>
[DataMember(Name="valueMetadata", EmitDefaultValue=false)]
public PropertyMetadata ValueMetadata { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RadioGroup {\n");
sb.Append(" ConditionalParentLabel: ").Append(ConditionalParentLabel).Append("\n");
sb.Append(" ConditionalParentLabelMetadata: ").Append(ConditionalParentLabelMetadata).Append("\n");
sb.Append(" ConditionalParentValue: ").Append(ConditionalParentValue).Append("\n");
sb.Append(" ConditionalParentValueMetadata: ").Append(ConditionalParentValueMetadata).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" DocumentIdMetadata: ").Append(DocumentIdMetadata).Append("\n");
sb.Append(" GroupName: ").Append(GroupName).Append("\n");
sb.Append(" GroupNameMetadata: ").Append(GroupNameMetadata).Append("\n");
sb.Append(" OriginalValue: ").Append(OriginalValue).Append("\n");
sb.Append(" OriginalValueMetadata: ").Append(OriginalValueMetadata).Append("\n");
sb.Append(" Radios: ").Append(Radios).Append("\n");
sb.Append(" RecipientId: ").Append(RecipientId).Append("\n");
sb.Append(" RecipientIdGuid: ").Append(RecipientIdGuid).Append("\n");
sb.Append(" RecipientIdGuidMetadata: ").Append(RecipientIdGuidMetadata).Append("\n");
sb.Append(" RecipientIdMetadata: ").Append(RecipientIdMetadata).Append("\n");
sb.Append(" RequireAll: ").Append(RequireAll).Append("\n");
sb.Append(" RequireAllMetadata: ").Append(RequireAllMetadata).Append("\n");
sb.Append(" RequireInitialOnSharedChange: ").Append(RequireInitialOnSharedChange).Append("\n");
sb.Append(" RequireInitialOnSharedChangeMetadata: ").Append(RequireInitialOnSharedChangeMetadata).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" SharedMetadata: ").Append(SharedMetadata).Append("\n");
sb.Append(" ShareToRecipients: ").Append(ShareToRecipients).Append("\n");
sb.Append(" ShareToRecipientsMetadata: ").Append(ShareToRecipientsMetadata).Append("\n");
sb.Append(" TabType: ").Append(TabType).Append("\n");
sb.Append(" TabTypeMetadata: ").Append(TabTypeMetadata).Append("\n");
sb.Append(" TemplateLocked: ").Append(TemplateLocked).Append("\n");
sb.Append(" TemplateLockedMetadata: ").Append(TemplateLockedMetadata).Append("\n");
sb.Append(" TemplateRequired: ").Append(TemplateRequired).Append("\n");
sb.Append(" TemplateRequiredMetadata: ").Append(TemplateRequiredMetadata).Append("\n");
sb.Append(" Tooltip: ").Append(Tooltip).Append("\n");
sb.Append(" TooltipMetadata: ").Append(TooltipMetadata).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" ValueMetadata: ").Append(ValueMetadata).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RadioGroup);
}
/// <summary>
/// Returns true if RadioGroup instances are equal
/// </summary>
/// <param name="other">Instance of RadioGroup to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RadioGroup other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ConditionalParentLabel == other.ConditionalParentLabel ||
this.ConditionalParentLabel != null &&
this.ConditionalParentLabel.Equals(other.ConditionalParentLabel)
) &&
(
this.ConditionalParentLabelMetadata == other.ConditionalParentLabelMetadata ||
this.ConditionalParentLabelMetadata != null &&
this.ConditionalParentLabelMetadata.Equals(other.ConditionalParentLabelMetadata)
) &&
(
this.ConditionalParentValue == other.ConditionalParentValue ||
this.ConditionalParentValue != null &&
this.ConditionalParentValue.Equals(other.ConditionalParentValue)
) &&
(
this.ConditionalParentValueMetadata == other.ConditionalParentValueMetadata ||
this.ConditionalParentValueMetadata != null &&
this.ConditionalParentValueMetadata.Equals(other.ConditionalParentValueMetadata)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.DocumentIdMetadata == other.DocumentIdMetadata ||
this.DocumentIdMetadata != null &&
this.DocumentIdMetadata.Equals(other.DocumentIdMetadata)
) &&
(
this.GroupName == other.GroupName ||
this.GroupName != null &&
this.GroupName.Equals(other.GroupName)
) &&
(
this.GroupNameMetadata == other.GroupNameMetadata ||
this.GroupNameMetadata != null &&
this.GroupNameMetadata.Equals(other.GroupNameMetadata)
) &&
(
this.OriginalValue == other.OriginalValue ||
this.OriginalValue != null &&
this.OriginalValue.Equals(other.OriginalValue)
) &&
(
this.OriginalValueMetadata == other.OriginalValueMetadata ||
this.OriginalValueMetadata != null &&
this.OriginalValueMetadata.Equals(other.OriginalValueMetadata)
) &&
(
this.Radios == other.Radios ||
this.Radios != null &&
this.Radios.SequenceEqual(other.Radios)
) &&
(
this.RecipientId == other.RecipientId ||
this.RecipientId != null &&
this.RecipientId.Equals(other.RecipientId)
) &&
(
this.RecipientIdGuid == other.RecipientIdGuid ||
this.RecipientIdGuid != null &&
this.RecipientIdGuid.Equals(other.RecipientIdGuid)
) &&
(
this.RecipientIdGuidMetadata == other.RecipientIdGuidMetadata ||
this.RecipientIdGuidMetadata != null &&
this.RecipientIdGuidMetadata.Equals(other.RecipientIdGuidMetadata)
) &&
(
this.RecipientIdMetadata == other.RecipientIdMetadata ||
this.RecipientIdMetadata != null &&
this.RecipientIdMetadata.Equals(other.RecipientIdMetadata)
) &&
(
this.RequireAll == other.RequireAll ||
this.RequireAll != null &&
this.RequireAll.Equals(other.RequireAll)
) &&
(
this.RequireAllMetadata == other.RequireAllMetadata ||
this.RequireAllMetadata != null &&
this.RequireAllMetadata.Equals(other.RequireAllMetadata)
) &&
(
this.RequireInitialOnSharedChange == other.RequireInitialOnSharedChange ||
this.RequireInitialOnSharedChange != null &&
this.RequireInitialOnSharedChange.Equals(other.RequireInitialOnSharedChange)
) &&
(
this.RequireInitialOnSharedChangeMetadata == other.RequireInitialOnSharedChangeMetadata ||
this.RequireInitialOnSharedChangeMetadata != null &&
this.RequireInitialOnSharedChangeMetadata.Equals(other.RequireInitialOnSharedChangeMetadata)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.SharedMetadata == other.SharedMetadata ||
this.SharedMetadata != null &&
this.SharedMetadata.Equals(other.SharedMetadata)
) &&
(
this.ShareToRecipients == other.ShareToRecipients ||
this.ShareToRecipients != null &&
this.ShareToRecipients.Equals(other.ShareToRecipients)
) &&
(
this.ShareToRecipientsMetadata == other.ShareToRecipientsMetadata ||
this.ShareToRecipientsMetadata != null &&
this.ShareToRecipientsMetadata.Equals(other.ShareToRecipientsMetadata)
) &&
(
this.TabType == other.TabType ||
this.TabType != null &&
this.TabType.Equals(other.TabType)
) &&
(
this.TabTypeMetadata == other.TabTypeMetadata ||
this.TabTypeMetadata != null &&
this.TabTypeMetadata.Equals(other.TabTypeMetadata)
) &&
(
this.TemplateLocked == other.TemplateLocked ||
this.TemplateLocked != null &&
this.TemplateLocked.Equals(other.TemplateLocked)
) &&
(
this.TemplateLockedMetadata == other.TemplateLockedMetadata ||
this.TemplateLockedMetadata != null &&
this.TemplateLockedMetadata.Equals(other.TemplateLockedMetadata)
) &&
(
this.TemplateRequired == other.TemplateRequired ||
this.TemplateRequired != null &&
this.TemplateRequired.Equals(other.TemplateRequired)
) &&
(
this.TemplateRequiredMetadata == other.TemplateRequiredMetadata ||
this.TemplateRequiredMetadata != null &&
this.TemplateRequiredMetadata.Equals(other.TemplateRequiredMetadata)
) &&
(
this.Tooltip == other.Tooltip ||
this.Tooltip != null &&
this.Tooltip.Equals(other.Tooltip)
) &&
(
this.TooltipMetadata == other.TooltipMetadata ||
this.TooltipMetadata != null &&
this.TooltipMetadata.Equals(other.TooltipMetadata)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.ValueMetadata == other.ValueMetadata ||
this.ValueMetadata != null &&
this.ValueMetadata.Equals(other.ValueMetadata)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ConditionalParentLabel != null)
hash = hash * 59 + this.ConditionalParentLabel.GetHashCode();
if (this.ConditionalParentLabelMetadata != null)
hash = hash * 59 + this.ConditionalParentLabelMetadata.GetHashCode();
if (this.ConditionalParentValue != null)
hash = hash * 59 + this.ConditionalParentValue.GetHashCode();
if (this.ConditionalParentValueMetadata != null)
hash = hash * 59 + this.ConditionalParentValueMetadata.GetHashCode();
if (this.DocumentId != null)
hash = hash * 59 + this.DocumentId.GetHashCode();
if (this.DocumentIdMetadata != null)
hash = hash * 59 + this.DocumentIdMetadata.GetHashCode();
if (this.GroupName != null)
hash = hash * 59 + this.GroupName.GetHashCode();
if (this.GroupNameMetadata != null)
hash = hash * 59 + this.GroupNameMetadata.GetHashCode();
if (this.OriginalValue != null)
hash = hash * 59 + this.OriginalValue.GetHashCode();
if (this.OriginalValueMetadata != null)
hash = hash * 59 + this.OriginalValueMetadata.GetHashCode();
if (this.Radios != null)
hash = hash * 59 + this.Radios.GetHashCode();
if (this.RecipientId != null)
hash = hash * 59 + this.RecipientId.GetHashCode();
if (this.RecipientIdGuid != null)
hash = hash * 59 + this.RecipientIdGuid.GetHashCode();
if (this.RecipientIdGuidMetadata != null)
hash = hash * 59 + this.RecipientIdGuidMetadata.GetHashCode();
if (this.RecipientIdMetadata != null)
hash = hash * 59 + this.RecipientIdMetadata.GetHashCode();
if (this.RequireAll != null)
hash = hash * 59 + this.RequireAll.GetHashCode();
if (this.RequireAllMetadata != null)
hash = hash * 59 + this.RequireAllMetadata.GetHashCode();
if (this.RequireInitialOnSharedChange != null)
hash = hash * 59 + this.RequireInitialOnSharedChange.GetHashCode();
if (this.RequireInitialOnSharedChangeMetadata != null)
hash = hash * 59 + this.RequireInitialOnSharedChangeMetadata.GetHashCode();
if (this.Shared != null)
hash = hash * 59 + this.Shared.GetHashCode();
if (this.SharedMetadata != null)
hash = hash * 59 + this.SharedMetadata.GetHashCode();
if (this.ShareToRecipients != null)
hash = hash * 59 + this.ShareToRecipients.GetHashCode();
if (this.ShareToRecipientsMetadata != null)
hash = hash * 59 + this.ShareToRecipientsMetadata.GetHashCode();
if (this.TabType != null)
hash = hash * 59 + this.TabType.GetHashCode();
if (this.TabTypeMetadata != null)
hash = hash * 59 + this.TabTypeMetadata.GetHashCode();
if (this.TemplateLocked != null)
hash = hash * 59 + this.TemplateLocked.GetHashCode();
if (this.TemplateLockedMetadata != null)
hash = hash * 59 + this.TemplateLockedMetadata.GetHashCode();
if (this.TemplateRequired != null)
hash = hash * 59 + this.TemplateRequired.GetHashCode();
if (this.TemplateRequiredMetadata != null)
hash = hash * 59 + this.TemplateRequiredMetadata.GetHashCode();
if (this.Tooltip != null)
hash = hash * 59 + this.Tooltip.GetHashCode();
if (this.TooltipMetadata != null)
hash = hash * 59 + this.TooltipMetadata.GetHashCode();
if (this.Value != null)
hash = hash * 59 + this.Value.GetHashCode();
if (this.ValueMetadata != null)
hash = hash * 59 + this.ValueMetadata.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 56.883871 | 1,804 | 0.60355 | [
"MIT"
] | shannonmae999/docusign-esign-csharp-client | sdk/src/DocuSign.eSign/Model/RadioGroup.cs | 35,268 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.