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
// 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.Management.DataFactory.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataFactory; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// HDInsight Pig activity type. /// </summary> [Newtonsoft.Json.JsonObject("HDInsightPig")] [Rest.Serialization.JsonTransformation] public partial class HDInsightPigActivity : ExecutionActivity { /// <summary> /// Initializes a new instance of the HDInsightPigActivity class. /// </summary> public HDInsightPigActivity() { CustomInit(); } /// <summary> /// Initializes a new instance of the HDInsightPigActivity class. /// </summary> /// <param name="name">Activity name.</param> /// <param name="additionalProperties">Unmatched properties from the /// message are deserialized this collection</param> /// <param name="description">Activity description.</param> /// <param name="dependsOn">Activity depends on condition.</param> /// <param name="linkedServiceName">Linked service reference.</param> /// <param name="policy">Activity policy.</param> /// <param name="storageLinkedServices">Storage linked service /// references.</param> /// <param name="arguments">User specified arguments to /// HDInsightActivity.</param> /// <param name="getDebugInfo">Debug info option. Possible values /// include: 'None', 'Always', 'Failure'</param> /// <param name="scriptPath">Script path. Type: string (or Expression /// with resultType string).</param> /// <param name="scriptLinkedService">Script linked service /// reference.</param> /// <param name="defines">Allows user to specify defines for Pig job /// request.</param> public HDInsightPigActivity(string name, IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), string description = default(string), IList<ActivityDependency> dependsOn = default(IList<ActivityDependency>), LinkedServiceReference linkedServiceName = default(LinkedServiceReference), ActivityPolicy policy = default(ActivityPolicy), IList<LinkedServiceReference> storageLinkedServices = default(IList<LinkedServiceReference>), IList<object> arguments = default(IList<object>), string getDebugInfo = default(string), object scriptPath = default(object), LinkedServiceReference scriptLinkedService = default(LinkedServiceReference), IDictionary<string, object> defines = default(IDictionary<string, object>)) : base(name, additionalProperties, description, dependsOn, linkedServiceName, policy) { StorageLinkedServices = storageLinkedServices; Arguments = arguments; GetDebugInfo = getDebugInfo; ScriptPath = scriptPath; ScriptLinkedService = scriptLinkedService; Defines = defines; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets storage linked service references. /// </summary> [JsonProperty(PropertyName = "typeProperties.storageLinkedServices")] public IList<LinkedServiceReference> StorageLinkedServices { get; set; } /// <summary> /// Gets or sets user specified arguments to HDInsightActivity. /// </summary> [JsonProperty(PropertyName = "typeProperties.arguments")] public IList<object> Arguments { get; set; } /// <summary> /// Gets or sets debug info option. Possible values include: 'None', /// 'Always', 'Failure' /// </summary> [JsonProperty(PropertyName = "typeProperties.getDebugInfo")] public string GetDebugInfo { get; set; } /// <summary> /// Gets or sets script path. Type: string (or Expression with /// resultType string). /// </summary> [JsonProperty(PropertyName = "typeProperties.scriptPath")] public object ScriptPath { get; set; } /// <summary> /// Gets or sets script linked service reference. /// </summary> [JsonProperty(PropertyName = "typeProperties.scriptLinkedService")] public LinkedServiceReference ScriptLinkedService { get; set; } /// <summary> /// Gets or sets allows user to specify defines for Pig job request. /// </summary> [JsonProperty(PropertyName = "typeProperties.defines")] public IDictionary<string, object> Defines { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (StorageLinkedServices != null) { foreach (var element in StorageLinkedServices) { if (element != null) { element.Validate(); } } } if (ScriptLinkedService != null) { ScriptLinkedService.Validate(); } } } }
42.791367
748
0.628447
[ "MIT" ]
MarzWorldLit/azure-sdk-for-net
src/SDKs/DataFactory/Management.DataFactory/Generated/Models/HDInsightPigActivity.cs
5,948
C#
using System; using System.Diagnostics; using System.Text; using NUnit.Framework; namespace Disruptor.PerfTests.Runner { public sealed class LatencyTestRun : TestRun { private readonly LatencyPerfTest _latencyPerfTest; public LatencyTestRun(LatencyPerfTest latencyPerfTest, int run, int availableCores) : base(run, latencyPerfTest, availableCores) { _latencyPerfTest = latencyPerfTest; } public override void Run() { _latencyPerfTest.PassNumber = RunIndex; GC.Collect(); var sw = Stopwatch.StartNew(); int gen0Count = GC.CollectionCount(0); int gen1Count = GC.CollectionCount(1); int gen2Count = GC.CollectionCount(2); _latencyPerfTest.Histogram.Clear(); _latencyPerfTest.RunPass(); if (_latencyPerfTest.Histogram.Count!= 0) { Assert.AreEqual(_latencyPerfTest.Iterations, _latencyPerfTest.Histogram.Count); } DurationInMs = sw.ElapsedMilliseconds; Gen0Count = GC.CollectionCount(0) - gen0Count; Gen1Count = GC.CollectionCount(1) - gen1Count; Gen2Count = GC.CollectionCount(2) - gen2Count; Console.WriteLine("{0} : {1}", _latencyPerfTest.GetType().Name, _latencyPerfTest.Histogram); DumpHistogram(); } protected override void AppendPerfResultHtml(StringBuilder sb) { var histo = _latencyPerfTest.Histogram; sb.AppendLine(string.Format(" <td>mean={0}ns, 99%={1}ns, 99.99%={2}</td>", histo.Mean, histo.TwoNinesUpperBound, histo.FourNinesUpperBound)); } private void DumpHistogram() { var histo = _latencyPerfTest.Histogram; for (var i = 0; i < histo.Size; i++) { Console.Write(histo.GetUpperBoundAt(i)); Console.Write("\t"); Console.Write(histo.GetCountAt(i)); Console.WriteLine(); } } } }
33.539683
168
0.58495
[ "Apache-2.0" ]
gmanny/Disruptor-net
Disruptor.PerfTests/Runner/LatencyTestRun.cs
2,115
C#
using System.Collections.Generic; using Volo.Abp.Localization; namespace LINGYUN.Abp.Localization.Dynamic { public class LanguageInfoComparer : IEqualityComparer<LanguageInfo> { public bool Equals(LanguageInfo x, LanguageInfo y) { if (x == null || y == null) { return false; } return x.CultureName.Equals(y.CultureName); } public int GetHashCode(LanguageInfo obj) { return obj?.CultureName.GetHashCode() ?? GetHashCode(); } } }
23.666667
71
0.579225
[ "MIT" ]
ZhaoYis/abp-next-admin
aspnet-core/modules/common/LINGYUN.Abp.Localization.Dynamic/LINGYUN/Abp/Localization/Dynamic/LanguageInfoComparer.cs
570
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Simple.Data.Commands { using System.Dynamic; using Extensions; internal static class ArgumentHelper { internal static void CheckFindArgs(object[] args, InvokeMemberBinder binder) { if (args.Length == 0) throw new ArgumentException(binder.Name + "requires arguments."); if (args.Length == 1) { if (ReferenceEquals(args[0], null) && binder.CallInfo.ArgumentNames.Count == 0) throw new ArgumentException(binder.Name + " does not accept unnamed null argument."); } } internal static IEnumerable<KeyValuePair<string, object>> CreateCriteriaDictionary(InvokeMemberBinder binder, IList<object> args, params string[] exactNames) { IDictionary<string, object> criteriaDictionary = null; if (exactNames.Contains(binder.Name)) { if (binder.CallInfo.ArgumentNames != null && binder.CallInfo.ArgumentNames.Count > 0) { criteriaDictionary = binder.NamedArgumentsToDictionary(args); } else if (args.Count == 1) { if (ReferenceEquals(args[0], null)) throw new ArgumentException("FindBy does not accept unnamed null argument."); criteriaDictionary = args[0].ObjectToDictionary(); } } else { criteriaDictionary = MethodNameParser.ParseFromBinder(binder, args); } if (criteriaDictionary == null || criteriaDictionary.Count == 0) { throw new ArgumentException(binder.Name + " requires an equal number of column names and values to filter data by."); } return criteriaDictionary; } } }
38.980392
166
0.570423
[ "MIT" ]
SimonH/Simple.Data
Simple.Data/Commands/ArgumentHelper.cs
1,990
C#
namespace ContosoUniversityData.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddedFavoriteColor : DbMigration { public override void Up() { AddColumn("dbo.Student", "FavoriteColor", c => c.String(maxLength: 50)); } public override void Down() { DropColumn("dbo.Student", "FavoriteColor"); } } }
23.210526
84
0.578231
[ "MIT" ]
apprenda/ApplicationSamples
datatierplugin/src/sample/V2/ContosoUniversityData/Migrations/201712152123053_AddedFavoriteColor.cs
441
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/Psapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; /// <include file='PSAPI_WORKING_SET_EX_BLOCK.xml' path='doc/member[@name="PSAPI_WORKING_SET_EX_BLOCK"]/*' /> [StructLayout(LayoutKind.Explicit)] public partial struct PSAPI_WORKING_SET_EX_BLOCK { /// <include file='PSAPI_WORKING_SET_EX_BLOCK.xml' path='doc/member[@name="PSAPI_WORKING_SET_EX_BLOCK.Flags"]/*' /> [FieldOffset(0)] [NativeTypeName("ULONG_PTR")] public nuint Flags; /// <include file='PSAPI_WORKING_SET_EX_BLOCK.xml' path='doc/member[@name="PSAPI_WORKING_SET_EX_BLOCK.Anonymous"]/*' /> [FieldOffset(0)] [NativeTypeName("_PSAPI_WORKING_SET_EX_BLOCK::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.20348.0/um/Psapi.h:406:5)")] public _Anonymous_e__Union Anonymous; /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Valid"]/*' /> public nuint Valid { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Valid; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Valid = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.ShareCount"]/*' /> public nuint ShareCount { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.ShareCount; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.ShareCount = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Win32Protection"]/*' /> public nuint Win32Protection { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Win32Protection; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Win32Protection = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Shared"]/*' /> public nuint Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Shared; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Shared = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Node"]/*' /> public nuint Node { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Node; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Node = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Locked"]/*' /> public nuint Locked { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Locked; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Locked = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.LargePage"]/*' /> public nuint LargePage { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.LargePage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.LargePage = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Reserved"]/*' /> public nuint Reserved { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Reserved; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Reserved = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Bad"]/*' /> public nuint Bad { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.Bad; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.Bad = value; } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.ReservedUlong"]/*' /> public nuint ReservedUlong { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.ReservedUlong; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.ReservedUlong = value; } } /// <include file='_Anonymous_e__Union.xml' path='doc/member[@name="_Anonymous_e__Union.Invalid"]/*' /> public ref _Anonymous_e__Union._Invalid_e__Struct Invalid { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous.Invalid, 1)); } } /// <include file='_Anonymous_e__Union.xml' path='doc/member[@name="_Anonymous_e__Union"]/*' /> [StructLayout(LayoutKind.Explicit)] public partial struct _Anonymous_e__Union { /// <include file='_Anonymous_e__Union.xml' path='doc/member[@name="_Anonymous_e__Union.Anonymous"]/*' /> [FieldOffset(0)] [NativeTypeName("_PSAPI_WORKING_SET_EX_BLOCK::(anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.20348.0/um/Psapi.h:407:9)")] public _Anonymous_e__Struct Anonymous; /// <include file='_Anonymous_e__Union.xml' path='doc/member[@name="_Anonymous_e__Union.Invalid"]/*' /> [FieldOffset(0)] [NativeTypeName("struct (anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.20348.0/um/Psapi.h:422:9)")] public _Invalid_e__Struct Invalid; /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct"]/*' /> public partial struct _Anonymous_e__Struct { public nuint _bitfield; /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Valid"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Valid { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _bitfield & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~0x1u) | (value & 0x1u); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.ShareCount"]/*' /> [NativeTypeName("ULONG_PTR : 3")] public nuint ShareCount { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 1) & 0x7u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x7u << 1)) | ((value & 0x7u) << 1); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Win32Protection"]/*' /> [NativeTypeName("ULONG_PTR : 11")] public nuint Win32Protection { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 4) & 0x7FFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x7FFu << 4)) | ((value & 0x7FFu) << 4); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Shared"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 15) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 15)) | ((value & 0x1u) << 15); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Node"]/*' /> [NativeTypeName("ULONG_PTR : 6")] public nuint Node { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 16) & 0x3Fu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x3Fu << 16)) | ((value & 0x3Fu) << 16); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Locked"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Locked { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 22) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 22)) | ((value & 0x1u) << 22); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.LargePage"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint LargePage { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 23) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 23)) | ((value & 0x1u) << 23); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Reserved"]/*' /> [NativeTypeName("ULONG_PTR : 7")] public nuint Reserved { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 24) & 0x7Fu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x7Fu << 24)) | ((value & 0x7Fu) << 24); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.Bad"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Bad { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 31) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 31)) | ((value & 0x1u) << 31); } } /// <include file='_Anonymous_e__Struct.xml' path='doc/member[@name="_Anonymous_e__Struct.ReservedUlong"]/*' /> [NativeTypeName("ULONG_PTR : 32")] public nuint ReservedUlong { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 32) & 0x0u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x0u << 32)) | ((value & 0x0u) << 32); } } } /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct"]/*' /> public partial struct _Invalid_e__Struct { public nuint _bitfield; /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct.Valid"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Valid { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _bitfield & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~0x1u) | (value & 0x1u); } } /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct.Reserved0"]/*' /> [NativeTypeName("ULONG_PTR : 14")] public nuint Reserved0 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 1) & 0x3FFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x3FFFu << 1)) | ((value & 0x3FFFu) << 1); } } /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct.Shared"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 15) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 15)) | ((value & 0x1u) << 15); } } /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct.Reserved1"]/*' /> [NativeTypeName("ULONG_PTR : 15")] public nuint Reserved1 { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 16) & 0x7FFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x7FFFu << 16)) | ((value & 0x7FFFu) << 16); } } /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct.Bad"]/*' /> [NativeTypeName("ULONG_PTR : 1")] public nuint Bad { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 31) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 31)) | ((value & 0x1u) << 31); } } /// <include file='_Invalid_e__Struct.xml' path='doc/member[@name="_Invalid_e__Struct.ReservedUlong"]/*' /> [NativeTypeName("ULONG_PTR : 32")] public nuint ReservedUlong { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 32) & 0x0u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x0u << 32)) | ((value & 0x0u) << 32); } } } } }
34.161943
155
0.527021
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/Psapi/PSAPI_WORKING_SET_EX_BLOCK.cs
16,878
C#
using System.Collections.Generic; using DataCore.Adapter.Example; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; namespace DataCore.Adapter.NetFxExample { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services .AddDataCoreAdapterAspNetCoreServices() .AddAdapter<ExampleAdapter>() .AddHostInfo( "Example .NET Framework Host", "An example App Store Connect Adapters host running on ASP.NET Core 2.2 on .NET Framework", GetType().Assembly.GetName().Version.ToString(), Common.VendorInfo.Create("Intelligent Plant", "https://appstore.intelligentplant.com"), properties: new[] { Common.AdapterProperty.Create("Project URL", "https://github.com/intelligentplant/AppStoreConnect.Adapters") } ); // Add the adapter API controllers to the MVC registration. services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddDataCoreAdapterMvc() .AddJsonOptions(options => { options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); }); services .AddSignalR() .AddDataCoreAdapterSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseSignalR(route => { route.MapDataCoreAdapterHubs(); }); } } }
43.240741
132
0.613704
[ "Apache-2.0", "MIT" ]
intelligentplant/AppStoreConnect.Adapters
examples/DataCore.Adapter.NetFxExample/Startup.cs
2,337
C#
using Playnite.SDK; using CommonPluginsShared.Collections; namespace CheckDlc.Models { public class CheckDlcCollection : PluginItemCollection<GameDlc> { public CheckDlcCollection(string path, GameDatabaseCollection type = GameDatabaseCollection.Uknown) : base(path, type) { } } }
24.461538
126
0.72327
[ "MIT" ]
Lacro59/playnite-checkdlc-plugin
source/Models/CheckDlcCollection.cs
320
C#
/* Tic Tac Toe game. Author: HugeBrain16 Project URL: https://github.com/HugeBrain16/tic-tac-toe */ using System; namespace main { class main { static int check_win(int[,] board, int player) { int match; int[,] win_patterns = new int[8, 3] { // horizontal {board[0, 0], board[0, 1], board[0, 2]}, {board[1, 0], board[1, 1], board[1, 2]}, {board[2, 0], board[2, 1], board[2, 2]}, // vertical {board[0, 0], board[1, 0], board[2, 0]}, {board[0, 1], board[1, 1], board[2, 1]}, {board[0, 2], board[1, 2], board[2, 2]}, //crossed {board[0, 0], board[1, 1], board[2, 2]}, {board[2, 0], board[1, 1], board[0, 2]} }; for (int y = 0; y < 8; y++) { match = 0; for (int x = 0; x < 3; x++) { if (win_patterns[y, x] == player) { match++; } } if (match == 3) { return 1; } } return 0; } static void Main(string[] args) { int[,] board = new int[3, 3] { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; int turn_player1 = 0; int turn_player2 = 0; /* * since i don't know how to use random stuff in here and i don't want to do so... * you must do something like rock paper scissor to decide who will play first. */ while (turn_player1 == 0 && turn_player2 == 0) { Console.Write("Who play first [player 1 or 2]: "); int turn; try { turn = Convert.ToInt16(Console.ReadLine()); } catch (FormatException) { Console.Clear(); Console.WriteLine("USE DIGITS!!7!!!1!!"); continue; } catch (OverflowException) { Console.Clear(); Console.WriteLine("TOO MANY NUMBERS!!1!1!7!"); continue; } if (turn != 1 && turn != 2) { Console.Clear(); Console.WriteLine("What?! choose between player 1 or 2!!"); continue; } if (turn == 1) { turn_player1 = 1; } else if (turn == 2) { turn_player2 = 1; } Console.Clear(); } int win_player1 = 0; int win_player2 = 0; int full; while (win_player1 == 0 && win_player2 == 0) { if (turn_player1 == 1) { Console.WriteLine("Player 1 Turn!"); } else if (turn_player2 == 1) { Console.WriteLine("Player 2 Turn!"); } full = 0; // draw board for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { Console.Write('|'); if (board[y, x] == 0) { Console.Write(' '); } else if (board[y, x] == 1) { Console.Write('X'); } else if (board[y, x] == 2) { Console.Write('O'); } Console.Write('|'); } Console.Write("\n"); } int col; int row; Console.Write("Select column [int 1 - 3, 0 = reset]: "); try { col = Convert.ToInt16(Console.ReadLine()); } catch (FormatException) { Console.Clear(); Console.WriteLine("Column value must be a digit"); continue; } catch (OverflowException) { Console.Clear(); Console.WriteLine("TOO MANY NUMBERS FOR COLUMN!!!!1!1!7!!!!"); continue; } if (col == 0) { Console.Clear(); Console.WriteLine("Reset game!"); board = new int[3, 3] { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; continue; } Console.Write("Select Row [int 1 - 3, 4 = back, 0 = reset]: "); try { row = Convert.ToInt16(Console.ReadLine()); } catch (FormatException) { Console.Clear(); Console.WriteLine("Row value must be a digit"); continue; } catch (OverflowException) { Console.Clear(); Console.WriteLine("TOO MANY NUMBERS FOR ROW!!!!1!1!7!!!!"); continue; } if (row == 4) { Console.Clear(); continue; } else if (row == 0) { Console.Clear(); Console.WriteLine("Reset game!"); board = new int[3, 3] { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; continue; } if (col < 1 || col > 3) { Console.Clear(); Console.WriteLine("Column number {0} did not exists", col); continue; } if (row < 1 || row > 3) { Console.Clear(); Console.WriteLine("Row number {0} did not exists", row); continue; } col--; row--; if (board[col, row] != 0) { Console.Clear(); Console.WriteLine("Row {0} in Column {1} is not empty", row + 1, col + 1); continue; } if (turn_player1 == 1) { board[col, row] = 1; turn_player1 = 0; turn_player2 = 1; } else if (turn_player2 == 1) { board[col, row] = 2; turn_player2 = 0; turn_player1 = 1; } // check win using patterns for (int player = 1; player < 3; player++) { if (check_win(board, player) == 1) { if (player == 1) { win_player1 = 1; } else if (player == 2) { win_player2 = 1; } } } // check is board full if so, then tie for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { if (board[y, x] != 0) { full++; } } } if (full == 9) { Console.WriteLine("Tie!"); break; } } if (win_player1 == 1) { Console.WriteLine("Player 1 Win!"); } else if (win_player2 == 1) { Console.WriteLine("Player 2 Win!"); } } } }
21.67364
84
0.50444
[ "MIT" ]
HugeBrain16/tic-tac-toe
src/main.cs
5,180
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100d_f462-3281dd26")] public void Method_100d_f462() { ii(0x100d_f462, 5); push(0x48); /* push 0x48 */ ii(0x100d_f467, 5); call(Definitions.sys_check_available_stack_size, 0x8_68e6);/* call 0x10165d52 */ ii(0x100d_f46c, 1); push(ebx); /* push ebx */ ii(0x100d_f46d, 1); push(ecx); /* push ecx */ ii(0x100d_f46e, 1); push(edx); /* push edx */ ii(0x100d_f46f, 1); push(esi); /* push esi */ ii(0x100d_f470, 1); push(edi); /* push edi */ ii(0x100d_f471, 1); push(ebp); /* push ebp */ ii(0x100d_f472, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100d_f474, 6); sub(esp, 0x2c); /* sub esp, 0x2c */ ii(0x100d_f47a, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x100d_f47d, 4); or(memb[ss, ebp - 8], 1); /* or byte [ebp-0x8], 0x1 */ ii(0x100d_f481, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f484, 5); call(0x100e_0608, 0x117f); /* call 0x100e0608 */ ii(0x100d_f489, 3); mov(memd[ss, ebp - 32], eax); /* mov [ebp-0x20], eax */ ii(0x100d_f48c, 4); and(memb[ss, ebp - 8], -2 /* 0xfe */);/* and byte [ebp-0x8], 0xfe */ ii(0x100d_f490, 7); mov(memd[ss, ebp - 12], 1); /* mov dword [ebp-0xc], 0x1 */ ii(0x100d_f497, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100d_f49a, 5); add(eax, 0x2f0); /* add eax, 0x2f0 */ ii(0x100d_f49f, 5); call(0x100e_0cf0, 0x184c); /* call 0x100e0cf0 */ ii(0x100d_f4a4, 2); mov(edx, eax); /* mov edx, eax */ ii(0x100d_f4a6, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f4a9, 5); call(0x100e_0548, 0x109a); /* call 0x100e0548 */ ii(0x100d_f4ae, 2); jmp(0x100d_f4b8, 8); goto l_0x100d_f4b8;/* jmp 0x100df4b8 */ l_0x100d_f4b0: ii(0x100d_f4b0, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f4b3, 5); call(0x1007_6bf8, -0x6_88c0); /* call 0x10076bf8 */ l_0x100d_f4b8: ii(0x100d_f4b8, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100d_f4ba, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f4bd, 5); call(0x1013_ad71, 0x5_b8af); /* call 0x1013ad71 */ ii(0x100d_f4c2, 2); test(al, al); /* test al, al */ ii(0x100d_f4c4, 2); if(jz(0x100d_f4d9, 0x13)) goto l_0x100d_f4d9;/* jz 0x100df4d9 */ ii(0x100d_f4c6, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f4c9, 5); call(0x100e_047c, 0xfae); /* call 0x100e047c */ ii(0x100d_f4ce, 5); call(0x100e_0d64, 0x1891); /* call 0x100e0d64 */ ii(0x100d_f4d3, 4); cmp(ax, memw[ss, ebp - 12]); /* cmp ax, [ebp-0xc] */ ii(0x100d_f4d7, 2); if(jz(0x100d_f4db, 2)) goto l_0x100d_f4db;/* jz 0x100df4db */ l_0x100d_f4d9: ii(0x100d_f4d9, 2); jmp(0x100d_f4e3, 8); goto l_0x100d_f4e3;/* jmp 0x100df4e3 */ l_0x100d_f4db: ii(0x100d_f4db, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x100d_f4de, 3); inc(memd[ss, ebp - 12]); /* inc dword [ebp-0xc] */ ii(0x100d_f4e1, 2); jmp(0x100d_f4b0, -0x33); goto l_0x100d_f4b0;/* jmp 0x100df4b0 */ l_0x100d_f4e3: ii(0x100d_f4e3, 5); mov(eax, 0x16); /* mov eax, 0x16 */ ii(0x100d_f4e8, 5); call(Definitions.sys_new, 0x8_6913); /* call 0x10165e00 */ ii(0x100d_f4ed, 3); mov(memd[ss, ebp - 16], eax); /* mov [ebp-0x10], eax */ ii(0x100d_f4f0, 3); mov(eax, memd[ss, ebp - 16]); /* mov eax, [ebp-0x10] */ ii(0x100d_f4f3, 3); mov(memd[ss, ebp - 20], eax); /* mov [ebp-0x14], eax */ ii(0x100d_f4f6, 4); cmp(memd[ss, ebp - 20], 0); /* cmp dword [ebp-0x14], 0x0 */ ii(0x100d_f4fa, 2); if(jz(0x100d_f513, 0x17)) goto l_0x100d_f513;/* jz 0x100df513 */ ii(0x100d_f4fc, 4); movsx(edx, memw[ss, ebp - 12]); /* movsx edx, word [ebp-0xc] */ ii(0x100d_f500, 3); mov(eax, memd[ss, ebp - 16]); /* mov eax, [ebp-0x10] */ ii(0x100d_f503, 5); call(0x1016_3dd9, 0x8_48d1); /* call 0x10163dd9 */ ii(0x100d_f508, 3); mov(memd[ss, ebp - 24], eax); /* mov [ebp-0x18], eax */ ii(0x100d_f50b, 3); mov(eax, memd[ss, ebp - 24]); /* mov eax, [ebp-0x18] */ ii(0x100d_f50e, 3); mov(memd[ss, ebp - 44], eax); /* mov [ebp-0x2c], eax */ ii(0x100d_f511, 2); jmp(0x100d_f519, 6); goto l_0x100d_f519;/* jmp 0x100df519 */ l_0x100d_f513: ii(0x100d_f513, 3); mov(eax, memd[ss, ebp - 20]); /* mov eax, [ebp-0x14] */ ii(0x100d_f516, 3); mov(memd[ss, ebp - 44], eax); /* mov [ebp-0x2c], eax */ l_0x100d_f519: ii(0x100d_f519, 3); mov(eax, memd[ss, ebp - 44]); /* mov eax, [ebp-0x2c] */ ii(0x100d_f51c, 3); mov(memd[ss, ebp - 28], eax); /* mov [ebp-0x1c], eax */ ii(0x100d_f51f, 3); mov(ebx, memd[ss, ebp - 28]); /* mov ebx, [ebp-0x1c] */ ii(0x100d_f522, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f525, 5); call(0x100e_0518, 0xfee); /* call 0x100e0518 */ ii(0x100d_f52a, 2); mov(edx, eax); /* mov edx, eax */ ii(0x100d_f52c, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100d_f52f, 5); add(eax, 0x2f0); /* add eax, 0x2f0 */ ii(0x100d_f534, 5); call(0x100e_0c8c, 0x1753); /* call 0x100e0c8c */ ii(0x100d_f539, 3); mov(eax, memd[ss, ebp - 28]); /* mov eax, [ebp-0x1c] */ ii(0x100d_f53c, 3); mov(memd[ss, ebp - 40], eax); /* mov [ebp-0x28], eax */ ii(0x100d_f53f, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100d_f541, 3); lea(eax, memd[ss, ebp - 36]); /* lea eax, [ebp-0x24] */ ii(0x100d_f544, 5); call(0x100e_043c, 0xef3); /* call 0x100e043c */ ii(0x100d_f549, 2); jmp(0x100d_f555, 0xa); goto l_0x100d_f555;/* jmp 0x100df555 */ // ii(0x100d_f54b, 10); Недостижимый код. l_0x100d_f555: ii(0x100d_f555, 3); mov(eax, memd[ss, ebp - 40]); /* mov eax, [ebp-0x28] */ ii(0x100d_f558, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100d_f55a, 1); pop(ebp); /* pop ebp */ ii(0x100d_f55b, 1); pop(edi); /* pop edi */ ii(0x100d_f55c, 1); pop(esi); /* pop esi */ ii(0x100d_f55d, 1); pop(edx); /* pop edx */ ii(0x100d_f55e, 1); pop(ecx); /* pop ecx */ ii(0x100d_f55f, 1); pop(ebx); /* pop ebx */ ii(0x100d_f560, 1); ret(); /* ret */ } } }
78.631068
114
0.45734
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100d-f462.cs
8,114
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MediaBazar { public partial class RemoveManager : Form { public RemoveManager() { InitializeComponent(); } } }
18.333333
45
0.696104
[ "MIT" ]
karinakozarova/MediaBazaar
WindowsFormsApp1/MediaBazar/RemoveManager.cs
387
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("NUnit.DataTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("nunit.tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // 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.911765
85
0.723041
[ "MIT" ]
Calabaraburus/WitsParser
src/NUnit.DataTests/Properties/AssemblyInfo.cs
1,292
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("MockAllTheThings.RhinoMocks")] [assembly: AssemblyDescription("RhinoMocks support for Mock All The Things.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Phillip Wong")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Phillip Wong")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("0.2.1.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
45.913043
81
0.756629
[ "MIT" ]
plmwong/mock-all-the-things
MockAllTheThings.RhinoMocks/Properties/AssemblyInfo.cs
1,058
C#
using FrazzApps.Xamarin.Geolocator; using FrazzApps.Xamarin.Geolocator.Abstractions; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using FrazzApps.Xamarin.Geolocator.WinPhone; using Xamarin.Forms; [assembly: Dependency(typeof(FrazzApps.Xamarin.Geolocator.WinPhone.Geolocator))] namespace FrazzApps.Xamarin.Geolocator.WinPhone { public class Geolocator : IGeolocator { /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { } Windows.Devices.Geolocation.Geolocator geolocator = new Windows.Devices.Geolocation.Geolocator(); public double DesiredAccuracy { get { return (geolocator.DesiredAccuracyInMeters.HasValue) ? geolocator.DesiredAccuracyInMeters.Value : double.NaN; } set { geolocator.DesiredAccuracyInMeters = (uint)value; } } public bool IsGeolocationEnabled { get { if (geolocator == null) return false; switch (geolocator.LocationStatus) { case Windows.Devices.Geolocation.PositionStatus.Disabled: case Windows.Devices.Geolocation.PositionStatus.Initializing: case Windows.Devices.Geolocation.PositionStatus.NoData: case Windows.Devices.Geolocation.PositionStatus.NotAvailable: case Windows.Devices.Geolocation.PositionStatus.NotInitialized: return false; break; case Windows.Devices.Geolocation.PositionStatus.Ready: return true; break; } return false; } } public bool IsListening { get; private set; } public bool SupportsHeading { get; private set; } //TODO public event EventHandler<PositionEventArgs> PositionChanged; public event EventHandler<PositionErrorEventArgs> PositionError; public async Task<Position> GetPositionAsync(bool includeHeading) { var position = await geolocator.GetGeopositionAsync(); return new Position() { Accuracy = position.Coordinate.Accuracy, Altitude = position.Coordinate.Altitude, AltitudeAccuracy = position.Coordinate.AltitudeAccuracy, Heading = (includeHeading) ? position.Coordinate.Heading : null, Latitude = position.Coordinate.Latitude, Longitude = position.Coordinate.Longitude, Speed = position.Coordinate.Speed, Timestamp = position.Coordinate.Timestamp.DateTime }; } // // Summary: // Start listening to location changes // // Parameters: // minTime: // Minimum interval in milliseconds // // minDistance: // Minimum distance in meters public void StartListening(uint minTime, double minDistance) { StartListening(minTime, minDistance, true); } // // Summary: // Start listening to location changes // // Parameters: // minTime: // Minimum interval in milliseconds // // minDistance: // Minimum distance in meters // // includeHeading: // Include heading information public void StartListening(uint minTime, double minDistance, bool includeHeading) { if (!this.IsListening) { this.IsListening = true; geolocator.ReportInterval = minTime; geolocator.MovementThreshold = minDistance; geolocator.PositionChanged += geolocator_PositionChanged; geolocator.StatusChanged += geolocator_StatusChanged; } } void geolocator_StatusChanged(Windows.Devices.Geolocation.Geolocator sender, Windows.Devices.Geolocation.StatusChangedEventArgs args) { if (this.IsListening) { switch(args.Status) { case Windows.Devices.Geolocation.PositionStatus.Disabled: case Windows.Devices.Geolocation.PositionStatus.Initializing: break; case Windows.Devices.Geolocation.PositionStatus.NoData: case Windows.Devices.Geolocation.PositionStatus.NotAvailable: this.PositionError(sender, new PositionErrorEventArgs(GeolocationError.PositionUnavailable)); break; case Windows.Devices.Geolocation.PositionStatus.NotInitialized: this.PositionError(sender, new PositionErrorEventArgs(GeolocationError.Unauthorized)); break; case Windows.Devices.Geolocation.PositionStatus.Ready: break; } } } void geolocator_PositionChanged(Windows.Devices.Geolocation.Geolocator sender, Windows.Devices.Geolocation.PositionChangedEventArgs args) { if (this.IsListening) { var position = args.Position; Position p = new Position() { Accuracy = position.Coordinate.Accuracy, Altitude = position.Coordinate.Altitude, AltitudeAccuracy = position.Coordinate.AltitudeAccuracy, Heading = position.Coordinate.Heading, Latitude = position.Coordinate.Latitude, Longitude = position.Coordinate.Longitude, Speed = position.Coordinate.Speed, Timestamp = position.Coordinate.Timestamp.DateTime }; this.PositionChanged(sender, new PositionEventArgs(p)); } } // // Summary: // Stop listening to location changes public void StopListening() { this.IsListening = false; geolocator.PositionChanged -= geolocator_PositionChanged; } } }
39.509317
217
0.58167
[ "MIT" ]
FrazzApps/Xamarin.Plugins
Geolocator/Geolocator/FrazzApps.Xamarin.Geolocator.WinPhone/Geolocator.cs
6,363
C#
#region Using Statements using System; using WaveEngine.Common; using WaveEngine.Common.Graphics; using WaveEngine.Common.Math; using WaveEngine.Components.Cameras; using WaveEngine.Components.Graphics2D; using WaveEngine.Components.Graphics3D; using WaveEngine.Framework; using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Physics2D; using WaveEngine.Framework.Resources; using WaveEngine.Framework.Services; #endregion namespace RevoluteJoint2DSampleProject { public class MyScene : Scene { // Constants private const int BRIDGE_Y_POSITION = 200; private const int BRIDGE_LENGTH = 600; private const int BRIDGE_CHAIN_LINKS = 38; private const string LEFT_BRIDGE_FILENAME = "Content/PinAzureB.wpk"; private const string RIGHT_BRIDGE_FILENAME = "Content/PinAzureA.wpk"; private const string BRIDGE_LINK1_FILENAME = "Content/Wood20x5a.wpk"; private const string BRIDGE_LINK2_FILENAME = "Content/Wood20x5b.wpk"; private const string BRIDGE_LINK3_FILENAME = "Content/Wood20x5c.wpk"; private const string CRATE1_FILENAME = "Content/CrateA.wpk"; private const string CRATE2_FILENAME = "Content/CrateB.wpk"; // Instance count. Use to create different entity names. private static long instances = 0; /// <summary> /// Scene /// </summary> protected override void CreateScene() { //this.RenderManager.DebugLines = true; FixedCamera2D camera2d = new FixedCamera2D("camera"); camera2d.BackgroundColor = Color.CornflowerBlue; EntityManager.Add(camera2d); // Left Bridge Anchor Entity Pin1 = this.CreateSquareSprite("Pin1", 50, BRIDGE_Y_POSITION, LEFT_BRIDGE_FILENAME, PhysicBodyType.Static, -1f); EntityManager.Add(Pin1); // Bridge links creation Entity lastLink = null; int spacing = BRIDGE_LENGTH / BRIDGE_CHAIN_LINKS; for (int i = 0; i < BRIDGE_CHAIN_LINKS; i++) { Entity currentLink = this.CreateSquareSprite("link" + i + 1, 70 + i * spacing, BRIDGE_Y_POSITION, this.GetRandomLinkFileName(), PhysicBodyType.Dynamic, -1); EntityManager.Add(currentLink); if (i == 0) { // First Link Joins to Left Anchor currentLink.AddComponent(new JointMap2D().AddJoint("joint", new RevoluteJoint2D(Pin1, new Vector2(-6, 0), new Vector2(0, 24)))); } else { if (lastLink != null) { currentLink.AddComponent(new JointMap2D() .AddJoint("joint", new RevoluteJoint2D(lastLink, new Vector2(-8, 0), new Vector2(8, 0)) { BreakPoint = 20, })); } } lastLink = currentLink; } if (lastLink != null) { // Right Bridge Anchor Entity Pin2 = this.CreateSquareSprite("Pin2", 750, BRIDGE_Y_POSITION, RIGHT_BRIDGE_FILENAME, PhysicBodyType.Static, -1f); EntityManager.Add(Pin2); // Last Bridge Link joins to Right Anchor Pin2.AddComponent(new JointMap2D() .AddJoint("joint", new RevoluteJoint2D(lastLink, new Vector2(-1, 23), new Vector2(6, 0)))); } // Physic ground Entity ground = this.CreateSquareSprite("Ground", 400, 500, "Content/groundSprite.wpk", PhysicBodyType.Static, -1f); EntityManager.Add(ground); // Timer to create crates WaveServices.TimerFactory.CreateTimer("FallingCratesTimer", TimeSpan.FromSeconds(1.0f), () => { Entity box = this.CreateSquareSprite("Crate" + instances++, WaveServices.Random.Next(300, 400), -40, this.GetRandomCrateFileName(), PhysicBodyType.Dynamic, -1); EntityManager.Add(box); if (instances == 10) { WaveServices.TimerFactory.RemoveTimer("FallingCratesTimer"); } }); } /// <summary> /// Creates a Sprite /// </summary> /// <param name="name">Sprite Name.</param> /// <param name="x">X position.</param> /// <param name="y">Y posisition.</param> /// <param name="fileName">Sprite filename.</param> /// <param name="isKinematic">Physic IsKinetic Sprite Parameter.</param> /// <param name="mass">Physic Mass Sprite Parameter.</param> /// <returns></returns> private Entity CreateSquareSprite(string name, int x, int y, string fileName, PhysicBodyType bodyType, float mass) { Entity sprite = new Entity(name) .AddComponent(new Transform2D() { X = x, Y = y, Origin = Vector2.Center }) .AddComponent(new RectangleCollider()) .AddComponent(new Sprite(fileName)) .AddComponent(new RigidBody2D() { PhysicBodyType = bodyType }) .AddComponent(new SpriteRenderer(DefaultLayers.Alpha)); if (mass != -1) { sprite.FindComponent<RigidBody2D>().Mass = mass; } return sprite; } /// <summary> /// Gets a random link sprite file name /// </summary> /// <returns></returns> private string GetRandomLinkFileName() { double random = WaveServices.Random.NextDouble(); string result = BRIDGE_LINK1_FILENAME; if (random >= 0 && random < 1d / 3d) { result = BRIDGE_LINK1_FILENAME; } else if (random >= 1d / 3d && random < 2d / 3d) { result = BRIDGE_LINK2_FILENAME; } else { result = BRIDGE_LINK3_FILENAME; } return result; } /// <summary> /// Gets a random crate filename /// </summary> /// <returns></returns> private string GetRandomCrateFileName() { double random = WaveServices.Random.NextDouble(); string result = CRATE1_FILENAME; if (random >= 0.5d) { result = CRATE2_FILENAME; } return result; } } }
38.01676
176
0.542248
[ "MIT" ]
starostin13/Samples
Physics2D/RevoluteJoint2DSample/RevoluteJoint2DSample/RevoluteJoint2DSampleProject/MyScene.cs
6,805
C#
#region Copyright 2010 by Apache Harmony, Licensed under the Apache License, Version 2.0 /* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using J2N.Numerics; using System; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace J2N { /// <summary> /// Extensions to the <see cref="double"/> structure. /// </summary> public static class DoubleExtensions { #region IsFinite /// <summary> /// Determines whether the specified value is finite (zero, subnormal, or normal). /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the value is finite (zero, subnormal or normal); otherwise <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static unsafe bool IsFinite(this double d) { long bits = BitConversion.DoubleToRawInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000; } #endregion #region IsInfinity /// <summary> /// Returns a value indicating whether the specified value evaluates to negative or positive infinity. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the value evaluates to <see cref="double.PositiveInfinity"/> or /// <see cref="double.NegativeInfinity"/>; otherwise, <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static unsafe bool IsInfinity(this double d) { long bits = BitConversion.DoubleToRawInt64Bits(d); return (bits & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } #endregion IsInfinity #region IsNaN /// <summary> /// Returns a value that indicates whether the specified value is not a number /// (<see cref="double.NaN"/>). /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the value evaluates to <see cref="double.NaN"/>; /// otherwise, <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool IsNaN(this double d) { // A NaN will never equal itself so this is an // easy and efficient way to check for NaN. #pragma warning disable CS1718 return d != d; #pragma warning restore CS1718 } #endregion IsNaN #region IsNegative /// <summary> /// Determines whether the specified value is negative. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the value is negative; otherwise, <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static unsafe bool IsNegative(this double d) { return BitConversion.DoubleToRawInt64Bits(d) < 0; } #endregion IsNegative #region IsNegativeInfinity /// <summary> /// Returns a value indicating whether the specified number evaluates to negative /// infinity. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if <paramref name="d"/> evaluates to <see cref="double.NegativeInfinity"/>; /// otherwise, <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static unsafe bool IsNegativeInfinity(this double d) { return d == double.NegativeInfinity; } #endregion IsNegativeInfinity #region IsNegativeZero /// <summary> /// Gets a value indicating whether the current <see cref="double"/> has the value negative zero (<c>-0.0d</c>). /// While negative zero is supported by the <see cref="double"/> datatype in .NET, comparisons and string formatting ignore /// this feature. This method allows a simple way to check whether the current <see cref="double"/> has the value negative zero. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the current value represents negative zero; otherwise, <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool IsNegativeZero(this double d) { return d == 0 && IsNegative(d); } #endregion IsNegativeZero #region IsNormal /// <summary> /// Determines whether the specified value is normal. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the value is normal; <c>false</c> otherwise.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static unsafe bool IsNormal(this double d) { long bits = BitConversion.DoubleToRawInt64Bits(d); bits &= 0x7FFFFFFFFFFFFFFF; return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) != 0); } #endregion IsNormal #region IsPositiveInfinity /// <summary> /// Returns a value indicating whether the specified number evaluates to positive infinity. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if <paramref name="d"/> evaluates to <see cref="double.PositiveInfinity"/>; otherwise, <c>false</c>.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool IsPositiveInfinity(this double d) { return d == double.PositiveInfinity; } #endregion IsPositiveInfinity #region IsSubnormal /// <summary> /// Determines whether the specified value is subnormal. /// </summary> /// <param name="d">A double-precision floating-point number.</param> /// <returns><c>true</c> if the value is subnormal; <c>false</c> otherwise.</returns> #if FEATURE_METHODIMPLOPTIONS_AGRESSIVEINLINING [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static unsafe bool IsSubnormal(this double d) { long bits = BitConversion.DoubleToRawInt64Bits(d); bits &= 0x7FFFFFFFFFFFFFFF; return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) == 0); } #endregion IsSubnormal #region ToHexString /// <summary> /// Returns a hexadecimal string representation of the <see cref="double"/> argument. All characters mentioned below are ASCII characters. /// <list type="bullet"> /// <item><description>If the argument is <see cref="double.NaN"/>, the result is <see cref="NumberFormatInfo.NumberDecimalSeparator"/> /// of the <paramref name="provider"/>.</description></item> /// <item><description>Otherwise, the result is a string that represents the sign and magnitude of the argument. If the sign /// is negative, it is prefixed by <see cref="NumberFormatInfo.NegativeSign"/> of the <paramref name="provider"/>; if the /// sign is positive, no sign character appears in the result. As for the magnitude <i>m</i>: </description> /// <list type="bullet"> /// <item><description>If <i>m</i> is positive infinity, it is represented by <see cref="NumberFormatInfo.PositiveInfinitySymbol"/> of the <paramref name="provider"/>; /// if <i>m</i> is negative infinity, it is represented by <see cref="NumberFormatInfo.NegativeInfinitySymbol"/> of the <paramref name="provider"/>.</description></item> /// <item><description>If <i>m</i> is zero, it is represented by the string "0x0.0p0"; thus, negative zero produces the result /// "-0x0.0p0" and positive zero produces the result "0x0.0p0". The negative symbol is represented by <see cref="NumberFormatInfo.NegativeSign"/> /// and decimal separator character is represented by <see cref="NumberFormatInfo.NumberDecimalSeparator"/>.</description></item> /// <item><description>If <i>m</i> is a <see cref="double"/> value with a normalized representation, substrings are used to represent the significand /// and exponent fields. The significand is represented by the characters "0x1" followed by <see cref="NumberFormatInfo.NumberDecimalSeparator"/>, /// followed by a lowercase hexadecimal representation of the rest of the significand as a fraction. Trailing zeros in the hexadecimal representation are /// removed unless all the digits are zero, in which case a single zero is used. Next, the exponent is represented by "p" /// followed by a decimal string of the unbiased exponent as if produced by a call to <see cref="int.ToString()"/> with invariant culture on the exponent value. </description></item> /// <item><description>If <i>m</i> is a <see cref="double"/> value with a subnormal representation, the significand is represented by the characters "0x0" /// followed by <see cref="NumberFormatInfo.NumberDecimalSeparator"/>, followed by a hexadecimal representation of the rest of the significand as a fraction. /// Trailing zeros in the hexadecimal representation are removed. Next, the exponent is represented by "p-1022". Note that there must be at least one nonzero /// digit in a subnormal significand. </description></item> /// </list> /// </item> /// </list> /// <para/> /// The value of <see cref="NumberFormatInfo.NumberNegativePattern"/> of <paramref name="provider"/> is ignored. /// <para/> /// <h3>Examples (using <see cref="NumberFormatInfo.InvariantInfo"/>)</h3> /// <list type="table"> /// <listheader> /// <term>Floating-point Value</term> /// <term>Hexadecimal String</term> /// </listheader> /// <item> /// <term>1.0</term> /// <term>0x1.0p0</term> /// </item> /// <item> /// <term>-1.0</term> /// <term>-0x1.0p0</term> /// </item> /// <item> /// <term>2.0</term> /// <term>0x1.0p1</term> /// </item> /// <item> /// <term>3.0</term> /// <term>0x1.8p1</term> /// </item> /// <item> /// <term>0.5</term> /// <term>0x1.0p-1</term> /// </item> /// <item> /// <term>0.25</term> /// <term>0x1.0p-2</term> /// </item> /// <item> /// <term><see cref="double.MaxValue"/></term> /// <term>0x1.fffffffffffffp1023</term> /// </item> /// <item> /// <term>Minimum Normal Value</term> /// <term>0x1.0p-1022</term> /// </item> /// <item> /// <term>Maximum Subnormal Value</term> /// <term>0x0.fffffffffffffp-1022</term> /// </item> /// <item> /// <term><see cref="double.Epsilon"/></term> /// <term>0x0.0000000000001p-1022</term> /// </item> /// </list> /// <para/> /// Usage Note: To exactly match the behavior of the JDK, use <see cref="NumberFormatInfo.InvariantInfo"/> /// for <paramref name="provider"/>. /// </summary> /// <param name="value">The double to be converted.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns>A hex string representing <paramref name="value"/>.</returns> public static string ToHexString(this double value, IFormatProvider? provider) { var info = NumberFormatInfo.GetInstance(provider); if (!value.IsFinite()) { if (double.IsNaN(value)) { return info.NaNSymbol; } return value.IsNegative() ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol; } return ToHexString(value, info, upperCase: false); } internal static string ToHexString(this double value, NumberFormatInfo info, bool upperCase) { /* * Reference: http://en.wikipedia.org/wiki/IEEE_754 */ long bitValue = BitConversion.DoubleToInt64Bits(value); bool negative = (bitValue & unchecked((long)0x8000000000000000L)) != 0; // mask exponent bits and shift down long exponent = (bitValue & 0x7FF0000000000000L).TripleShift(52); // mask significand bits and shift up long significand = bitValue & 0x000FFFFFFFFFFFFFL; if (exponent == 0 && significand == 0) { if (upperCase) return string.Concat(negative ? info.NegativeSign : "", "0X0", info.NumberDecimalSeparator, "0P0"); //$NON-NLS-1$ //$NON-NLS-2$ else return string.Concat(negative ? info.NegativeSign : "", "0x0", info.NumberDecimalSeparator, "0p0"); //$NON-NLS-1$ //$NON-NLS-2$ } StringBuilder hexString = new StringBuilder(10); if (negative) { hexString.Append(info.NegativeSign); } hexString.Append(upperCase ? "0X" : "0x"); //$NON-NLS-1$ if (exponent == 0) { // denormal (subnormal) value hexString.Append('0'); //$NON-NLS-1$ hexString.Append(info.NumberDecimalSeparator); // significand is 52-bits, so there can be 13 hex digits int fractionDigits = 13; // remove trailing hex zeros, so long.ToHexString() won't print // them while ((significand != 0) && ((significand & 0xF) == 0)) { significand = significand.TripleShift(4); fractionDigits--; } string hexSignificand = significand.ToString(upperCase ? "X" : "x", info); // if there are digits left, then insert some '0' chars first if (significand != 0 && fractionDigits > hexSignificand.Length) { int digitDiff = fractionDigits - hexSignificand.Length; while (digitDiff-- != 0) { hexString.Append('0'); } } hexString.Append(hexSignificand); hexString.Append(upperCase ? "P-1022" : "p-1022"); //$NON-NLS-1$ } else { // normal value hexString.Append('1'); //$NON-NLS-1$ hexString.Append(info.NumberDecimalSeparator); // significand is 52-bits, so there can be 13 hex digits int fractionDigits = 13; // remove trailing hex zeros, so long.ToHexString() won't print // them while ((significand != 0) && ((significand & 0xF) == 0)) { significand = significand.TripleShift(4); fractionDigits--; } string hexSignificand = significand.ToString(upperCase ? "X" : "x", info); // if there are digits left, then insert some '0' chars first if (significand != 0 && fractionDigits > hexSignificand.Length) { int digitDiff = fractionDigits - hexSignificand.Length; while (digitDiff-- != 0) { hexString.Append('0'); } } hexString.Append(hexSignificand); hexString.Append(upperCase ? "P" : "p"); //$NON-NLS-1$ // remove exponent's 'bias' and convert to a string hexString.Append((exponent - 1023).ToString(CultureInfo.InvariantCulture)); } return hexString.ToString(); } #endregion ToHexString } }
45.689394
206
0.58028
[ "Apache-2.0" ]
NightOwl888/J2N
src/J2N/DoubleExtensions.cs
18,095
C#
using UnityEditor.IMGUI.Controls; using UnityEditor.Networking.PlayerConnection; using UnityEngine; using UnityEngine.Networking.PlayerConnection; using UnityEngine.XR.OpenXR; using UnityEngine.XR.OpenXR.Features.RuntimeDebugger; namespace UnityEditor.XR.OpenXR.Features.RuntimeDebugger { internal class DebuggerTreeView : TreeView { public DebuggerTreeView(TreeViewState state) : base(state) { Reload(); } protected override TreeViewItem BuildRoot() { var root = new TreeViewItem(0, -1, "Root"); foreach (var t in DebuggerState._functionCalls) { root.AddChild(t); } SetupDepthsFromParentsAndChildren(root); return root; } } internal class RuntimeDebuggerWindow : EditorWindow { private static class Styles { public static GUIStyle s_Wrap; } private static void InitStyles() { if (Styles.s_Wrap != null) return; Styles.s_Wrap = new GUIStyle(EditorStyles.label) { wordWrap = true, alignment = TextAnchor.MiddleLeft, padding = new RectOffset(0, 5, 1, 1) }; } [MenuItem("Window/Analysis/OpenXR Runtime Debugger")] [MenuItem("Window/XR/OpenXR/Runtime Debugger")] internal static void Init() { RuntimeDebuggerWindow w = EditorWindow.GetWindow<RuntimeDebuggerWindow>() as RuntimeDebuggerWindow; w.titleContent = new GUIContent("OpenXR Runtime Debugger"); w.Show(); } private IConnectionState state; void OnEnable() { state = PlayerConnectionGUIUtility.GetConnectionState(this); EditorConnection.instance.Initialize(); EditorConnection.instance.Register(RuntimeDebuggerOpenXRFeature.kPlayerToEditorSendDebuggerOutput, DebuggerState.OnMessageEvent); } void OnDisable() { EditorConnection.instance.Unregister(RuntimeDebuggerOpenXRFeature.kPlayerToEditorSendDebuggerOutput, DebuggerState.OnMessageEvent); state.Dispose(); } private Vector2 scrollpos = new Vector2(); private TreeViewState treeViewState; private DebuggerTreeView treeView; private string _lastRefreshStats; void Clear() { DebuggerState.Clear(); treeView = null; treeViewState = null; _lastRefreshStats = ""; scrollpos = Vector2.zero; } void OnGUI() { InitStyles(); var debuggerFeatureInfo = FeatureHelpers.GetFeatureWithIdForActiveBuildTarget("com.unity.openxr.features.runtimedebugger"); if (!debuggerFeatureInfo.enabled) { EditorGUILayout.BeginVertical(); EditorGUILayout.Space(); EditorGUILayout.LabelField("OpenXR Runtime Debugger must be enabled for this build target.", Styles.s_Wrap); EditorGUILayout.Space(); if (GUILayout.Button("Enable Runtime Debugger")) { debuggerFeatureInfo.enabled = true; } EditorGUILayout.EndVertical(); return; } PlayerConnectionGUILayout.ConnectionTargetSelectionDropdown(state); GUILayout.BeginHorizontal(); if (GUILayout.Button("Refresh")) { DebuggerState.SetDoneCallback(() => { if (treeViewState == null) treeViewState = new TreeViewState(); treeView = new DebuggerTreeView(treeViewState); var debugger = OpenXRSettings.ActiveBuildTargetInstance.GetFeature<RuntimeDebuggerOpenXRFeature>(); if (debugger != null) _lastRefreshStats = $"Last payload size: {DebuggerState._lastPayloadSize} ({((100.0f * DebuggerState._lastPayloadSize / debugger.cacheSize)):F2}% cache full) Number of Frames: {DebuggerState._frameCount}"; else _lastRefreshStats = $"Last payload size: {DebuggerState._lastPayloadSize} Number of Frames: {DebuggerState._frameCount}"; }); _lastRefreshStats = "Refreshing ..."; if (EditorApplication.isPlaying) { var debugger = OpenXRSettings.Instance.GetFeature<RuntimeDebuggerOpenXRFeature>(); if (debugger.enabled) { debugger.RecvMsg(new MessageEventArgs()); } } else { EditorConnection.instance.Send(RuntimeDebuggerOpenXRFeature.kEditorToPlayerRequestDebuggerOutput, new byte[]{byte.MinValue}); } } if (GUILayout.Button("Clear")) { Clear(); } if (GUILayout.Button(EditorGUIUtility.IconContent("d_SaveAs"))) { string path = EditorUtility.SaveFilePanel("Save OpenXR Dump", "", state.connectionName,"openxrdump"); if (path.Length != 0) { DebuggerState.SaveToFile(path); } } if (GUILayout.Button(EditorGUIUtility.IconContent("d_FolderOpened Icon"))) { string path = EditorUtility.OpenFilePanelWithFilters("Load OpenXR Dump", "", new [] { "OpenXR Dump", "openxrdump" }); if (path.Length != 0) { Clear(); DebuggerState.SetDoneCallback(() => { if (treeViewState == null) treeViewState = new TreeViewState(); treeView = new DebuggerTreeView(treeViewState); _lastRefreshStats = $"Last payload size: {DebuggerState._lastPayloadSize} Number of Frames: {DebuggerState._frameCount}"; }); DebuggerState.LoadFromFile(path); } } GUILayout.EndHorizontal(); GUILayout.Label($"Connections: {EditorConnection.instance.ConnectedPlayers.Count}"); GUILayout.Label(_lastRefreshStats); scrollpos = GUILayout.BeginScrollView(scrollpos); if (treeView != null) { var treeRect = GUILayoutUtility.GetRect(position.width, treeView.totalHeight); treeView.OnGUI(treeRect); } GUILayout.EndScrollView(); } } }
34.386935
229
0.556481
[ "MIT" ]
BigMeatBaoZi/SDM5002
Unity/vr_arm_ctrl/Library/PackageCache/com.unity.xr.openxr@1.3.1/RuntimeDebugger/Editor/RuntimeDebuggerWindow.cs
6,843
C#
using EvilFarmingGame.Objects.Farm.Plants; using Godot; namespace EvilFarmingGame.Items { public class Item { public string Name; public string Description; public string ID; public Texture Icon; public int MaxStackAmount; public bool IsSellable; public float BuyingPrice; public float SellingPrice; public Item(string Name, string IconPath, string Description, string ID, bool IsSellable, int MaxStackAmount = 64, float BuyingPrice = 0, float SellingPrice = 0) // Constructor with selling-price { this.Name = Name; this.Description = Description; this.ID = ID; this.MaxStackAmount = MaxStackAmount; this.IsSellable = IsSellable; this.BuyingPrice = BuyingPrice; this.SellingPrice = SellingPrice; Icon = (Texture) GD.Load(IconPath); } } public class Crop : Item { public bool IsEdible; public float StaminaIncrease; public Crop(string Name, string IconPath, string Description, string ID, bool IsEdible, bool IsSellable, int MaxStackAmount = 64, float StaminaIncrease = 0f, float BuyingPrice = 0, float SellingPrice = 0) : base(Name, IconPath, Description, ID, IsSellable, MaxStackAmount , BuyingPrice, SellingPrice) { this.StaminaIncrease = StaminaIncrease; this.IsEdible = IsEdible; } public void Eat(global::Player PlayerBody) { PlayerBody.Stamina += StaminaIncrease; PlayerBody.Inventory.Remove(this); } } public class Seed : Item { public string PlantID; public Seed(string Name, string IconPath, string Description, string ID, string plantID, bool IsSellable, int MaxStackAmount=64, float BuyingPrice = 0, float SellingPrice = 0) : base(Name, IconPath, Description, ID, IsSellable, MaxStackAmount, BuyingPrice, SellingPrice) { PlantID = plantID; } } public class Tool : Item { public delegate bool UseFunc(global::Player PlayerBody); private UseFunc UseFunction; public readonly ToolTypes Type; public float StaminaCost; public Tool(string Name, string IconPath, string Description, string ID, ToolTypes type, float StaminaCost, bool IsSellable, UseFunc UseFunction = null, float BuyingPrice = 0, float SellingPrice = 0) : base(Name, IconPath, Description, ID, IsSellable, 0, BuyingPrice, SellingPrice) { Type = type; this.UseFunction = UseFunction; this.StaminaCost = StaminaCost; } public void Use(global::Player PlayerBody) { if (UseFunction(PlayerBody)) PlayerBody.Stamina -= StaminaCost; } } public class PlaceableItem : Item { public string ScenePath; public PlaceableItem(string Name, string IconPath, string Description, string ID, string ScenePath, bool IsSellable, int MaxStackAmount, float BuyingPrice = 0, float SellingPrice = 0) : base(Name, IconPath, Description, ID, IsSellable, MaxStackAmount, BuyingPrice, SellingPrice) { this.ScenePath = ScenePath; } } public enum ToolTypes { Misc = 0, Hoe, WateringCan } }
27.857143
202
0.732991
[ "MIT" ]
ComLarsic/EFG-open-source
src/Items/Item.cs
2,925
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExitMenu : MonoBehaviour { // Start is called before the first frame update public GameObject settingCanvas; // Update is called once per frame void Update() { if (Input.GetKeyUp(KeyCode.Escape)) { if (gameObject.GetComponent<ConflictControl>().notgamescene) { settingCanvas.SetActive(true); Cursor.lockState = CursorLockMode.None; gameObject.GetComponent<ConflictControl>().notgamescene = false; } else { Cursor.lockState = CursorLockMode.Locked; foreach (Transform child in GameObject.Find("Main Camera").transform) { //if(!child.name.Equals("Main Camera")) child.gameObject.SetActive(false); } gameObject.GetComponent<ConflictControl>().notgamescene = true; } } } }
30.085714
85
0.567901
[ "MIT" ]
WangberlinT/CodingWorld
CodingWorld_Unity/Assets/Script/GamingScence/Camera/ExitMenu.cs
1,055
C#
using UnityEngine; using UnityEngine.UI; public class DEMOInterfaceManager : InterfaceManager { public override void Initialize() { gameManager = GameObject.Find("GameManager").GetComponent<GameManager>(); grupos = new Animator[NUMGROUPS-1]; grupos[BACK] = backgroundGroup; grupos[PBACK] = pauseBlurGroup; grupos[MAIN] = mainManuGroup; grupos[PAUSE] = pauseManuGroup; grupos[GSETTINGS] = gameSettingsGroup; grupos[ASETTINGS] = audioSettingsGroup; selectDefecto = new Selectable[NUMGROUPS - 1]; selectDefecto[BACK] = backgroundDefSelect; selectDefecto[PBACK] = pauseBlurDefSelect; selectDefecto[MAIN] = mainManuDefSelect; selectDefecto[PAUSE] = pauseManuDefSelect; selectDefecto[GSETTINGS] = gameSettingsManuDefSelect; selectDefecto[ASETTINGS] = audioSettingsManuDefSelect; StartMainMenu(); historialGrupos.Push(-1); LockCursor(false); } }
27.684211
82
0.645437
[ "MIT" ]
XenMoros/ProjectAlpaca
Assets/Scripts/Managers/DEMOInterfaceManager.cs
1,054
C#
/* * Copyright (c) 2006-2016, openmetaverse.co * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //#define DEBUG_VOICE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenMetaverse.Voice { public partial class VoiceGateway : IDisposable { // These states should be in increasing order of 'completeness' // so that the (int) values can drive a progress bar. public enum ConnectionState { None = 0, Provisioned, DaemonStarted, DaemonConnected, ConnectorConnected, AccountLogin, RegionCapAvailable, SessionRunning } internal string sipServer = ""; private string acctServer = "https://www.bhr.vivox.com/api2/"; private string connectionHandle; private string accountHandle; private string sessionHandle; // Parameters to Vivox daemon private string slvoicePath = ""; private string slvoiceArgs = "-ll 5"; private string daemonNode = "127.0.0.1"; private int daemonPort = 37331; private string voiceUser; private string voicePassword; private string spatialUri; private string spatialCredentials; // Session management private Dictionary<string, VoiceSession> sessions; private VoiceSession spatialSession; private Uri currentParcelCap; private Uri nextParcelCap; private string regionName; // Position update thread private Thread posThread; private ManualResetEvent posRestart; public GridClient Client; private VoicePosition position; private Vector3d oldPosition; private Vector3d oldAt; // Audio interfaces private List<string> inputDevices; /// <summary> /// List of audio input devices /// </summary> public List<string> CaptureDevices { get { return inputDevices; } } private List<string> outputDevices; /// <summary> /// List of audio output devices /// </summary> public List<string> PlaybackDevices { get { return outputDevices; } } private string currentCaptureDevice; private string currentPlaybackDevice; private bool testing = false; public event EventHandler OnSessionCreate; public event EventHandler OnSessionRemove; public delegate void VoiceConnectionChangeCallback(ConnectionState state); public event VoiceConnectionChangeCallback OnVoiceConnectionChange; public delegate void VoiceMicTestCallback(float level); public event VoiceMicTestCallback OnVoiceMicTest; public VoiceGateway(GridClient c) { Random rand = new Random(); daemonPort = rand.Next(34000, 44000); Client = c; sessions = new Dictionary<string, VoiceSession>(); position = new VoicePosition(); position.UpOrientation = new Vector3d(0.0, 1.0, 0.0); position.Velocity = new Vector3d(0.0, 0.0, 0.0); oldPosition = new Vector3d(0, 0, 0); oldAt = new Vector3d(1, 0, 0); slvoiceArgs = " -ll -1"; // Min logging slvoiceArgs += " -i 127.0.0.1:" + daemonPort.ToString(); // slvoiceArgs += " -lf " + control.instance.ClientDir; } /// <summary> /// Start up the Voice service. /// </summary> public void Start() { // Start the background thread if (posThread != null && posThread.IsAlive) posThread.Abort(); posThread = new Thread(new ThreadStart(PositionThreadBody)); posThread.Name = "VoicePositionUpdate"; posThread.IsBackground = true; posRestart = new ManualResetEvent(false); posThread.Start(); Client.Network.EventQueueRunning += new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning += new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun += new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse += new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected += new DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect += new DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent += new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent += new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent += new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent += new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent += new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); // Device events OnAuxGetCaptureDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Generic status response OnVoiceResponse += new EventHandler<VoiceResponseEventArgs>(connector_OnVoiceResponse); // Account events OnAccountLoginResponse += new EventHandler<VoiceAccountEventArgs>(connector_OnAccountLoginResponse); Logger.Log("Voice initialized", Helpers.LogLevel.Info); // If voice provisioning capability is already available, // proceed with voice startup. Otherwise the EventQueueRunning // event will do it. System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); if (vCap != null) RequestVoiceProvision(vCap); } /// <summary> /// Handle miscellaneous request status /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ///<remarks>If something goes wrong, we log it.</remarks> void connector_OnVoiceResponse(object sender, VoiceGateway.VoiceResponseEventArgs e) { if (e.StatusCode == 0) return; Logger.Log(e.Message + " on " + sender as string, Helpers.LogLevel.Error); } public void Stop() { Client.Network.EventQueueRunning -= new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun -= new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse -= new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected -= new VoiceGateway.DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect -= new VoiceGateway.DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent -= new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent -= new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent -= new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent -= new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent -= new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); OnSessionParticipantRemovedEvent -= new EventHandler<ParticipantRemovedEventArgs>(connector_OnSessionParticipantRemovedEvent); // Tuning events OnAuxGetCaptureDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Account events OnAccountLoginResponse -= new EventHandler<VoiceGateway.VoiceAccountEventArgs>(connector_OnAccountLoginResponse); // Stop the background thread if (posThread != null) { PosUpdating(false); if (posThread.IsAlive) posThread.Abort(); posThread = null; } // Close all sessions foreach (VoiceSession s in sessions.Values) { if (OnSessionRemove != null) OnSessionRemove(s, EventArgs.Empty); s.Close(); } // Clear out lots of state so in case of restart we begin at the beginning. currentParcelCap = null; sessions.Clear(); accountHandle = null; voiceUser = null; voicePassword = null; SessionTerminate(sessionHandle); sessionHandle = null; AccountLogout(accountHandle); accountHandle = null; ConnectorInitiateShutdown(connectionHandle); connectionHandle = null; StopDaemon(); } /// <summary> /// Cleanup oject resources /// </summary> public void Dispose() { Stop(); } internal string GetVoiceDaemonPath() { string myDir = Path.GetDirectoryName( (System.Reflection.Assembly.GetEntryAssembly() ?? typeof (VoiceGateway).Assembly).Location); if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix) { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice.exe")); if (File.Exists(localDaemon)) return localDaemon; string progFiles; if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { progFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); } else { progFiles = Environment.GetEnvironmentVariable("ProgramFiles"); } if (System.IO.File.Exists(Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"))) { return Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"); } return Path.Combine(myDir, @"SLVoice.exe"); } else { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice")); if (File.Exists(localDaemon)) return localDaemon; return Path.Combine(myDir,"SLVoice"); } } void RequestVoiceProvision(System.Uri cap) { OpenMetaverse.Http.CapsClient capClient = new OpenMetaverse.Http.CapsClient(cap); capClient.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(cClient_OnComplete); OSD postData = new OSD(); // STEP 0 Logger.Log("Requesting voice capability", Helpers.LogLevel.Info); capClient.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Request voice cap when changing regions /// </summary> void Network_EventQueueRunning(object sender, EventQueueRunningEventArgs e) { // We only care about the sim we are in. if (e.Simulator != Client.Network.CurrentSim) return; // Did we provision voice login info? if (string.IsNullOrEmpty(voiceUser)) { // The startup steps are // 0. Get voice account info // 1. Start Daemon // 2. Create TCP connection // 3. Create Connector // 4. Account login // 5. Create session // Get the voice provisioning data System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); // Do we have voice capability? if (vCap == null) { Logger.Log("Null voice capability after event queue running", Helpers.LogLevel.Warning); } else { RequestVoiceProvision(vCap); } return; } else { // Change voice session for this region. ParcelChanged(); } } #region Participants void connector_OnSessionParticipantUpdatedEvent(object sender, ParticipantUpdatedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.ParticipantUpdate(e.URI, e.IsMuted, e.IsSpeaking, e.Volume, e.Energy); } public string SIPFromUUID(UUID id) { return "sip:" + nameFromID(id) + "@" + sipServer; } private static string nameFromID(UUID id) { string result = null; if (id == UUID.Zero) return result; // Prepending this apparently prevents conflicts with reserved names inside the vivox and diamondware code. result = "x"; // Base64 encode and replace the pieces of base64 that are less compatible // with e-mail local-parts. // See RFC-4648 "Base 64 Encoding with URL and Filename Safe Alphabet" byte[] encbuff = id.GetBytes(); result += Convert.ToBase64String(encbuff); result = result.Replace('+', '-'); result = result.Replace('/', '_'); return result; } void connector_OnSessionParticipantAddedEvent(object sender, ParticipantAddedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) { Logger.Log("Orphan participant", Helpers.LogLevel.Error); return; } s.AddParticipant(e.URI); } void connector_OnSessionParticipantRemovedEvent(object sender, ParticipantRemovedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.RemoveParticipant(e.URI); } #endregion #region Sessions void connector_OnSessionAddedEvent(object sender, SessionAddedEventArgs e) { sessionHandle = e.SessionHandle; // Create our session context. VoiceSession s = FindSession(sessionHandle, true); s.RegionName = regionName; spatialSession = s; // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); Logger.Log("Added voice session in " + regionName, Helpers.LogLevel.Info); } /// <summary> /// Handle a change in session state /// </summary> void connector_OnSessionStateChangeEvent(object sender, SessionStateChangeEventArgs e) { VoiceSession s; switch (e.State) { case VoiceGateway.SessionState.Connected: s = FindSession(e.SessionHandle, true); sessionHandle = e.SessionHandle; s.RegionName = regionName; spatialSession = s; Logger.Log("Voice connected in " + regionName, Helpers.LogLevel.Info); // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); break; case VoiceGateway.SessionState.Disconnected: s = FindSession(sessionHandle, false); sessions.Remove(sessionHandle); if (s != null) { Logger.Log("Voice disconnected in " + s.RegionName, Helpers.LogLevel.Info); // Inform interested parties if (OnSessionRemove != null) OnSessionRemove(s, null); if (s == spatialSession) spatialSession = null; } // The previous session is now ended. Check for a new one and // start it going. if (nextParcelCap != null) { currentParcelCap = nextParcelCap; nextParcelCap = null; RequestParcelInfo(currentParcelCap); } break; } } /// <summary> /// Close a voice session /// </summary> /// <param name="sessionHandle"></param> internal void CloseSession(string sessionHandle) { if (!sessions.ContainsKey(sessionHandle)) return; PosUpdating(false); ReportConnectionState(ConnectionState.AccountLogin); // Clean up spatial pointers. VoiceSession s = sessions[sessionHandle]; if (s.IsSpatial) { spatialSession = null; currentParcelCap = null; } // Remove this session from the master session list sessions.Remove(sessionHandle); // Let any user-facing code clean up. if (OnSessionRemove != null) OnSessionRemove(s, null); // Tell SLVoice to clean it up as well. SessionTerminate(sessionHandle); } /// <summary> /// Locate a Session context from its handle /// </summary> /// <remarks>Creates the session context if it does not exist.</remarks> VoiceSession FindSession(string sessionHandle, bool make) { if (sessions.ContainsKey(sessionHandle)) return sessions[sessionHandle]; if (!make) return null; // Create a new session and add it to the sessions list. VoiceSession s = new VoiceSession(this, sessionHandle); // Turn on position updating for spatial sessions // (For now, only spatial sessions are supported) if (s.IsSpatial) PosUpdating(true); // Register the session by its handle sessions.Add(sessionHandle, s); return s; } #endregion #region MinorResponses void connector_OnAuxAudioPropertiesEvent(object sender, AudioPropertiesEventArgs e) { if (OnVoiceMicTest != null) OnVoiceMicTest(e.MicEnergy); } #endregion private void ReportConnectionState(ConnectionState s) { if (OnVoiceConnectionChange == null) return; OnVoiceConnectionChange(s); } /// <summary> /// Handle completion of main voice cap request. /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void cClient_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { if (error != null) { Logger.Log("Voice cap error " + error.Message, Helpers.LogLevel.Error); return; } Logger.Log("Voice provisioned", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.Provisioned); OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; // We can get back 4 interesting values: // voice_sip_uri_hostname // voice_account_server_name (actually a full URI) // username // password if (pMap.ContainsKey("voice_sip_uri_hostname")) sipServer = pMap["voice_sip_uri_hostname"].AsString(); if (pMap.ContainsKey("voice_account_server_name")) acctServer = pMap["voice_account_server_name"].AsString(); voiceUser = pMap["username"].AsString(); voicePassword = pMap["password"].AsString(); // Start the SLVoice daemon slvoicePath = GetVoiceDaemonPath(); // Test if the executable exists if (!System.IO.File.Exists(slvoicePath)) { Logger.Log("SLVoice is missing", Helpers.LogLevel.Error); return; } // STEP 1 StartDaemon(slvoicePath, slvoiceArgs); } #region Daemon void connector_OnDaemonCouldntConnect() { Logger.Log("No voice daemon connect", Helpers.LogLevel.Error); } void connector_OnDaemonCouldntRun() { Logger.Log("Daemon not started", Helpers.LogLevel.Error); } /// <summary> /// Daemon has started so connect to it. /// </summary> void connector_OnDaemonRunning() { OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); Logger.Log("Daemon started", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonStarted); // STEP 2 ConnectToDaemon(daemonNode, daemonPort); } /// <summary> /// The daemon TCP connection is open. /// </summary> void connector_OnDaemonConnected() { Logger.Log("Daemon connected", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonConnected); // The connector is what does the logging. VoiceGateway.VoiceLoggingSettings vLog = new VoiceGateway.VoiceLoggingSettings(); #if DEBUG_VOICE vLog.Enabled = true; vLog.FileNamePrefix = "OpenmetaverseVoice"; vLog.FileNameSuffix = ".log"; vLog.LogLevel = 4; #endif // STEP 3 int reqId = ConnectorCreate( "V2 SDK", // Magic value keeps SLVoice happy acctServer, // Account manager server 30000, 30099, // port range vLog); if (reqId < 0) { Logger.Log("No voice connector request", Helpers.LogLevel.Error); } } /// <summary> /// Handle creation of the Connector. /// </summary> void connector_OnConnectorCreateResponse( object sender, VoiceGateway.VoiceConnectorEventArgs e) { Logger.Log("Voice daemon protocol started " + e.Message, Helpers.LogLevel.Info); connectionHandle = e.Handle; if (e.StatusCode != 0) return; // STEP 4 AccountLogin( connectionHandle, voiceUser, voicePassword, "VerifyAnswer", // This can also be "AutoAnswer" "", // Default account management server URI 10, // Throttle state changes true); // Enable buddies and presence } #endregion void connector_OnAccountLoginResponse( object sender, VoiceGateway.VoiceAccountEventArgs e) { Logger.Log("Account Login " + e.Message, Helpers.LogLevel.Info); accountHandle = e.AccountHandle; ReportConnectionState(ConnectionState.AccountLogin); ParcelChanged(); } #region Audio devices /// <summary> /// Handle response to audio output device query /// </summary> void connector_OnAuxGetRenderDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { outputDevices = e.Devices; currentPlaybackDevice = e.CurrentDevice; } /// <summary> /// Handle response to audio input device query /// </summary> void connector_OnAuxGetCaptureDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { inputDevices = e.Devices; currentCaptureDevice = e.CurrentDevice; } public string CurrentCaptureDevice { get { return currentCaptureDevice; } set { currentCaptureDevice = value; AuxSetCaptureDevice(value); } } public string PlaybackDevice { get { return currentPlaybackDevice; } set { currentPlaybackDevice = value; AuxSetRenderDevice(value); } } public int MicLevel { set { ConnectorSetLocalMicVolume(connectionHandle, value); } } public int SpkrLevel { set { ConnectorSetLocalSpeakerVolume(connectionHandle, value); } } public bool MicMute { set { ConnectorMuteLocalMic(connectionHandle, value); } } public bool SpkrMute { set { ConnectorMuteLocalSpeaker(connectionHandle, value); } } /// <summary> /// Set audio test mode /// </summary> public bool TestMode { get { return testing; } set { testing = value; if (testing) { if (spatialSession != null) { spatialSession.Close(); spatialSession = null; } AuxCaptureAudioStart(0); } else { AuxCaptureAudioStop(); ParcelChanged(); } } } #endregion /// <summary> /// Set voice channel for new parcel /// </summary> /// internal void ParcelChanged() { // Get the capability for this parcel. Caps c = Client.Network.CurrentSim.Caps; System.Uri pCap = c.CapabilityURI("ParcelVoiceInfoRequest"); if (pCap == null) { Logger.Log("Null voice capability", Helpers.LogLevel.Error); return; } // Parcel has changed. If we were already in a spatial session, we have to close it first. if (spatialSession != null) { nextParcelCap = pCap; CloseSession(spatialSession.Handle); } // Not already in a session, so can start the new one. RequestParcelInfo(pCap); } private OpenMetaverse.Http.CapsClient parcelCap; /// <summary> /// Request info from a parcel capability Uri. /// </summary> /// <param name="cap"></param> void RequestParcelInfo(Uri cap) { Logger.Log("Requesting region voice info", Helpers.LogLevel.Info); parcelCap = new OpenMetaverse.Http.CapsClient(cap); parcelCap.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); OSD postData = new OSD(); currentParcelCap = cap; parcelCap.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Receive parcel voice cap /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void pCap_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { parcelCap.OnComplete -= new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); parcelCap = null; if (error != null) { Logger.Log("Region voice cap " + error.Message, Helpers.LogLevel.Error); return; } OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; regionName = pMap["region_name"].AsString(); ReportConnectionState(ConnectionState.RegionCapAvailable); if (pMap.ContainsKey("voice_credentials")) { OpenMetaverse.StructuredData.OSDMap cred = pMap["voice_credentials"] as OpenMetaverse.StructuredData.OSDMap; if (cred.ContainsKey("channel_uri")) spatialUri = cred["channel_uri"].AsString(); if (cred.ContainsKey("channel_credentials")) spatialCredentials = cred["channel_credentials"].AsString(); } if (spatialUri == null || spatialUri == "") { // "No voice chat allowed here"); return; } Logger.Log("Voice connecting for region " + regionName, Helpers.LogLevel.Info); // STEP 5 int reqId = SessionCreate( accountHandle, spatialUri, // uri "", // Channel name seems to be always null spatialCredentials, // spatialCredentials, // session password true, // Join Audio false, // Join Text ""); if (reqId < 0) { Logger.Log("Voice Session ReqID " + reqId.ToString(), Helpers.LogLevel.Error); } } #region Location Update /// <summary> /// Tell Vivox where we are standing /// </summary> /// <remarks>This has to be called when we move or turn.</remarks> internal void UpdatePosition(AgentManager self) { // Get position in Global coordinates Vector3d OMVpos = new Vector3d(self.GlobalPosition); // Do not send trivial updates. if (OMVpos.ApproxEquals(oldPosition, 1.0)) return; oldPosition = OMVpos; // Convert to the coordinate space that Vivox uses // OMV X is East, Y is North, Z is up // VVX X is East, Y is up, Z is South position.Position = new Vector3d(OMVpos.X, OMVpos.Z, -OMVpos.Y); // TODO Rotate these two vectors // Get azimuth from the facing Quaternion. // By definition, facing.W = Cos( angle/2 ) double angle = 2.0 * Math.Acos(self.Movement.BodyRotation.W); position.LeftOrientation = new Vector3d(-1.0, 0.0, 0.0); position.AtOrientation = new Vector3d((float)Math.Acos(angle), 0.0, -(float)Math.Asin(angle)); SessionSet3DPosition( sessionHandle, position, position); } /// <summary> /// Start and stop updating out position. /// </summary> /// <param name="go"></param> internal void PosUpdating(bool go) { if (go) posRestart.Set(); else posRestart.Reset(); } private void PositionThreadBody() { while (true) { posRestart.WaitOne(); Thread.Sleep(1500); UpdatePosition(Client.Self); } } #endregion } }
35.057769
129
0.557929
[ "BSD-3-Clause" ]
BigManzai/libopenmetaverse
OpenMetaverse/Voice/VoiceControl.cs
35,198
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("Sklad.UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sklad.UnitTests")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("df45036b-b8a2-490a-b822-5baa7f8375fb")] // 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.783784
84
0.747496
[ "MIT" ]
Flexberry/automated-testing-course-2020
2 Unit testing CSharp/Sklad/Sklad.UnitTests/Properties/AssemblyInfo.cs
1,401
C#
using CocosSharp; namespace CocosSharpSamples.CCDrawNode.UWP { public class GameDelegate : CCApplicationDelegate { public override void ApplicationDidFinishLaunching (CCApplication application, CCWindow mainWindow) { application.PreferMultiSampling = false; application.ContentRootDirectory = "Content"; application.ContentSearchPaths.Add ("animations"); application.ContentSearchPaths.Add ("fonts"); application.ContentSearchPaths.Add ("sounds"); CCSize windowSize = mainWindow.WindowSizeInPixels; float desiredWidth = 1024.0f; float desiredHeight = 768.0f; // This will set the world bounds to be (0,0, w, h) // CCSceneResolutionPolicy.ShowAll will ensure that the aspect ratio is preserved CCScene.SetDefaultDesignResolution (desiredWidth, desiredHeight, CCSceneResolutionPolicy.ShowAll); // Determine whether to use the high or low def versions of our images // Make sure the default texel to content size ratio is set correctly // Of course you're free to have a finer set of image resolutions e.g (ld, hd, super-hd) if (desiredWidth < windowSize.Width) { application.ContentSearchPaths.Add ("images/hd"); CCSprite.DefaultTexelToContentSizeRatio = 2.0f; } else { application.ContentSearchPaths.Add ("images/ld"); CCSprite.DefaultTexelToContentSizeRatio = 1.0f; } CCScene scene = new CCScene (mainWindow); GameLayer gameLayer = new GameLayer (); scene.AddChild (gameLayer); mainWindow.RunWithScene (scene); } public override void ApplicationDidEnterBackground (CCApplication application) { application.Paused = true; } public override void ApplicationWillEnterForeground (CCApplication application) { application.Paused = false; } } }
31.596491
101
0.734037
[ "MIT" ]
iivchenko/Learning-CocosSharp
src/CocosSharpSamples/CCDrawNode/CocosSharpSamples.CCDrawNode.UWP/GameDelegate.cs
1,803
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("UnifiedLogViewerPlugins")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnifiedLogViewerPlugins")] [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("ad8cfaeb-ba41-49b4-b3da-76923eb45fcb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.216216
84
0.751768
[ "BSD-2-Clause", "Unlicense" ]
Diedinium/Community
Support/UnifiedLogViewer/UnifiedLogViewer/UnifiedLogViewerPlugins/Properties/AssemblyInfo.cs
1,417
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.AzureNextGen.Network.V20160901.Inputs { /// <summary> /// Network security rule. /// </summary> public sealed class SecurityRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. /// </summary> [Input("access", required: true)] public Input<string> Access { get; set; } = null!; /// <summary> /// A description for this rule. Restricted to 140 chars. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The destination address prefix. CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. /// </summary> [Input("destinationAddressPrefix", required: true)] public Input<string> DestinationAddressPrefix { get; set; } = null!; /// <summary> /// The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. /// </summary> [Input("destinationPortRange")] public Input<string>? DestinationPortRange { get; set; } /// <summary> /// The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values are: 'Inbound' and 'Outbound'. /// </summary> [Input("direction", required: true)] public Input<string> Direction { get; set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. /// </summary> [Input("priority")] public Input<int>? Priority { get; set; } /// <summary> /// Network protocol this rule applies to. Possible values are 'Tcp', 'Udp', and '*'. /// </summary> [Input("protocol", required: true)] public Input<string> Protocol { get; set; } = null!; /// <summary> /// The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [Input("provisioningState")] public Input<string>? ProvisioningState { get; set; } /// <summary> /// The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. /// </summary> [Input("sourceAddressPrefix", required: true)] public Input<string> SourceAddressPrefix { get; set; } = null!; /// <summary> /// The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. /// </summary> [Input("sourcePortRange")] public Input<string>? SourcePortRange { get; set; } public SecurityRuleArgs() { } } }
40.990099
265
0.608213
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20160901/Inputs/SecurityRuleArgs.cs
4,140
C#
using Xunit; using Sellix.Net; namespace Tests { public class OrderTest { [Fact] public void Test() { Sellix.Net.Sellix sellix = new Sellix.Net.Sellix(Token.Get, new System.Net.Http.HttpClient()); var orders = sellix.Orders.GetOrders(); Assert.Equal(200, orders.Status); } } }
21.117647
106
0.571031
[ "Unlicense" ]
Speedo69/Sellix.net
Tests/OrderTest.cs
361
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 System.Security.Policy { public abstract partial class CodeGroup { protected CodeGroup(System.Security.Policy.IMembershipCondition membershipCondition, System.Security.Policy.PolicyStatement policy) { } public virtual string AttributeString { get { return null; } } public System.Collections.IList Children { get; set; } public string Description { get; set; } public System.Security.Policy.IMembershipCondition MembershipCondition { get; set; } public abstract string MergeLogic { get; } public string Name { get; set; } public virtual string PermissionSetName { get { return null; } } public System.Security.Policy.PolicyStatement PolicyStatement { get; set; } public void AddChild(System.Security.Policy.CodeGroup group) { } public abstract System.Security.Policy.CodeGroup Copy(); protected virtual void CreateXml(SecurityElement element, System.Security.Policy.PolicyLevel level) { } public override bool Equals(object o) => base.Equals(o); public void FromXml(SecurityElement e) { } public void FromXml(SecurityElement e, System.Security.Policy.PolicyLevel level) { } public bool Equals(System.Security.Policy.CodeGroup cg, bool compareChildren) { return false; } public override int GetHashCode() => base.GetHashCode(); protected virtual void ParseXml(SecurityElement e, System.Security.Policy.PolicyLevel level) { } public void RemoveChild(System.Security.Policy.CodeGroup group) { } public abstract System.Security.Policy.PolicyStatement Resolve(System.Security.Policy.Evidence evidence); public abstract System.Security.Policy.CodeGroup ResolveMatchingCodeGroups(System.Security.Policy.Evidence evidence); public SecurityElement ToXml() { return default(SecurityElement); } public SecurityElement ToXml(System.Security.Policy.PolicyLevel level) { return default(SecurityElement); } } }
64.911765
143
0.733122
[ "MIT" ]
robertmclaws/corefx
src/System.Security.Permissions/src/System/Security/Policy/CodeGroup.cs
2,209
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xunit; using static MimeDetective.Utilities.TypeComparisions; namespace MimeDetective.Tests.Documents { public class OpenDocFormats { public const string DocsPath = "./Data/Documents/"; [Theory] [InlineData("OpenDocWord2016")] [InlineData("OpenOfficeDoc")] public async Task IsOpenDoc(string filePath) { var info = GetFileInfo(DocsPath, filePath, ".odt"); await AssertIsType(info, MimeTypes.ODT); } [Theory] [InlineData("OpenOfficePresentation")] public async Task IsOpenPresentation(string filePath) { var info = GetFileInfo(DocsPath, filePath, ".odp"); await AssertIsType(info, MimeTypes.ODP); } [Theory] [InlineData("OpenOfficeSpreadsheet")] public async Task IsOpenSpreadSheet(string filePath) { var info = GetFileInfo(DocsPath, filePath, ".ods"); await AssertIsType(info, MimeTypes.ODS); } } }
26.27907
63
0.626549
[ "MIT" ]
HenricObjektvision/Mime-Detective
test/Mime-Detective.Tests/Tests/Documents/OpenDocFormats.cs
1,132
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace FilterExample { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
27.318182
76
0.703827
[ "CC0-1.0" ]
SamuelGuerin/420-GEJ-HY
FilterExample/FilterExample/Program.cs
603
C#
using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Connector.Authentication; using Microsoft.Extensions.Logging; using StarterBot.Middleware; using System; namespace StarterBot.Adapters { public class AdapterWithErrorHandler : BotFrameworkHttpAdapter { public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger<BotFrameworkHttpAdapter> logger, ResetStateMiddleware resetStateMiddleware, ShowTypingMiddleware showTypingMiddleware, ConversationState conversationState = null) : base(credentialProvider) { if (credentialProvider == null) { throw new NullReferenceException(nameof(credentialProvider)); } if (logger == null) { throw new NullReferenceException(nameof(logger)); } if (showTypingMiddleware == null) { throw new NullReferenceException(nameof(showTypingMiddleware)); } if (resetStateMiddleware == null) { throw new NullReferenceException(nameof(resetStateMiddleware)); } // Add middleware to the adapter's middleware pipeline Use(showTypingMiddleware); Use(resetStateMiddleware); OnTurnError = async (turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; } } }
36.782609
117
0.570528
[ "MIT" ]
daltskin/Bot-Starter-Template
src/Adapters/AdapterWithErrorHandler.cs
2,540
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the gamelift-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.GameLift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.GameLift.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GameSession Object /// </summary> public class GameSessionUnmarshaller : IUnmarshaller<GameSession, XmlUnmarshallerContext>, IUnmarshaller<GameSession, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> GameSession IUnmarshaller<GameSession, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public GameSession Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; GameSession unmarshalledObject = new GameSession(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("CreationTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreationTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreatorId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.CreatorId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CurrentPlayerSessionCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.CurrentPlayerSessionCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DnsName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DnsName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FleetArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.FleetArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FleetId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.FleetId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("GameProperties", targetDepth)) { var unmarshaller = new ListUnmarshaller<GameProperty, GamePropertyUnmarshaller>(GamePropertyUnmarshaller.Instance); unmarshalledObject.GameProperties = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("GameSessionData", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.GameSessionData = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("GameSessionId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.GameSessionId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("IpAddress", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.IpAddress = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MatchmakerData", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.MatchmakerData = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MaximumPlayerSessionCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MaximumPlayerSessionCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PlayerSessionCreationPolicy", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.PlayerSessionCreationPolicy = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Port", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Port = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StatusReason", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.StatusReason = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TerminationTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.TerminationTime = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static GameSessionUnmarshaller _instance = new GameSessionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static GameSessionUnmarshaller Instance { get { return _instance; } } } }
41.969072
146
0.568779
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/GameLift/Generated/Model/Internal/MarshallTransformations/GameSessionUnmarshaller.cs
8,142
C#
using Countdown_ASP.NET.Data; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Swashbuckle.AspNetCore.Annotations; using Countdown_ASP.NET.Models; namespace Countdown_ASP.NET.Controllers { [ApiController] [Route(Entrypoint)] public class ProductController : ControllerBase { public const string Entrypoint = "/api/products"; private readonly ProductDbContext _dbContext; public ProductController(ProductDbContext dbContext) { _dbContext = dbContext; } [HttpGet] [SwaggerOperation( OperationId = "GetProducts", Summary = "Retrieve all Products", Description = "Publicly available" )] [SwaggerResponse(200, "List of public product data", Type = typeof(List<Product>))] public ActionResult GetResources() => Ok(_dbContext.Products.ToList()); [HttpPost] [SwaggerOperation(OperationId = "RegisterProduct", Summary = "Create a new Product")] [SwaggerResponse(201, "Returns new data", Type = typeof(Product))] [SwaggerResponse(400, "Invalid or missing data", Type = null)] //public ActionResult RegisterProduct([FromBody] NewProductDto NewProductDto) //public async Task<ActionResult<Product>> RegisterProduct([FromBody] NewProductDto NewProductDto) //{ // var productEntry = _dbContext.Products.Add(new Product()); // productEntry.CurrentValues.SetValues(NewProductDto); // //_dbContext.SaveChanges(); // await _dbContext.SaveChangesAsync(); // var newProduct = productEntry.Entity; // return CreatedAtAction( // nameof(GetProduct), // new { entityId = newProduct.Id }, // newProduct // ); //} public async Task<ActionResult<NewProductDto>> RegisterProduct([FromBody] NewProductDto NewProductDto) { //if (await UserExist(NewUserDto.Name)) return BadRequest("Username is taken"); var productEntry = _dbContext.Products.Add(new Product()); productEntry.CurrentValues.SetValues(NewProductDto); await _dbContext.SaveChangesAsync(); var newProduct = productEntry.Entity; return new NewProductDto { Title = newProduct.Title, ReleaseDate = newProduct.ReleaseDate, ImgLink = newProduct.ImgLink }; } [HttpGet] [Route("{productId}")] [SwaggerOperation(OperationId = "GetProduct", Summary = "Retrieve Product data")] [SwaggerResponse(200, "Complete Product data", Type = typeof(Product))] [SwaggerResponse(404, "Product not found", Type = null)] public ActionResult GetProduct([FromRoute] long productId) { var product = _dbContext.Products.Find(productId); if (product == null) return NotFound(); return Ok(product); } [HttpDelete] [Route("{productId}")] [SwaggerOperation( OperationId = "DeleteProduct", Summary = "Cancel (delete) an Product" )] [ProducesResponseType(204)] // suppress default swagger 200 response code [SwaggerResponse(204, "No content success", Type = null)] public ActionResult DeleteProduct([FromRoute] long productId) { _dbContext.Products.Remove(new Product { Id = productId }); try { _dbContext.SaveChanges(); } catch (DbUpdateConcurrencyException) { // row did not exist return NotFound(); } return NoContent(); } } }
34.175439
110
0.608316
[ "MIT" ]
LaunchCodeLiftoffProjects/CountDown
countDownBackEnd/Countdown ASP.NET/Controllers/ProductController.cs
3,898
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.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.CCC.Model.V20170705 { public class ListAgentSummaryReportsSinceMidnightResponse : AcsResponse { private string requestId; private bool? success; private string code; private string message; private int? httpStatusCode; private ListAgentSummaryReportsSinceMidnight_PagedAgentSummaryReport pagedAgentSummaryReport; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public string Code { get { return code; } set { code = value; } } public string Message { get { return message; } set { message = value; } } public int? HttpStatusCode { get { return httpStatusCode; } set { httpStatusCode = value; } } public ListAgentSummaryReportsSinceMidnight_PagedAgentSummaryReport PagedAgentSummaryReport { get { return pagedAgentSummaryReport; } set { pagedAgentSummaryReport = value; } } public class ListAgentSummaryReportsSinceMidnight_PagedAgentSummaryReport { private int? totalCount; private int? pageNumber; private int? pageSize; private List<ListAgentSummaryReportsSinceMidnight_AgentSummaryReport> list; public int? TotalCount { get { return totalCount; } set { totalCount = value; } } public int? PageNumber { get { return pageNumber; } set { pageNumber = value; } } public int? PageSize { get { return pageSize; } set { pageSize = value; } } public List<ListAgentSummaryReportsSinceMidnight_AgentSummaryReport> List { get { return list; } set { list = value; } } public class ListAgentSummaryReportsSinceMidnight_AgentSummaryReport { private string timestamp; private string instanceId; private string agentId; private string loginName; private string agentName; private string skillGroupIds; private string skillGroupNames; private ListAgentSummaryReportsSinceMidnight_Overall overall; private ListAgentSummaryReportsSinceMidnight_Inbound inbound; private ListAgentSummaryReportsSinceMidnight_Outbound outbound; public string Timestamp { get { return timestamp; } set { timestamp = value; } } public string InstanceId { get { return instanceId; } set { instanceId = value; } } public string AgentId { get { return agentId; } set { agentId = value; } } public string LoginName { get { return loginName; } set { loginName = value; } } public string AgentName { get { return agentName; } set { agentName = value; } } public string SkillGroupIds { get { return skillGroupIds; } set { skillGroupIds = value; } } public string SkillGroupNames { get { return skillGroupNames; } set { skillGroupNames = value; } } public ListAgentSummaryReportsSinceMidnight_Overall Overall { get { return overall; } set { overall = value; } } public ListAgentSummaryReportsSinceMidnight_Inbound Inbound { get { return inbound; } set { inbound = value; } } public ListAgentSummaryReportsSinceMidnight_Outbound Outbound { get { return outbound; } set { outbound = value; } } public class ListAgentSummaryReportsSinceMidnight_Overall { private long? totalCalls; private long? totalLoggedInTime; private long? totalBreakTime; private float? occupancyRate; private long? totalReadyTime; private long? maxReadyTime; private long? averageReadyTime; private long? totalTalkTime; private long? maxTalkTime; private long? averageTalkTime; private long? totalWorkTime; private long? maxWorkTime; private long? averageWorkTime; private float? satisfactionIndex; private long? satisfactionSurveysOffered; private long? satisfactionSurveysResponded; public long? TotalCalls { get { return totalCalls; } set { totalCalls = value; } } public long? TotalLoggedInTime { get { return totalLoggedInTime; } set { totalLoggedInTime = value; } } public long? TotalBreakTime { get { return totalBreakTime; } set { totalBreakTime = value; } } public float? OccupancyRate { get { return occupancyRate; } set { occupancyRate = value; } } public long? TotalReadyTime { get { return totalReadyTime; } set { totalReadyTime = value; } } public long? MaxReadyTime { get { return maxReadyTime; } set { maxReadyTime = value; } } public long? AverageReadyTime { get { return averageReadyTime; } set { averageReadyTime = value; } } public long? TotalTalkTime { get { return totalTalkTime; } set { totalTalkTime = value; } } public long? MaxTalkTime { get { return maxTalkTime; } set { maxTalkTime = value; } } public long? AverageTalkTime { get { return averageTalkTime; } set { averageTalkTime = value; } } public long? TotalWorkTime { get { return totalWorkTime; } set { totalWorkTime = value; } } public long? MaxWorkTime { get { return maxWorkTime; } set { maxWorkTime = value; } } public long? AverageWorkTime { get { return averageWorkTime; } set { averageWorkTime = value; } } public float? SatisfactionIndex { get { return satisfactionIndex; } set { satisfactionIndex = value; } } public long? SatisfactionSurveysOffered { get { return satisfactionSurveysOffered; } set { satisfactionSurveysOffered = value; } } public long? SatisfactionSurveysResponded { get { return satisfactionSurveysResponded; } set { satisfactionSurveysResponded = value; } } } public class ListAgentSummaryReportsSinceMidnight_Inbound { private long? callsOffered; private long? callsHandled; private float? handleRate; private long? totalRingTime; private long? maxRingTime; private long? averageRingTime; private float? serviceLevel20; private long? totalTalkTime; private long? maxTalkTime; private long? averageTalkTime; private long? totalWorkTime; private long? maxWorkTime; private long? averageWorkTime; private float? satisfactionIndex; private long? satisfactionSurveysOffered; private long? satisfactionSurveysResponded; public long? CallsOffered { get { return callsOffered; } set { callsOffered = value; } } public long? CallsHandled { get { return callsHandled; } set { callsHandled = value; } } public float? HandleRate { get { return handleRate; } set { handleRate = value; } } public long? TotalRingTime { get { return totalRingTime; } set { totalRingTime = value; } } public long? MaxRingTime { get { return maxRingTime; } set { maxRingTime = value; } } public long? AverageRingTime { get { return averageRingTime; } set { averageRingTime = value; } } public float? ServiceLevel20 { get { return serviceLevel20; } set { serviceLevel20 = value; } } public long? TotalTalkTime { get { return totalTalkTime; } set { totalTalkTime = value; } } public long? MaxTalkTime { get { return maxTalkTime; } set { maxTalkTime = value; } } public long? AverageTalkTime { get { return averageTalkTime; } set { averageTalkTime = value; } } public long? TotalWorkTime { get { return totalWorkTime; } set { totalWorkTime = value; } } public long? MaxWorkTime { get { return maxWorkTime; } set { maxWorkTime = value; } } public long? AverageWorkTime { get { return averageWorkTime; } set { averageWorkTime = value; } } public float? SatisfactionIndex { get { return satisfactionIndex; } set { satisfactionIndex = value; } } public long? SatisfactionSurveysOffered { get { return satisfactionSurveysOffered; } set { satisfactionSurveysOffered = value; } } public long? SatisfactionSurveysResponded { get { return satisfactionSurveysResponded; } set { satisfactionSurveysResponded = value; } } } public class ListAgentSummaryReportsSinceMidnight_Outbound { private long? callsDialed; private long? callsAnswered; private float? answerRate; private long? totalDialingTime; private long? maxDialingTime; private long? averageDialingTime; private long? totalTalkTime; private long? maxTalkTime; private long? averageTalkTime; private long? totalWorkTime; private string maxWorkTime; private long? averageWorkTime; private float? satisfactionIndex; private long? satisfactionSurveysOffered; private long? satisfactionSurveysResponded; public long? CallsDialed { get { return callsDialed; } set { callsDialed = value; } } public long? CallsAnswered { get { return callsAnswered; } set { callsAnswered = value; } } public float? AnswerRate { get { return answerRate; } set { answerRate = value; } } public long? TotalDialingTime { get { return totalDialingTime; } set { totalDialingTime = value; } } public long? MaxDialingTime { get { return maxDialingTime; } set { maxDialingTime = value; } } public long? AverageDialingTime { get { return averageDialingTime; } set { averageDialingTime = value; } } public long? TotalTalkTime { get { return totalTalkTime; } set { totalTalkTime = value; } } public long? MaxTalkTime { get { return maxTalkTime; } set { maxTalkTime = value; } } public long? AverageTalkTime { get { return averageTalkTime; } set { averageTalkTime = value; } } public long? TotalWorkTime { get { return totalWorkTime; } set { totalWorkTime = value; } } public string MaxWorkTime { get { return maxWorkTime; } set { maxWorkTime = value; } } public long? AverageWorkTime { get { return averageWorkTime; } set { averageWorkTime = value; } } public float? SatisfactionIndex { get { return satisfactionIndex; } set { satisfactionIndex = value; } } public long? SatisfactionSurveysOffered { get { return satisfactionSurveysOffered; } set { satisfactionSurveysOffered = value; } } public long? SatisfactionSurveysResponded { get { return satisfactionSurveysResponded; } set { satisfactionSurveysResponded = value; } } } } } } }
15.727457
96
0.497713
[ "Apache-2.0" ]
bitType/aliyun-openapi-net-sdk
aliyun-net-sdk-ccc/CCC/Model/V20170705/ListAgentSummaryReportsSinceMidnightResponse.cs
15,523
C#
// Copyright 2020 Jon Skeet. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.Linq; using VDrumExplorer.Utility; namespace VDrumExplorer.Model.Schema.Physical { /// <summary> /// A container that only contains other containers. /// </summary> public sealed class ContainerContainer : ContainerBase { /// <summary> /// The list of containers within this one. /// </summary> public IReadOnlyList<IContainer> Containers { get; } /// <summary> /// A map from container name to container. /// </summary> public IReadOnlyDictionary<string, IContainer> ContainersByName { get; } internal ContainerContainer(ModuleSchema schema, string name, string description, ModuleAddress address, string path, List<IContainer> containers) : base(schema, name, description, address, path) { Containers = containers; foreach (ContainerBase container in Containers) { container.Parent = this; } ContainersByName = Containers.ToDictionary(c => c.Name).AsReadOnly(); } } }
33.552632
154
0.639216
[ "Apache-2.0" ]
fredatgithub/DemoCode
Drums/VDrumExplorer.Model/Schema/Physical/ContainerContainer.cs
1,277
C#
// <auto-generated /> // Built from: hl7.fhir.r5.core version: 4.6.0 // Option: "NAMESPACE" = "fhirCsR5" using fhirCsR5.Models; namespace fhirCsR5.ValueSets { /// <summary> /// The current status of the task. /// </summary> public static class TaskStatusCodes { /// <summary> /// The potential performer has agreed to execute the task but has not yet started work. /// </summary> public static readonly Coding Accepted = new Coding { Code = "accepted", Display = "Accepted", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task was not completed. /// </summary> public static readonly Coding Cancelled = new Coding { Code = "cancelled", Display = "Cancelled", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task has been completed. /// </summary> public static readonly Coding Completed = new Coding { Code = "completed", Display = "Completed", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task is not yet ready to be acted upon. /// </summary> public static readonly Coding Draft = new Coding { Code = "draft", Display = "Draft", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task should never have existed and is retained only because of the possibility it may have used. /// </summary> public static readonly Coding EnteredInError = new Coding { Code = "entered-in-error", Display = "Entered in Error", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task was attempted but could not be completed due to some error. /// </summary> public static readonly Coding Failed = new Coding { Code = "failed", Display = "Failed", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task has been started but is not yet complete. /// </summary> public static readonly Coding InProgress = new Coding { Code = "in-progress", Display = "In Progress", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task has been started but work has been paused. /// </summary> public static readonly Coding OnHold = new Coding { Code = "on-hold", Display = "On Hold", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task is ready to be performed, but no action has yet been taken. Used in place of requested/received/accepted/rejected when request assignment and acceptance is a given. /// </summary> public static readonly Coding Ready = new Coding { Code = "ready", Display = "Ready", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// A potential performer has claimed ownership of the task and is evaluating whether to perform it. /// </summary> public static readonly Coding Received = new Coding { Code = "received", Display = "Received", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The potential performer who claimed ownership of the task has decided not to execute it prior to performing any action. /// </summary> public static readonly Coding Rejected = new Coding { Code = "rejected", Display = "Rejected", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// The task is ready to be acted upon and action is sought. /// </summary> public static readonly Coding Requested = new Coding { Code = "requested", Display = "Requested", System = "http://hl7.org/fhir/task-status" }; /// <summary> /// Literal for code: Accepted /// </summary> public const string LiteralAccepted = "accepted"; /// <summary> /// Literal for code: Cancelled /// </summary> public const string LiteralCancelled = "cancelled"; /// <summary> /// Literal for code: Completed /// </summary> public const string LiteralCompleted = "completed"; /// <summary> /// Literal for code: Draft /// </summary> public const string LiteralDraft = "draft"; /// <summary> /// Literal for code: EnteredInError /// </summary> public const string LiteralEnteredInError = "entered-in-error"; /// <summary> /// Literal for code: Failed /// </summary> public const string LiteralFailed = "failed"; /// <summary> /// Literal for code: InProgress /// </summary> public const string LiteralInProgress = "in-progress"; /// <summary> /// Literal for code: OnHold /// </summary> public const string LiteralOnHold = "on-hold"; /// <summary> /// Literal for code: Ready /// </summary> public const string LiteralReady = "ready"; /// <summary> /// Literal for code: Received /// </summary> public const string LiteralReceived = "received"; /// <summary> /// Literal for code: Rejected /// </summary> public const string LiteralRejected = "rejected"; /// <summary> /// Literal for code: Requested /// </summary> public const string LiteralRequested = "requested"; }; }
28.940217
182
0.600751
[ "MIT" ]
microsoft-healthcare-madison/argonaut-subscription-server-proxy
argonaut-subscription-server-proxy/Fhir/R5/ValueSets/TaskStatus.cs
5,325
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SpartanX.Services { public interface IReadService<T, TSearch> where T: class where TSearch: class { IEnumerable<T> Get(TSearch search = null); public T GetById(int id); } }
22.142857
81
0.706452
[ "MIT" ]
6en6ar/SpartanX_RS2_Seminarski
SpartanX/SpartanX/Services/IReadService.cs
312
C#
using UnityEngine; using System.Collections; public class gazMove : MonoBehaviour { private int saveNum; private float maxWidth = -2.1f; private float minWidth = -2.7f; void Start() { saveNum = Random.Range(1, 3); } void Update() { transform.position -= new Vector3((2f) * Time.deltaTime, 0.0f, 0.0f); if (saveNum == 1) { transform.position = new Vector3(transform.position.x, transform.position.y + 0.03f, transform.position.z); } else if (saveNum == 2) { transform.position = new Vector3(transform.position.x, transform.position.y - 0.03f, transform.position.z); } if (transform.position.y >= maxWidth) { saveNum = 2; } else if (transform.position.y <= minWidth) { saveNum = 1; } } }
26.085714
120
0.535597
[ "Unlicense" ]
iidan/Android2D-game-developed-in-unity3D
gazMove.cs
915
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FPS : MonoBehaviour { public float avgFrameRate; public Text texto; public void Update() { avgFrameRate = Time.frameCount / Time.time; texto.text = "FPS : " + avgFrameRate; } }
19.352941
51
0.680851
[ "MIT" ]
AdrianN17/Proyecto_Robot_IA
Assets/Scripts/FPS.cs
329
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WinAuth.ViewComponents { public class RandomNumberViewComponent : ViewComponent { private readonly Random _rnd; public RandomNumberViewComponent() { _rnd = new Random(); } public async Task<IViewComponentResult> InvokeAsync(int? max = Int32.MaxValue) { await Task.Delay(200); return View(_rnd.Next()); } } }
22.346154
87
0.611015
[ "MIT" ]
faddiv/Misc
AspPlay/WinAuth/ViewComponents/RandomNumberViewComponent.cs
558
C#
// Copyright © 2015 - Present RealDimensions Software, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace chocolatey.package.validator.infrastructure.app.rules { using NuGet; using infrastructure.rules; public class PackageIdUsesDotsNote : BasePackageRule { public override string ValidationFailureMessage { get { return @"The package id includes dots (.). Usually the package id is separated by '-' instead of dots (except in the case of *.install and *.portable). The reviewer will ensure this is not a new package. [More...](https://docs.chocolatey.org/en-us/community-repository/moderation/package-validator/rules/cpmr0061)"; } } public override PackageValidationOutput is_valid(IPackage package) { var packageId = package.Id.to_lower(); if ( packageId.Contains(".portable") || packageId.Contains(".commandline") || packageId.Contains(".install") || packageId.Contains(".extension") || packageId.Contains(".template") || packageId.Contains(".powershell") ) return true; return !package.Id.Contains("."); } } }
40.863636
309
0.647386
[ "Apache-2.0" ]
chocolatey/package-validator
src/chocolatey.package.validator/infrastructure.app/rules/PackageIdUsesDotsNote.cs
1,801
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("MergeGraphs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MergeGraphs")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("f1b637d7-678d-4674-9d85-90127e2aab25")] // 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.567568
84
0.747482
[ "MIT" ]
balintn22/MetaDependencies
MergeGraphs/Properties/AssemblyInfo.cs
1,393
C#
namespace SimpleMVC.Framework.Routers { using SimpleMVC.Framework.Attributes.Methods; using SimpleMVC.Framework.Controllers; using SimpleMVC.Framework.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using WebServer.Contracts; using WebServer.Enums; using WebServer.Extensions; using WebServer.Http.Contracts; using WebServer.Http.Response; /// <summary> /// The main purpose of this class would be to transform the incoming request to a response. /// </summary> public class ControllerRouter : IHandleable { public IHttpResponse Handle(IHttpRequest request) { IDictionary<string, string> getParams = request.UrlParameters; IDictionary<string, string> postParams = request.FormData; string requestMethod = request.Method.ToString().ToUpper(); var urlTokens = request.Path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (urlTokens.Length != 2) { return new BadRequestResponse(); } string controllerName = urlTokens[0].ToUpperFirstLetter(); string actionName = urlTokens[1].ToUpperFirstLetter(); Controller controller = this.GetController(controllerName); if (controller != null) { controller.Request = request; controller.InitializeController(); } MethodInfo method = this.GetMethod(controller, actionName, requestMethod); if (method == null) { return new NotFoundResponse(); } ParameterInfo[] parameters = method.GetParameters(); object[] methodParams = this.AddParameters(parameters, getParams, postParams); try { IHttpResponse response = this.GetResponse(method, controller, methodParams); return response; } catch (Exception ex) { return new InternalServerErrorResponse(ex); } } private IHttpResponse GetResponse(MethodInfo method, Controller controller, object[] methodParams) { object actionResult = method.Invoke(controller, methodParams); IHttpResponse response = null; if (actionResult is IViewable) { string content = ((IViewable)actionResult).Invoke(); response = new ContentResponse(HttpStatusCode.Ok, content); } else if (actionResult is IRedirectable) { string redirectUrl = ((IRedirectable)actionResult).Invoke(); response = new RedirectResponse(redirectUrl); } return response; } private object[] AddParameters(ParameterInfo[] parameters, IDictionary<string, string> getParams, IDictionary<string, string> postParams) { object[] methodParams = new object[parameters.Count()]; for (int index = 0; index < parameters.Length; index++) { ParameterInfo parameter = parameters[index]; if (parameter.ParameterType.IsPrimitive || parameter.ParameterType == typeof(string)) { methodParams[index] = this.ProcessPrimitiveParameters(getParams, parameter); } else { methodParams[index] = ProcessComplexParameters(postParams, parameter); } } return methodParams; } private object ProcessPrimitiveParameters(IDictionary<string, string> getParams, ParameterInfo parameter) { object value = getParams[parameter.Name]; return Convert.ChangeType(value, parameter.ParameterType); } private object ProcessComplexParameters(IDictionary<string, string> postParams, ParameterInfo parameter) { Type bindingModelType = parameter.ParameterType; object bindingModel = Activator.CreateInstance(bindingModelType); IEnumerable<PropertyInfo> properties = bindingModelType.GetProperties(); foreach (PropertyInfo property in properties) { property.SetValue( bindingModel, Convert.ChangeType(postParams[property.Name], property.PropertyType) ); } return Convert.ChangeType(bindingModel, bindingModelType); ; } // Returns the requested method from the controller or null if no such method is found. private MethodInfo GetMethod(Controller controller, string actionName, string requestMethod) { foreach (MethodInfo methodInfo in this.GetSiutableMethods(controller, actionName)) { IEnumerable<Attribute> attributes = methodInfo .GetCustomAttributes() .Where(attribute => attribute is HttpMethodAttribute); if (!attributes.Any() && requestMethod == "GET") { return methodInfo; } foreach (HttpMethodAttribute attribute in attributes) { if (attribute.IsValid(requestMethod)) { return methodInfo; } } } // method not found return null; } // The GetSuitableMethods() method get all methods of the requested controller. private IEnumerable<MethodInfo> GetSiutableMethods(Controller controller, string actionName) { if (controller == null) { return new MethodInfo[0]; } return controller .GetType() .GetMethods() .Where(method => method.Name == actionName); } // The GetController() method creates an instance of the requested controller using the full path to the controller in the project. private Controller GetController(string controllerName) { var controllerFullyQualifiedname = string.Format( "{0}.{1}.{2}{3}, {0}", MvcContext.Get.AssemblyName, MvcContext.Get.ControllersFolder, controllerName, MvcContext.Get.ControllersSuffix ); Type type = Type.GetType(controllerFullyQualifiedname); if (type == null) { return null; } var controller = (Controller)Activator.CreateInstance(type); return controller; } } }
35.782383
145
0.572401
[ "MIT" ]
Steffkn/SoftUni
05.CSharpWeb/01.Basics/06.SimpleMVC/SimpleMVC.Framework/Routers/ControllerRouter.cs
6,908
C#
 namespace DDictionary.Domain.Entities { public enum WordGroup: byte { E_TotallyUnknown = 10, D_NeedToMemorize = 20, C_KindaKnown = 30, B_WellKnown = 40, A_DefinitelyKnown = 50 } }
18
37
0.594017
[ "Apache-2.0" ]
Alex-D-Green/DDictionary
Domain/Entities/WordGroup.cs
236
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.Xml; using System.IO; namespace VcProjectSerialize { public class ProjectSerializer : IProjSerializer { private XmlSerializer Serializer; public ProjectSerializer() { Serializer = new XmlSerializer(typeof(Project)); } public Project ReadProjectFile(string filename) { if(!File.Exists(filename)) { return null; } FileStream file = new FileStream(filename, FileMode.Open); Project proj = (Project)Serializer.Deserialize(file); file.Close(); return proj; } public void WriteProjectFile(Project proj, string filename) { FileStream outfile = new FileStream(filename, FileMode.Create); StreamWriter writer = new StreamWriter(outfile, Encoding.UTF8); XmlWriterSettings writerSetting = new XmlWriterSettings(); writerSetting.Indent = true; writerSetting.IndentChars = "\t"; writerSetting.Encoding = Encoding.UTF8; var xmlWriter = XmlWriter.Create(writer, writerSetting); var xns = new XmlSerializerNamespaces(); xns.Add(string.Empty, "http://schemas.microsoft.com/developer/msbuild/2003"); Serializer.Serialize(xmlWriter, proj, xns); outfile.Close(); } } }
30.115385
89
0.614943
[ "MIT" ]
CylonWarrior/UnrealIncludesFix
ProjectSerializer/ProjectSerializer.cs
1,568
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #nullable enable #pragma warning disable CS1591 #pragma warning disable CS0108 #pragma warning disable 618 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using JetBrains.Space.Common; using JetBrains.Space.Common.Json.Serialization; using JetBrains.Space.Common.Json.Serialization.Polymorphism; using JetBrains.Space.Common.Types; namespace JetBrains.Space.Client.M2PollContentPartialBuilder; public static class M2PollContentPartialExtensions { public static Partial<M2PollContent> WithPoll(this Partial<M2PollContent> it) => it.AddFieldName("poll"); public static Partial<M2PollContent> WithPoll(this Partial<M2PollContent> it, Func<Partial<PollRecord>, Partial<PollRecord>> partialBuilder) => it.AddFieldName("poll", partialBuilder(new Partial<PollRecord>(it))); }
33.952381
144
0.693548
[ "Apache-2.0" ]
JetBrains/space-dotnet-sdk
src/JetBrains.Space.Client/Generated/Partials/M2PollContentPartialBuilder.generated.cs
1,426
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Pronto { public static class StringExtensions { public static IEnumerable<XObject> NewLinesToBr(this string s) { var lines = s.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); return lines.SelectMany(line => new XObject[] { new XElement("br"), new XText(line) }).Skip(1); } public static string ToJavascriptString(this string s) { if (s == null || s.Length == 0) { return "\"\""; } char c; int i; int len = s.Length; StringBuilder sb = new StringBuilder(len + 4); string t; sb.Append('"'); for (i = 0; i < len; i += 1) { c = s[i]; if ((c == '\\') || (c == '"') || (c == '>')) { sb.Append('\\'); sb.Append(c); } else if (c == '\b') sb.Append("\\b"); else if (c == '\t') sb.Append("\\t"); else if (c == '\n') sb.Append("\\n"); else if (c == '\f') sb.Append("\\f"); else if (c == '\r') sb.Append("\\r"); else { if (c < ' ') { //t = "000" + Integer.toHexString(c); string tmp = new string(c, 1); t = "000" + int.Parse(tmp, System.Globalization.NumberStyles.HexNumber); sb.Append("\\u" + t.Substring(t.Length - 4)); } else { sb.Append(c); } } } sb.Append('"'); return sb.ToString(); } } }
31.397059
108
0.346136
[ "MIT" ]
Saeed-munir/prontocms
Source/Pronto/StringExtensions.cs
2,137
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Toolkit.Uwp.Deferred; namespace Microsoft.Toolkit.Uwp.UI.Controls { /// <summary> /// Event arguments for <see cref="TokenizingTextBox.TokenItemRemoving"/> event. /// </summary> public class TokenItemRemovingEventArgs : DeferredCancelEventArgs { /// <summary> /// Initializes a new instance of the <see cref="TokenItemRemovingEventArgs"/> class. /// </summary> /// <param name="item">Item being removed.</param> /// <param name="token"><see cref="TokenizingTextBoxItem"/> container being closed.</param> public TokenItemRemovingEventArgs(object item, TokenizingTextBoxItem token) { Item = item; Token = token; } /// <summary> /// Gets the Item being closed. /// </summary> public object Item { get; private set; } /// <summary> /// Gets the <see cref="TokenizingTextBoxItem"/> being removed. /// </summary> public TokenizingTextBoxItem Token { get; private set; } } }
36.2
99
0.632202
[ "MIT" ]
Difegue/WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls/TokenizingTextBox/TokenItemRemovingEventArgs.cs
1,269
C#
#if RAZENSOFT_FUNCTIONAL_UNITASK_SUPPORT using System; using Cysharp.Threading.Tasks; namespace Razensoft.Functional { public static partial class AsyncResultExtensionsBothOperands { public static UniTask<Result<T>> CheckIf<T>(this UniTask<Result<T>> resultUniTask, bool condition, Func<T, UniTask<Result>> func) { if (condition) return resultUniTask.Check(func); else return resultUniTask; } public static UniTask<Result<T>> CheckIf<T, K>(this UniTask<Result<T>> resultUniTask, bool condition, Func<T, UniTask<Result<K>>> func) { if (condition) return resultUniTask.Check(func); else return resultUniTask; } public static UniTask<Result<T, E>> CheckIf<T, K, E>(this UniTask<Result<T, E>> resultUniTask, bool condition, Func<T, UniTask<Result<K, E>>> func) { if (condition) return resultUniTask.Check(func); else return resultUniTask; } public static async UniTask<Result<T>> CheckIf<T>(this UniTask<Result<T>> resultUniTask, Func<T, bool> predicate, Func<T, UniTask<Result>> func) { Result<T> result = await resultUniTask; if (result.IsSuccess && predicate(result.Value)) return await result.Check(func); else return result; } public static async UniTask<Result<T>> CheckIf<T, K>(this UniTask<Result<T>> resultUniTask, Func<T, bool> predicate, Func<T, UniTask<Result<K>>> func) { Result<T> result = await resultUniTask; if (result.IsSuccess && predicate(result.Value)) return await result.Check(func); else return result; } public static async UniTask<Result<T, E>> CheckIf<T, K, E>(this UniTask<Result<T, E>> resultUniTask, Func<T, bool> predicate, Func<T, UniTask<Result<K, E>>> func) { Result<T, E> result = await resultUniTask; if (result.IsSuccess && predicate(result.Value)) return await result.Check(func); else return result; } } } #endif
34.757576
170
0.578901
[ "MIT" ]
Razenpok/Razensoft.Functional
src/Razensoft.Functional/Runtime/Result/UniTask/CheckIfAsyncBoth.cs
2,294
C#
 using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml.Linq; using BrightstarDB.Client; using BrightstarDB.Rdf; using BrightstarDB.Storage; using NUnit.Framework; namespace BrightstarDB.Server.IntegrationTests { [TestFixture] public class ClientTests : ClientTestBase { private readonly string _storeLocation; public ClientTests() { #if PORTABLE var appSettings = new System.Configuration.AppSettingsReader(); _storeLocation = appSettings.GetValue("BrightstarDB.StoreLocation", typeof (string)) as string; #else var appSettings = System.Configuration.ConfigurationManager.AppSettings; _storeLocation = appSettings.Get("BrightstarDB.StoreLocation"); #endif } private static IBrightstarService GetClient() { return BrightstarService.GetClient("type=rest;endpoint=http://localhost:8090/brightstar"); } [TestFixtureSetUp] public void SetUp() { StartService(); } [TestFixtureTearDown] public void TearDown() { CloseService(); } [Test] public void TestCreateStore() { var bc = GetClient(); var sid = Guid.NewGuid().ToString(); bc.CreateStore(sid); } [Test] public void TestInvalidStoreNames() { var bc = GetClient(); try { bc.CreateStore(null); Assert.Fail("Expected ArgumentNullException"); } catch(ArgumentNullException) { // Expected } try { bc.CreateStore(String.Empty); Assert.Fail("Expected ArgumentException (empty string)"); } catch(ArgumentException) { // Expected } try { bc.CreateStore("This is\\an invalid\\store name"); Assert.Fail("Expected ArgumentException (backslash in name)"); }catch(ArgumentException) { //Expected } try { bc.CreateStore("This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long.This is an invalid store name because it is too long."); Assert.Fail("Expected ArgumentException (name too long)"); } catch(ArgumentException) { // Expected } } [Test] public void TestIfStoreExistsFalseWhenNoStoreCreated() { var bc = GetClient(); var sid = Guid.NewGuid().ToString(); var exists = bc.DoesStoreExist(sid); Assert.IsFalse(exists); } [Test] public void TestIfStoreExistsTrueAfterStoreCreated() { var bc = GetClient(); var sid = Guid.NewGuid().ToString(); bc.CreateStore(sid); var exists = bc.DoesStoreExist(sid); Assert.IsTrue(exists); } [Test] [ExpectedException(typeof(BrightstarClientException))] public void TestCreateDuplicateStoreFails() { var bc = GetClient(); var sid = Guid.NewGuid().ToString(); bc.CreateStore(sid); bc.CreateStore(sid); } [Test] public void TestDeleteStore() { var bc = GetClient(); // create store var sid = Guid.NewGuid().ToString(); bc.CreateStore(sid); // check it is there var stores = bc.ListStores(); Assert.AreEqual(1, stores.Where(s => s.Equals(sid)).Count()); // delete store bc.DeleteStore(sid); // check it is gone stores = bc.ListStores(); Assert.AreEqual(0, stores.Where(s => s.Equals(sid)).Count()); } [Test] public void TestListStores() { var bc = GetClient(); var stores = bc.ListStores(); Assert.IsTrue(stores.Count() > 0); } [Test] public void TestQuery() { var client = GetClient(); var storeName = "Client.TestQuery_" + DateTime.Now.Ticks; client.CreateStore(storeName); client.ExecuteQuery(storeName, "SELECT ?s WHERE { ?s ?p ?o }"); } [Test] public void TestQueryIfNotModifiedSince() { var client = GetClient(); var storeName = "Client.TestQueryIfNotModifiedSince_" + DateTime.Now.Ticks; client.CreateStore(storeName); client.ExecuteQuery(storeName, "SELECT ?s WHERE { ?s ?p ?o }"); var lastResponseTime = client.LastResponseTimestamp; Assert.IsNotNull(lastResponseTime); try { client.ExecuteQuery(storeName, "SELECT ?s WHERE {?s ?p ?o}", lastResponseTime); Assert.Fail("Expected a BrightstarClientException"); } catch (BrightstarClientException clientException) { //Assert.AreEqual(typeof (BrightstarStoreNotModifiedException).FullName, // clientException.InnerException.Type); Assert.AreEqual("Store not modified", clientException.Message); } } [Test] public void TestListJobs() { var client = GetClient(); var storeName = "ListJobs_" + DateTime.Now.Ticks; const string batch1 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource1> ."; const string batch2 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource2> ."; const string batch3 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource3> ."; // Prepare store with three consecutive commits client.CreateStore(storeName); var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = batch1}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = batch2}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = batch3}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); var jobs = client.GetJobInfo(storeName, 0, 10).ToList(); Assert.That(jobs, Is.Not.Null); Assert.That(jobs, Has.Count.EqualTo(3)); jobs = client.GetJobInfo(storeName, 1, 10).ToList(); Assert.That(jobs, Is.Not.Null); Assert.That(jobs, Has.Count.EqualTo(2)); jobs = client.GetJobInfo(storeName, 1, 1).ToList(); Assert.That(jobs, Is.Not.Null); Assert.That(jobs, Has.Count.EqualTo(1)); } [Test] public void TestQueryCommitPoint() { var client = GetClient(); var storeName = "QueryCommitPoint_" + DateTime.Now.Ticks; const string batch1 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource1> ."; const string batch2 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource2> ."; const string batch3 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource3> ."; // Prepare store with three consecutive commits client.CreateStore(storeName); var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = batch1}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = batch2}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = batch3}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); // Retrieve commit points - there should be one initial one plus one for each transaction we executed var commits = client.GetCommitPoints(storeName, 0, 10).ToList(); Assert.That(commits, Has.Count.EqualTo(4)); // Each commit added one match to this query, so each commit point we step back through should // return one less result row. for (int i = 0; i < 4; i++) { var resultsStream = client.ExecuteQuery(commits[i], "SELECT ?p WHERE { <http://example.org/resource> <http://example.org/property> ?p }"); var resultsDoc = XDocument.Load(resultsStream); Assert.That(resultsDoc.SparqlResultRows().ToList(), Has.Count.EqualTo(3-i)); } } const string Batch1 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource1> ."; const string Batch2 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource2> ."; const string Batch3 = @"<http://example.org/resource> <http://example.org/property> <http://example.org/resource3> ."; private static void PreloadStore(IBrightstarService client, string storeName, params string[] insertBatches) { foreach (var insertBatch in insertBatches) { var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = insertBatch}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); } } [Test] public void TestRevertCommit() { var client = GetClient(); var storeName = "QueryCommitPoint_" + DateTime.Now.Ticks; // Prepare store with three consecutive commits client.CreateStore(storeName); PreloadStore(client, storeName, Batch1, Batch2, Batch3); // Retrieve commit points - there should be one initial one plus one for each transaction we executed var commits = client.GetCommitPoints(storeName, 0, 10).ToList(); Assert.That(commits, Has.Count.EqualTo(4)); // Before the revert we should have the last of the three patterns in the store AssertTriplePatternInDefaultGraph(client, storeName, Batch3); // Attempt to revert to the last-but-one commit client.RevertToCommitPoint(storeName, commits[1]); // After the revert the last of the three patterns should no longer be in the store AssertTriplePatternNotInDefaultGraph(client, storeName, Batch3); // But the first and second of the three should AssertTriplePatternInDefaultGraph(client, storeName, Batch1); AssertTriplePatternInDefaultGraph(client, storeName, Batch2); } [Test] [Ignore("Need to fix this in embedded client first")] public void TestRepeatTransaction() { var client = GetClient(); var storeName = "RepeatTransaction_" + DateTime.Now.Ticks; client.CreateStore(storeName); PreloadStore(client, storeName, Batch1, Batch2, Batch3); // Retrieve commit points var commits = client.GetCommitPoints(storeName, 0, 10).ToList(); Assert.That(commits, Has.Count.EqualTo(4)); AssertTriplePatternInDefaultGraph(client, storeName, Batch3); // Reverting back to the point where we only had Batch1 client.RevertToCommitPoint(storeName, commits[2]); // Check the revert worked as expected AssertTriplePatternInDefaultGraph(client, storeName, Batch1); AssertTriplePatternNotInDefaultGraph(client, storeName, Batch3); AssertTriplePatternNotInDefaultGraph(client, storeName, Batch2); // Repeat the transaction that added batch3 var txn = client.GetTransaction(storeName, commits[0].JobId); Assert.That(txn, Is.Not.Null); var job = client.ReExecuteTransaction(storeName, txn); job = WaitForJob(job, client, storeName); Assert.That(job.JobCompletedOk, "Re-execute transaction failed: " + job.StatusMessage); // Check that after re-execution Batch3 is now in the store, but Batch2 still isn't AssertTriplePatternInDefaultGraph(client, storeName, Batch1); AssertTriplePatternInDefaultGraph(client, storeName, Batch3); AssertTriplePatternNotInDefaultGraph(client, storeName, Batch2); } [Test] public void TestListTransactionsAndGetTransaction() { var client = GetClient(); var storeName = "ListTransactions_" + DateTime.Now.Ticks; client.CreateStore(storeName); PreloadStore(client, storeName, Batch1, Batch2, Batch3); var transactions = client.GetTransactions(storeName, 0, 10).ToList(); Assert.That(transactions, Has.Count.EqualTo(3)); transactions = client.GetTransactions(storeName, 1, 10).ToList(); Assert.That(transactions, Has.Count.EqualTo(2)); transactions = client.GetTransactions(storeName, 1, 1).ToList(); Assert.That(transactions, Has.Count.EqualTo(1)); // Try using the API to get a single transaction var txn = client.GetTransaction(storeName, transactions[0].JobId); Assert.That(txn, Is.Not.Null); Assert.That(txn.Id, Is.EqualTo(transactions[0].Id)); txn = client.GetTransaction(storeName, Guid.NewGuid()); Assert.That(txn, Is.Null); } [Test] public void TestTransactionAddStatements() { var bc = GetClient(); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); const string triplesToAdd = @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2> ."; var jobInfo = bc.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = triplesToAdd}); Assert.IsNotNull(jobInfo); while (!jobInfo.JobCompletedOk && !jobInfo.JobCompletedWithErrors) { Thread.Sleep(50); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } AssertTriplePatternInDefaultGraph(bc, storeName, triplesToAdd); } [Test] public void TestTransactiondDeleteStatements() { var bc = GetClient(); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); const string triplesToAdd = @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2>."; var jobInfo = bc.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = triplesToAdd}); Assert.IsNotNull(jobInfo); while (!jobInfo.JobCompletedOk && !jobInfo.JobCompletedWithErrors) { Thread.Sleep(50); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } AssertTriplePatternInDefaultGraph(bc, storeName, triplesToAdd); const string deletePatterns = @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2>."; jobInfo = bc.ExecuteTransaction(storeName, new UpdateTransactionData{DeletePatterns = deletePatterns}); while (!jobInfo.JobCompletedOk && !jobInfo.JobCompletedWithErrors) { Thread.Sleep(50); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } AssertTriplePatternNotInDefaultGraph(bc, storeName, triplesToAdd); } [Test] public void TestSparqlQuery() { var bc = GetClient(); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); const string triplesToAdd = @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2>."; var jobInfo = bc.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = triplesToAdd}); Assert.IsNotNull(jobInfo); while (!jobInfo.JobCompletedOk && !jobInfo.JobCompletedWithErrors) { Thread.Sleep(50); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } //var triples = bc.GetStoreData(storeName); //var memoryStream = new MemoryStream(); //triples.CopyTo(memoryStream); //Assert.IsTrue(0 < memoryStream.Length); // do query var result = bc.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource13> ?p ?o }"); Assert.IsNotNull(result); } [Test] public void TestSparqlQueryWithDefaultGraph() { var client = GetClient(); var storeName = "SparqlQueryWithDefaultGraph_" + DateTime.Now.Ticks; client.CreateStore(storeName); var triplesToAdd = new StringBuilder(); triplesToAdd.AppendLine(@"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2>."); triplesToAdd.AppendLine( @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource3> <http://example.org/graph1> ."); var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = triplesToAdd.ToString()}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.IsNotNull(jobInfo); Assert.IsTrue(jobInfo.JobCompletedOk); // do query var resultStream = client.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource13> ?p ?o }", "http://example.org/graph1"); var result = XDocument.Load(resultStream); var rows = result.SparqlResultRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(new Uri("http://example.org/resource3"), rows[0].GetColumnValue("o")); // Do a query over the normal default graph resultStream = client.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource13> ?p ?o }"); result = XDocument.Load(resultStream); rows = result.SparqlResultRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(new Uri("http://example.org/resource2"), rows[0].GetColumnValue("o")); } [Test] public void TestSparqlQueryWithDefaultGraphs() { var client = GetClient(); var storeName = "SparqlQueryWithDefaultGraphs_" + DateTime.Now.Ticks; client.CreateStore(storeName); var triplesToAdd = new StringBuilder(); triplesToAdd.AppendLine(@"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2>."); triplesToAdd.AppendLine( @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource3> <http://example.org/graph1> ."); triplesToAdd.AppendLine( @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource4> <http://example.org/graph2> ."); var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = triplesToAdd.ToString()}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.IsNotNull(jobInfo); Assert.IsTrue(jobInfo.JobCompletedOk); // do query using graph1 and graph2 as the default var resultStream = client.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource13> ?p ?o }", new[] {"http://example.org/graph1", "http://example.org/graph2"}); var result = XDocument.Load(resultStream); var rows = result.SparqlResultRows().ToList(); Assert.AreEqual(2, rows.Count); var expected = new[] {new Uri("http://example.org/resource3"), new Uri("http://example.org/resource4")}; Assert.IsTrue(expected.Contains(rows[0].GetColumnValue("o"))); Assert.IsTrue(expected.Contains(rows[1].GetColumnValue("o"))); // Do a query over the normal default graph resultStream = client.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource13> ?p ?o }"); result = XDocument.Load(resultStream); rows = result.SparqlResultRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(new Uri("http://example.org/resource2"), rows[0].GetColumnValue("o")); } [Test] public void TestSparqlXDocumentExtensions() { var bc = GetClient(); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); const string triplesToAdd = @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2> . <http://example.org/resource14> <http://example.org/property1> ""30""^^<http://www.w3.org/2001/XMLSchema#integer> . "; var jobInfo = bc.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = triplesToAdd}); jobInfo = WaitForJob(jobInfo, bc, storeName); Assert.IsNotNull(jobInfo); Assert.IsTrue(jobInfo.JobCompletedOk); // var triples = bc.GetStoreData(storeName); //var memoryStream = new MemoryStream(); //triples.CopyTo(memoryStream); //Assert.IsTrue(0 < memoryStream.Length); // do query var result = bc.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource13> ?p ?o }"); var doc = XDocument.Load(result); var resultRows = doc.SparqlResultRows().ToList(); Assert.AreEqual(1, resultRows.Count()); foreach (var row in resultRows) { var p = row.GetColumnValue("p"); var o = row.GetColumnValue("o"); Assert.AreEqual("http://example.org/property", p.ToString()); Assert.AreEqual("http://example.org/resource2", o.ToString()); Assert.IsNull(row.GetColumnValue("z")); Assert.IsFalse(row.IsLiteral("p")); Assert.IsFalse(row.IsLiteral("o")); } result = bc.ExecuteQuery(storeName, "select ?p ?o where { <http://example.org/resource14> ?p ?o }"); doc = XDocument.Load(result); resultRows = doc.SparqlResultRows().ToList(); Assert.AreEqual(1, resultRows.Count()); foreach (var row in resultRows) { var p = row.GetColumnValue("p"); var o = row.GetColumnValue("o"); Assert.AreEqual("http://example.org/property1", p.ToString()); Assert.AreEqual(30, o); Assert.AreEqual("http://www.w3.org/2001/XMLSchema#integer", row.GetLiteralDatatype("o")); Assert.IsNull(row.GetLiteralDatatype("p")); Assert.IsNull(row.GetColumnValue("z")); Assert.IsFalse(row.IsLiteral("p")); Assert.IsTrue(row.IsLiteral("o")); Assert.IsInstanceOf(typeof(Int32), o); } } [Test] public void TestSparqlUpdate() { var client = GetClient(); var storeName = "SparqlUpdate_" + DateTime.Now.Ticks; const string initialTriples = @"<http://example.org/foo> <http://example.org/p> ""foo""."; const string updateExpression = @"DELETE { ?s ?p 'foo' } INSERT { ?s ?p 'bar' } WHERE { ?s ?p 'foo' }"; client.CreateStore(storeName); var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData=initialTriples}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); // Attempt update jobInfo = client.ExecuteUpdate(storeName, updateExpression); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.That(jobInfo.JobCompletedOk); // Verify results var resultsStream = client.ExecuteQuery(storeName, "SELECT ?v WHERE { <http://example.org/foo> <http://example.org/p> ?v }"); var resultsDoc = XDocument.Load(resultsStream); var resultsRows = resultsDoc.SparqlResultRows().ToList(); Assert.That(resultsRows, Has.Count.EqualTo(1)); var row = resultsRows[0]; var result = row.GetColumnValue("v"); Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<PlainLiteral>()); Assert.That((result as PlainLiteral).Value, Is.EqualTo("bar")); } [Test] public void TestPassingNullForData() { var bc = GetClient(); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); const string triplesToAdd = @"<http://example.org/resource13> <http://example.org/property> <http://example.org/resource2>."; var jobInfo = bc.ExecuteTransaction(storeName, new UpdateTransactionData { ExistencePreconditions = "", DeletePatterns = null, InsertData = triplesToAdd }); Assert.IsNotNull(jobInfo); while (!jobInfo.JobCompletedOk && !jobInfo.JobCompletedWithErrors) { Thread.Sleep(50); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } //var triples = bc.GetStoreData(storeName); //var memoryStream = new MemoryStream(); //triples.CopyTo(memoryStream); //memoryStream.Flush(); //Assert.IsTrue(0 < memoryStream.Length); } [Test] public void TestBadDataGetsUsefulErrorMessage() { try { var bc = GetClient(); var sid = Guid.NewGuid().ToString(); bc.CreateStore(sid); bc.CreateStore(sid); } catch (BrightstarClientException ex) { var detail = ex.Message; Assert.That(detail, Is.EqualTo("Store name conflicts with the name of an existing store.")); } } [Test] public void TestExportWhileWriting() { const int firstBatchSize = 50000; var storeName = Guid.NewGuid().ToString(); var client = GetClient(); client.CreateStore(storeName); var batch1 = MakeTriples(0, firstBatchSize); var batch2 = MakeTriples(firstBatchSize, firstBatchSize+1000); var batch3 = MakeTriples(firstBatchSize+1000, firstBatchSize+2000); var batch4 = MakeTriples(firstBatchSize+2000, firstBatchSize+3000); // Verify batch size var p = new NTriplesParser(); var counterSink = new CounterTripleSink(); p.Parse(new StringReader(batch1), counterSink, Constants.DefaultGraphUri); Assert.AreEqual(firstBatchSize, counterSink.Count); var jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData { ExistencePreconditions = String.Empty, DeletePatterns = String.Empty, InsertData = batch1 }); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.AreEqual(true, jobInfo.JobCompletedOk); // Second export with parallel store writes var exportJobInfo = client.StartExport(storeName, storeName + "_export.nt"); jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData { ExistencePreconditions = null, DeletePatterns = null, InsertData = batch2 }); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.AreEqual(true, jobInfo.JobCompletedOk); exportJobInfo = client.GetJobInfo(storeName, exportJobInfo.JobId); if (exportJobInfo.JobCompletedWithErrors) { Assert.Fail("Export job completed with errors: {0} : {1}", exportJobInfo.StatusMessage, exportJobInfo.ExceptionInfo); } if (exportJobInfo.JobCompletedOk) { Assert.Inconclusive("Export job completed before end of first concurrent import job."); } jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData= batch3}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.AreEqual(true, jobInfo.JobCompletedOk); jobInfo = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = batch4}); jobInfo = WaitForJob(jobInfo, client, storeName); Assert.AreEqual(true, jobInfo.JobCompletedOk); exportJobInfo = WaitForJob(exportJobInfo, client, storeName); Assert.That(exportJobInfo.JobCompletedOk); var exportFile = new FileInfo("c:\\brightstar\\import\\" + storeName + "_export.nt"); Assert.IsTrue(exportFile.Exists); var lineCount = File.ReadAllLines(exportFile.FullName).Count(x => !String.IsNullOrEmpty(x)); Assert.AreEqual(firstBatchSize, lineCount); } public class CounterTripleSink : ITripleSink { public int Count { get; private set; } #region Implementation of ITripleSink /// <summary> /// Handler method for an individual RDF statement /// </summary> /// <param name="subject">The statement subject resource URI</param> /// <param name="subjectIsBNode">True if the value of <paramref name="subject"/> is a BNode identifier</param> /// <param name="predicate">The predicate resource URI</param> /// <param name="predicateIsBNode">True if the value of <paramref name="predicate"/> is a BNode identifier.</param> /// <param name="obj">The object of the statement</param> /// <param name="objIsBNode">True if the value of <paramref name="obj"/> is a BNode identifier.</param> /// <param name="objIsLiteral">True if the value of <paramref name="obj"/> is a literal string</param> /// <param name="dataType">The datatype URI for the object literal or null if the object is not a literal</param> /// <param name="langCode">The language code for the object literal or null if the object is not a literal</param> /// <param name="graphUri">The graph URI for the statement</param> public void Triple(string subject, bool subjectIsBNode, string predicate, bool predicateIsBNode, string obj, bool objIsBNode, bool objIsLiteral, string dataType, string langCode, string graphUri) { Count++; } /// <summary> /// Method invoked to indicate that no more triples remain to be written to the sink. /// </summary> public void Close() { // No-op } #endregion } private static string MakeTriples(int startId, int endId) { var triples = new StringBuilder(); for(var i = startId; i < endId; i++ ) { triples.AppendFormat("<http://www.example.org/resource/{0}> <http://example.org/value> \"{0}\" .\n",i); } return triples.ToString(); } #if !PORTABLE // Won't work on portable as requires direct access to server import directory [Test] public void TestSpecialCharsInIdentities() { var importDir = Path.Combine(_storeLocation, "import"); if (!Directory.Exists(importDir)) { Directory.CreateDirectory(importDir); } var testTarget = new FileInfo(importDir + Path.DirectorySeparatorChar + "persondata_en_subset.nt"); if (!testTarget.Exists) { var testSource = new FileInfo("persondata_en_subset.nt"); if (!testSource.Exists) { Assert.Inconclusive("Could not locate test source file {0}. Test will not run", testSource.FullName); return; } testSource.CopyTo(importDir + Path.DirectorySeparatorChar + "persondata_en_subset.nt"); } var bc = BrightstarService.GetClient("type=rest;endpoint=http://localhost:8090/brightstar"); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); var jobInfo = bc.StartImport(storeName, "persondata_en_subset.nt", null); while (!(jobInfo.JobCompletedOk || jobInfo.JobCompletedWithErrors)) { Thread.Sleep(1000); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } Assert.IsTrue(jobInfo.JobCompletedOk, "Import job failed"); IDataObjectContext context = new EmbeddedDataObjectContext(new ConnectionString("type=embedded;storesDirectory=" + _storeLocation + "\\")); var store = context.OpenStore(storeName); var test = store.BindDataObjectsWithSparql("SELECT ?p WHERE {?p a <http://xmlns.com/foaf/0.1/Person>} LIMIT 30").ToList(); Assert.IsNotNull(test); foreach (var testDo in test) { Assert.IsNotNull(testDo); var propValues = testDo.GetPropertyValues("http://xmlns.com/foaf/0.1/name").OfType<PlainLiteral>(); Assert.IsNotNull(propValues); Assert.IsTrue(propValues.Any()); } } #endif [Test] public void TestConsolidateEmptyStore() { var storeName = "ConsolidateEmptyStore_" + DateTime.Now.Ticks; var client = GetClient(); client.CreateStore(storeName); var job = client.ConsolidateStore(storeName); job = WaitForJob(job, client, storeName); Assert.IsTrue(job.JobCompletedOk, "Job did not complete successfully: {0} : {1}", job.StatusMessage, job.ExceptionInfo); } private static IJobInfo WaitForJob(IJobInfo job, IBrightstarService client, string storeName) { var cycleCount = 0; while (!job.JobCompletedOk && !job.JobCompletedWithErrors && cycleCount < 100) { Thread.Sleep(500); cycleCount++; job = client.GetJobInfo(storeName, job.JobId); } if (!job.JobCompletedOk && !job.JobCompletedWithErrors) { Assert.Fail("Job did not complete in time."); } return job; } [Test] public void TestConsolidatePopulatedStore() { var storeName = "ConsolidatePopulatedStore_" + DateTime.Now.Ticks; var client = GetClient(); client.CreateStore(storeName); const string addSet1 = "<http://example.org/people/alice> <http://www.w3.org/2000/01/rdf-schema#label> \"Alice\"."; const string addSet2 = "<http://example.org/people/bob> <http://www.w3.org/2000/01/rdf-schema#label> \"Bob\"."; const string addSet3 = "<http://example.org/people/carol> <http://www.w3.org/2000/01/rdf-schema#label> \"Carol\"."; var result = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = addSet1}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); result = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData= addSet2}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); result = client.ExecuteTransaction(storeName, new UpdateTransactionData { InsertData = addSet3 }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); var job = client.ConsolidateStore(storeName); var cycleCount = 0; while (!job.JobCompletedOk && !job.JobCompletedWithErrors && cycleCount < 100) { Thread.Sleep(500); cycleCount++; job = client.GetJobInfo(storeName, job.JobId); } if (!job.JobCompletedOk && !job.JobCompletedWithErrors) { Assert.Fail("Job did not complete in time."); } Assert.IsTrue(job.JobCompletedOk, "Job did not complete successfully: {0} : {1}", job.StatusMessage, job.ExceptionInfo); } [Test] public void TestConsolidatePopulatedStoreAfterQuery() { var storeName = "ConsolidatePopulatedStore_" + DateTime.Now.Ticks; var client = GetClient(); client.CreateStore(storeName); const string addSet1 = "<http://example.org/people/alice> <http://www.w3.org/2000/01/rdf-schema#label> \"Alice\"."; const string addSet2 = "<http://example.org/people/bob> <http://www.w3.org/2000/01/rdf-schema#label> \"Bob\"."; const string addSet3 = "<http://example.org/people/carol> <http://www.w3.org/2000/01/rdf-schema#label> \"Carol\"."; var result = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = addSet1}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); result = client.ExecuteTransaction(storeName, new UpdateTransactionData { InsertData = addSet2 }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); result = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = addSet3}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); var resultsStream = client.ExecuteQuery(storeName, "SELECT * WHERE {?s ?p ?o}"); resultsStream.Close(); var job = client.ConsolidateStore(storeName); var cycleCount = 0; while (!job.JobCompletedOk && !job.JobCompletedWithErrors && cycleCount < 100) { Thread.Sleep(500); cycleCount++; job = client.GetJobInfo(storeName, job.JobId); } if (!job.JobCompletedOk && !job.JobCompletedWithErrors) { Assert.Fail("Job did not complete in time."); } Assert.IsTrue(job.JobCompletedOk, "Job did not complete successfully: {0} : {1}", job.StatusMessage, job.ExceptionInfo); } [Test] public void TestInsertQuadsIntoDefaultGraph() { var client = GetClient(); var storeName = "QuadsTransaction1_" + DateTime.Now.Ticks; client.CreateStore(storeName); const string txn1Adds = @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice"" <http://example.org/graphs/alice> . <http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"" ."; var result = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = txn1Adds}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInDefaultGraph(client, storeName, @"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"""); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice""", "http://example.org/graphs/alice"); } [Test] public void TestInsertQuadsIntoNonDefaultGraph() { var client = GetClient(); var storeName = "QuadsTransaction2_" + DateTime.Now.Ticks; client.CreateStore(storeName); const string txn1Adds = @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice"" <http://example.org/graphs/alice> . <http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"" ."; var result = client.ExecuteTransaction(storeName, new UpdateTransactionData { InsertData = txn1Adds, DefaultGraphUri = "http://example.org/graphs/bob" }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice""", "http://example.org/graphs/alice"); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob""", "http://example.org/graphs/bob"); } [Test] public void TestUpdateQuadsUsingDefaultGraph() { var client = GetClient(); var storeName = "QuadsTransaction3_" + DateTime.Now.Ticks; client.CreateStore(storeName); var txn1Adds = new StringBuilder(); txn1Adds.AppendLine( @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice"" <http://example.org/graphs/alice> ."); txn1Adds.AppendLine(@"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"" ."); var result = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = txn1Adds.ToString()}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInDefaultGraph(client, storeName, @"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"""); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice""", "http://example.org/graphs/alice"); var txn2Adds = new StringBuilder(); txn2Adds.AppendLine(@"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice Arnold"" <http://example.org/graphs/alice> ."); txn2Adds.AppendLine(@"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob Bobbins"" ."); result = client.ExecuteTransaction(storeName, new UpdateTransactionData { ExistencePreconditions = txn1Adds.ToString(), DeletePatterns = txn1Adds.ToString(), InsertData = txn2Adds.ToString() }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice Arnold""", "http://example.org/graphs/alice"); AssertTriplePatternInDefaultGraph(client, storeName, @"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob Bobbins"""); } [Test] public void TestUpdateQuadsUsingNonDefaultGraph() { var client = GetClient(); var storeName = "QuadsTransaction4_" + DateTime.Now.Ticks; client.CreateStore(storeName); const string txn1Adds = @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice"" <http://example.org/graphs/alice> . <http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"" ."; var result = client.ExecuteTransaction(storeName, new UpdateTransactionData { InsertData = txn1Adds, DefaultGraphUri = "http://example.org/graphs/bob" }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice""", "http://example.org/graphs/alice"); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob""", "http://example.org/graphs/bob"); const string txn2Adds = @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice Arnold"" <http://example.org/graphs/alice> . <http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob Bobbins"" ."; result = client.ExecuteTransaction(storeName, new UpdateTransactionData { ExistencePreconditions = txn1Adds, DeletePatterns = txn1Adds, InsertData = txn2Adds, DefaultGraphUri = "http://example.org/graphs/bob" }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/alice> <http://xmlns.com/foaf/0.1/name> ""Alice Arnold""", "http://example.org/graphs/alice"); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/people/bob> <http://xmlns.com/foaf/0.1/name> ""Bob Bobbins""", "http://example.org/graphs/bob"); } [Test] public void TestTransactionWithWildcardGraph() { var client = GetClient(); var storeName = "QuadsTransaction5_" + DateTime.Now.Ticks; client.CreateStore(storeName); var txn1Adds = new StringBuilder(); txn1Adds.AppendLine(@"<http://example.org/alice> <http://xmlns.com/foaf/0.1/name> ""Alice"" <http://example.org/graphs/alice> ."); txn1Adds.AppendLine( @"<http://example.org/alice> <http://xmlns.com/foaf/0.1/mbox> ""alice@example.org"" <http://example.org/graphs/alice> ."); txn1Adds.AppendLine(@"<http://example.org/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"" ."); txn1Adds.AppendLine(@"<http://example.org/bob> <http://xmlns.com/foaf/0.1/mbox> ""bob@example.org"" ."); var result = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData= txn1Adds.ToString()}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); AssertTriplePatternInGraph(client, storeName, @"<http://example.org/alice> <http://xmlns.com/foaf/0.1/name> ""Alice""", "http://example.org/graphs/alice"); AssertTriplePatternInDefaultGraph(client, storeName, @"<http://example.org/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"""); var txn2Deletes = new StringBuilder(); txn2Deletes.AppendFormat(@"<{0}> <http://xmlns.com/foaf/0.1/name> <{0}> <{0}> .", Constants.WildcardUri); result = client.ExecuteTransaction(storeName, new UpdateTransactionData {DeletePatterns = txn2Deletes.ToString()}); result = WaitForJob(result, client, storeName); Assert.That(result.JobCompletedOk); AssertTriplePatternNotInGraph(client, storeName, @"<http://example.org/alice> <http://xmlns.com/foaf/0.1/name> ""Alice""", "http://example.org/graphs/alice"); AssertTriplePatternNotInDefaultGraph(client, storeName, @"<http://example.org/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"""); } [Test] public void TestGenerateAndRetrieveStats() { var client = GetClient(); var storeName = "GenerateAndRetrieveStats_" + DateTime.Now.Ticks; client.CreateStore(storeName); var txn1Adds = new StringBuilder(); txn1Adds.AppendLine(@"<http://example.org/alice> <http://xmlns.com/foaf/0.1/name> ""Alice"" <http://example.org/graphs/alice> ."); txn1Adds.AppendLine( @"<http://example.org/alice> <http://xmlns.com/foaf/0.1/mbox> ""alice@example.org"" <http://example.org/graphs/alice> ."); txn1Adds.AppendLine(@"<http://example.org/bob> <http://xmlns.com/foaf/0.1/name> ""Bob"" ."); txn1Adds.AppendLine(@"<http://example.org/bob> <http://xmlns.com/foaf/0.1/mbox> ""bob@example.org"" ."); var result = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = txn1Adds.ToString()}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); var stats = client.GetStatistics(storeName); Assert.IsNull(stats); var job = client.UpdateStatistics(storeName); job = WaitForJob(job, client, storeName); Assert.IsTrue(job.JobCompletedOk); stats = client.GetStatistics(storeName); Assert.IsNotNull(stats); Assert.AreEqual(4, stats.TotalTripleCount); Assert.AreEqual(2, stats.PredicateTripleCounts.Count); var commitPoint = client.GetCommitPoint(storeName, stats.CommitTimestamp.AddSeconds(1.0)); // added a second to allow for timestamp rounding Assert.That(commitPoint, Is.Not.Null); Assert.AreEqual(commitPoint.Id, stats.CommitId); } [Test] public void TestCreateSnapshot() { var storeName = "CreateSnapshot_" + DateTime.Now.Ticks; var client = GetClient(); client.CreateStore(storeName); const string addSet1 = "<http://example.org/people/alice> <http://www.w3.org/2000/01/rdf-schema#label> \"Alice\"."; const string addSet2 = "<http://example.org/people/bob> <http://www.w3.org/2000/01/rdf-schema#label> \"Bob\"."; const string addSet3 = "<http://example.org/people/carol> <http://www.w3.org/2000/01/rdf-schema#label> \"Carol\"."; var result = client.ExecuteTransaction(storeName, new UpdateTransactionData {InsertData = addSet1}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); result = client.ExecuteTransaction(storeName, new UpdateTransactionData { InsertData = addSet2 }); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); result = client.ExecuteTransaction(storeName, new UpdateTransactionData{InsertData = addSet3}); result = WaitForJob(result, client, storeName); Assert.IsTrue(result.JobCompletedOk); var resultsStream = client.ExecuteQuery(storeName, "SELECT * WHERE {?s ?p ?o}"); resultsStream.Close(); var commitPoints = client.GetCommitPoints(storeName, 0, 2).ToList(); Assert.AreEqual(2, commitPoints.Count); // Append Only targets // Create from default (latest) commit var job = client.CreateSnapshot(storeName, storeName + "_snapshot1", PersistenceType.AppendOnly); job = WaitForJob(job, client, storeName); Assert.IsTrue(job.JobCompletedOk, "Job failed: " + job.StatusMessage + " - " + job.ExceptionInfo); resultsStream = client.ExecuteQuery(storeName + "_snapshot1", "SELECT * WHERE { ?s ?p ?o }"); var resultsDoc = XDocument.Load(resultsStream); Assert.AreEqual(3, resultsDoc.SparqlResultRows().Count()); // Create from specific commit point job = client.CreateSnapshot(storeName, storeName + "_snapshot2", PersistenceType.AppendOnly, commitPoints[1]); job = WaitForJob(job, client, storeName); Assert.IsTrue(job.JobCompletedOk); resultsStream = client.ExecuteQuery(storeName + "_snapshot2", "SELECT * WHERE {?s ?p ?o}"); resultsDoc = XDocument.Load(resultsStream); Assert.AreEqual(2, resultsDoc.SparqlResultRows().Count()); // Rewrite targets // Create from default (latest) commit job = client.CreateSnapshot(storeName, storeName + "_snapshot3", PersistenceType.Rewrite); job = WaitForJob(job, client, storeName); Assert.IsTrue(job.JobCompletedOk); resultsStream = client.ExecuteQuery(storeName + "_snapshot3", "SELECT * WHERE { ?s ?p ?o }"); resultsDoc = XDocument.Load(resultsStream); Assert.AreEqual(3, resultsDoc.SparqlResultRows().Count()); // Create from specific commit point job = client.CreateSnapshot(storeName, storeName + "_snapshot4", PersistenceType.Rewrite, commitPoints[1]); job = WaitForJob(job, client, storeName); Assert.IsTrue(job.JobCompletedOk); resultsStream = client.ExecuteQuery(storeName + "_snapshot4", "SELECT * WHERE {?s ?p ?o}"); resultsDoc = XDocument.Load(resultsStream); Assert.AreEqual(2, resultsDoc.SparqlResultRows().Count()); } [Test] public void TestListCommitPoints() { var storeName = "ListCommitPoints_" + DateTime.Now.Ticks; var client = GetClient(); client.CreateStore(storeName, PersistenceType.AppendOnly); var initialCommitPoints = client.GetCommitPoints(storeName, 0, 10).ToList(); Assert.That(initialCommitPoints.Count, Is.EqualTo(1)); Assert.That(initialCommitPoints[0].StoreName, Is.EqualTo(storeName)); Assert.That(initialCommitPoints[0], Has.Property("Id")); Assert.That(initialCommitPoints[0], Has.Property("CommitTime")); Assert.That(initialCommitPoints[0], Has.Property("JobId")); var job = client.ExecuteTransaction(storeName, new UpdateTransactionData { InsertData = "<http://example.com/s> <http://example.com/p> <http://example.com/o>" }); job = WaitForJob(job, client, storeName); Assert.That(job.JobCompletedOk); var updatedCommitPoints = client.GetCommitPoints(storeName, 0, 10).ToList(); Assert.That(updatedCommitPoints.Count, Is.EqualTo(2)); Assert.That(updatedCommitPoints[1].Id, Is.EqualTo(initialCommitPoints[0].Id)); updatedCommitPoints = client.GetCommitPoints(storeName, 0, 1).ToList(); Assert.That(updatedCommitPoints, Has.Count.EqualTo(1)); updatedCommitPoints = client.GetCommitPoints( storeName, // Need to allow for resolution of the date/time format DateTime.UtcNow.Add(TimeSpan.FromSeconds(1.0)), DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)), 0, 10) .ToList(); Assert.That(updatedCommitPoints, Has.Count.EqualTo(2)); } private static void AssertTriplePatternInGraph(IBrightstarService client, string storeName, string triplePattern, string graphUri) { var sparql = "ASK { GRAPH <" + graphUri + "> {" + triplePattern + "}}"; var resultsDoc = XDocument.Load(client.ExecuteQuery(storeName, sparql)); Assert.IsTrue(resultsDoc.SparqlBooleanResult()); } private static void AssertTriplePatternInDefaultGraph(IBrightstarService client, string storeName, string triplePattern) { var sparql = "ASK {{" + triplePattern + "}}"; var resultsDoc = XDocument.Load(client.ExecuteQuery(storeName, sparql)); Assert.IsTrue(resultsDoc.SparqlBooleanResult()); } private static void AssertTriplePatternNotInGraph(IBrightstarService client, string storeName, string triplePattern, string graphUri) { var sparql = "ASK { GRAPH <" + graphUri + "> {" + triplePattern + "}}"; var resultsDoc = XDocument.Load(client.ExecuteQuery(storeName, sparql)); Assert.IsFalse(resultsDoc.SparqlBooleanResult()); } private static void AssertTriplePatternNotInDefaultGraph(IBrightstarService client, string storeName, string triplePattern) { var sparql = "ASK {{" + triplePattern + "}}"; var resultsDoc = XDocument.Load(client.ExecuteQuery(storeName, sparql)); Assert.IsFalse(resultsDoc.SparqlBooleanResult()); } // private IJobInfo PollToCompletion(IBrightstarService client, string storeName, IJobInfo job) // { // while (true) // { // if (job.JobCompletedOk || job.JobCompletedWithErrors) return job; //#if PORTABLE // var l = new ManualResetEvent(false); // l.WaitOne(250); //#else // Thread.CurrentThread.Sleep(250); //#endif // job = client.GetJobInfo(storeName, job.JobId); // } // } } }
48.119216
1,201
0.581513
[ "MIT" ]
rajcybage/BrightstarDB
src/core/BrightstarDB.Server.IntegrationTests/ClientTests.cs
61,354
C#
namespace EA.Weee.Core.Tests.Unit.Helpers { public class SimpleObject { public string MyString { get; set; } } }
16.75
44
0.626866
[ "Unlicense" ]
DEFRA/prsd-weee
src/EA.Weee.Core.Tests.Unit/Helpers/SimpleObject.cs
136
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace ProgressBarTest { public partial class App : Application { public App () { this.Startup += this.Application_Startup; this.Exit += this.Application_Exit; this.UnhandledException += this.Application_UnhandledException; InitializeComponent (); } private void Application_Startup (object sender, StartupEventArgs e) { this.RootVisual = new Page (); } private void Application_Exit (object sender, EventArgs e) { } private void Application_UnhandledException (object sender, ApplicationUnhandledExceptionEventArgs e) { // If the app is running outside of the debugger then report the exception using // the browser's exception mechanism. On IE this will display it a yellow alert // icon in the status bar and Firefox will display a script error. if (!System.Diagnostics.Debugger.IsAttached) { // NOTE: This will allow the application to continue running after an exception has been thrown // but not handled. // For production applications this error handling should be replaced with something that will // report the error to the website and stop the application. e.Handled = true; Deployment.Current.Dispatcher.BeginInvoke (delegate { ReportErrorToDOM (e); }); } } private void ReportErrorToDOM (ApplicationUnhandledExceptionEventArgs e) { try { string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; errorMsg = errorMsg.Replace ('"', '\'').Replace ("\r\n", @"\n"); System.Windows.Browser.HtmlPage.Window.Eval ("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");"); } catch (Exception) { } } } }
31.238095
136
0.735264
[ "MIT" ]
ABEMBARKA/monoUI
MoonAtkBridge/tests/assets/ProgressBarTest/App.xaml.cs
1,970
C#
using System; using System.Collections.Generic; using System.Text; using UnityEngine; public interface IAssetFactory { GameObject LoadSoldier(string name); GameObject LoadEnemy(string name); GameObject LoadWeapon(string name); GameObject LoadEffect(string name); AudioClip LoadAudioClip(string name); Sprite LoadSprite(string name); }
21.352941
41
0.763085
[ "MIT" ]
WithoutUmbrella-Boy/Design-patterns-in-game-development
RedAlertProject/Assets/Scripts/Factory/Asset/IAssetFactory.cs
365
C#
using System.Threading; using System.Threading.Tasks; using AgreementService; using LBHTenancyAPI.Infrastructure.V1.UseCase.Execution; namespace LBHTenancyAPI.Gateways.V1.Arrears { public interface IArrearsAgreementGateway { Task<IExecuteWrapper<ArrearsAgreementResponse>> CreateArrearsAgreementAsync(ArrearsAgreementRequest request, CancellationToken cancellationToken); } }
30.538462
154
0.826196
[ "MIT" ]
cob16/LBHTenancyAPI
LBHTenancyAPI/Gateways/V1/Arrears/IArrearsAgreementGateway.cs
397
C#
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Pipeline.Filters { using System; using System.Threading.Tasks; using Events; using Transports; using Util; /// <summary> /// In the case of an exception, the message is moved to the destination transport. If the receive had not yet been /// faulted, a fault is generated. /// </summary> public class MoveExceptionToTransportFilter : IFilter<ExceptionReceiveContext> { readonly Uri _destinationAddress; readonly Func<Task<ISendTransport>> _getDestinationTransport; readonly IPublishEndpointProvider _publishEndpoint; public MoveExceptionToTransportFilter(IPublishEndpointProvider publishEndpoint, Uri destinationAddress, Func<Task<ISendTransport>> getDestinationTransport) { _getDestinationTransport = getDestinationTransport; _publishEndpoint = publishEndpoint; _destinationAddress = destinationAddress; } void IProbeSite.Probe(ProbeContext context) { ProbeContext scope = context.CreateFilterScope("moveFault"); scope.Add("destinationAddress", _destinationAddress); } async Task IFilter<ExceptionReceiveContext>.Send(ExceptionReceiveContext context, IPipe<ExceptionReceiveContext> next) { ISendTransport transport = await _getDestinationTransport(); IPipe<SendContext> pipe = Pipe.Execute<SendContext>(sendContext => { sendContext.Headers.Set(MessageHeaders.Reason, "fault"); Exception exception = context.Exception.GetBaseException(); sendContext.Headers.Set(MessageHeaders.FaultMessage, exception.Message); sendContext.Headers.Set(MessageHeaders.FaultStackTrace, ExceptionUtil.GetStackTrace(exception)); sendContext.SetHostHeaders(); }); if (!context.IsFaulted) GenerateFault(context); await transport.Move(context, pipe); await next.Send(context); } void GenerateFault(ExceptionReceiveContext context) { Guid? faultedMessageId = context.TransportHeaders.Get("MessageId", default(Guid?)); ReceiveFault fault = new ReceiveFaultEvent(HostMetadataCache.Host, context.Exception, context.ContentType.MediaType, faultedMessageId); var publishEndpoint = _publishEndpoint.CreatePublishEndpoint(context.InputAddress); var publishTask = publishEndpoint.Publish(fault, context.CancellationToken); context.AddPendingTask(publishTask); context.AddPendingTask(context.NotifyFaulted(context.Exception)); } } }
40.244186
148
0.670615
[ "Apache-2.0" ]
lsfera/MassTransit
src/MassTransit/Pipeline/Filters/MoveExceptionToTransportFilter.cs
3,461
C#
using System; namespace Quartz { internal sealed class TriggerConfigurator : ITriggerConfigurator { private readonly TriggerBuilder triggerBuilder = new TriggerBuilder(); public ITriggerConfigurator WithIdentity(string name) { triggerBuilder.WithIdentity(name); return this; } public ITriggerConfigurator WithIdentity(string name, string @group) { triggerBuilder.WithIdentity(name, @group); return this; } public ITriggerConfigurator WithIdentity(TriggerKey key) { triggerBuilder.WithIdentity(key); return this; } public ITriggerConfigurator WithDescription(string? description) { triggerBuilder.WithDescription(description); return this; } public ITriggerConfigurator WithPriority(int priority) { triggerBuilder.WithPriority(priority); return this; } public ITriggerConfigurator ModifiedByCalendar(string? calendarName) { triggerBuilder.ModifiedByCalendar(calendarName); return this; } public ITriggerConfigurator StartAt(DateTimeOffset startTimeUtc) { triggerBuilder.StartAt(startTimeUtc); return this; } public ITriggerConfigurator StartNow() { triggerBuilder.StartNow(); return this; } public ITriggerConfigurator EndAt(DateTimeOffset? endTimeUtc) { triggerBuilder.EndAt(endTimeUtc); return this; } public ITriggerConfigurator WithSchedule(IScheduleBuilder scheduleBuilder) { triggerBuilder.WithSchedule(scheduleBuilder); return this; } public ITriggerConfigurator ForJob(JobKey jobKey) { triggerBuilder.ForJob(jobKey); return this; } public ITriggerConfigurator ForJob(string jobName) { triggerBuilder.ForJob(jobName); return this; } public ITriggerConfigurator ForJob(string jobName, string jobGroup) { triggerBuilder.ForJob(jobName, jobGroup); return this; } public ITriggerConfigurator ForJob(IJobDetail jobDetail) { triggerBuilder.ForJob(jobDetail); return this; } public ITriggerConfigurator UsingJobData(JobDataMap newJobDataMap) { triggerBuilder.UsingJobData(newJobDataMap); return this; } public ITriggerConfigurator UsingJobData(string key, string value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, int value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, long value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, float value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, double value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, decimal value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, bool value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, Guid value) { triggerBuilder.UsingJobData(key, value); return this; } public ITriggerConfigurator UsingJobData(string key, char value) { triggerBuilder.UsingJobData(key, value); return this; } internal ITrigger Build() => triggerBuilder.Build(); } }
27.6
82
0.593268
[ "Apache-2.0" ]
BearerPipelineTest/quartznet
src/Quartz.Extensions.DependencyInjection/TriggerConfigurator.cs
4,278
C#
// Copyright (c) 2015 manu-silicon // This file is distributed under the MIT License. See LICENSE.md for details. namespace WCL.Enums { /// <summary> /// Constants used to control how a window is shown. /// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx for more details. /// </summary> public enum ShowWindowCommands { /// <summary> /// Hides the window and activates another window. /// </summary> Hide = 0, /// <summary> /// Activates and displays a window. If the window is minimized or /// maximized, the system restores it to its original size and position. /// An application should specify this flag when displaying the window /// for the first time. /// </summary> Normal = 1, /// <summary> /// Activates the window and displays it as a minimized window. /// </summary> ShowMinimized = 2, /// <summary> /// Activates the window and displays it as a maximized window. /// </summary> Maximize = 3, ShowMaximized = 3, /// <summary> /// Displays a window in its most recent size and position. This value /// is similar to <see cref="Win32.ShowWindowCommand.Normal"/>, except /// the window is not activated. /// </summary> ShowNoActivate = 4, /// <summary> /// Activates the window and displays it in its current size and position. /// </summary> Show = 5, /// <summary> /// Minimizes the specified window and activates the next top-level /// window in the Z order. /// </summary> Minimize = 6, /// <summary> /// Displays the window as a minimized window. This value is similar to /// <see cref="Win32.ShowWindowCommand.ShowMinimized"/>, except the /// window is not activated. /// </summary> ShowMinNoActive = 7, /// <summary> /// Displays the window in its current size and position. This value is /// similar to <see cref="Win32.ShowWindowCommand.Show"/>, except the /// window is not activated. /// </summary> ShowNA = 8, /// <summary> /// Activates and displays the window. If the window is minimized or /// maximized, the system restores it to its original size and position. /// An application should specify this flag when restoring a minimized window. /// </summary> Restore = 9, /// <summary> /// Sets the show state based on the SW_* value specified in the /// STARTUPINFO structure passed to the CreateProcess function by the /// program that started the application. /// </summary> ShowDefault = 10, /// <summary> /// <b>Windows 2000/XP:</b> Minimizes a window, even if the thread /// that owns the window is not responding. This flag should only be /// used when minimizing windows from a different thread. /// </summary> ForceMinimize = 11 } }
31.377778
107
0.654037
[ "MIT" ]
manu-silicon/wcl
Sources/enums/ShowWindowCommands.cs
2,826
C#
using System; using System.Net; namespace Roadie.Dlna.Server { internal sealed class UpnpDevice { public readonly IPAddress Address; public readonly Uri Descriptor; public readonly string Type; public readonly string USN; public readonly Guid UUID; public UpnpDevice(Guid uuid, string type, Uri descriptor, IPAddress address) { UUID = uuid; Type = type; Descriptor = descriptor; Address = address; if (Type.StartsWith("uuid:", StringComparison.Ordinal)) { USN = Type; } else { USN = $"uuid:{UUID}::{Type}"; } } } }
21.111111
67
0.509211
[ "MIT" ]
sphildreth/roadie
Roadie.Dlna/Server/Types/UpnpDevice.cs
762
C#
using System; using System.IO.Abstractions; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; using Mt.MediaFiles.AppEngine.Cataloging; using Mt.MediaFiles.AppEngine.Video.Tasks; using Mt.MediaFiles.ClientApp.Cli.Core; namespace Mt.MediaFiles.ClientApp.Cli.Commands { /// <summary> /// Walks through the files starting from the current directory and updates the items. /// For now used to retrieve video imprints /// </summary> [Command("update", Description = "Updates information about files starting from the current directory.")] [ExperimentalCommand] internal class CommandUpdate { public async Task<int> OnExecuteAsync( IShellAppContext shellAppContext, IFileSystem fileSystem, ICatalogTaskUpdateVideoImprintsFactory updateVideoImprintsFactory ) { var currentDirectory = fileSystem.Directory.GetCurrentDirectory(); var catalogItem = await CatalogItemUtils.FindItemByFsPathAsync( shellAppContext.Catalog, currentDirectory ); if (catalogItem == null) throw new InvalidOperationException("Cannot find the current directory in the catalog."); var task = updateVideoImprintsFactory.Create(catalogItem); await shellAppContext.Catalog.ExecuteTaskAsync(task); return Program.CommandExitResult; } } }
32.878049
107
0.747033
[ "MIT" ]
mtebenev/mediafiles
ClientApp.Cli/Commands/CommandUpdate.cs
1,348
C#
using Newtonsoft.Json.Linq; using Skybrud.Essentials.Json.Extensions; using Skybrud.Social.GitHub.Extensions; using Skybrud.Social.GitHub.Models.Common; namespace Skybrud.Social.GitHub.Models.Teams { /// <summary> /// Class representing a GitHub team. /// </summary> public class GitHubTeamItem : GitHubObject { #region Properties /// <summary> /// Gets the name of the team. /// </summary> public string Name { get; } /// <summary> /// Gets the ID of the team. /// </summary> public int Id { get; } /// <summary> /// Gets the node ID of the team. /// </summary> public string NodeId { get; } /// <summary> /// Gets the slug of the team. /// </summary> public string Slug { get; } /// <summary> /// Gets the description of the team. /// </summary> public string Description { get; } /// <summary> /// Gets the privacy setting of the team. /// </summary> public GitHubTeamPrivacy Privacy { get; } /// <summary> /// Gets the default permission of the team. /// </summary> public GitHubPermissionLevel Permission { get; } #endregion #region Constructors /// <summary> /// Initializes a new instance from the specified <paramref name="json"/>. /// </summary> /// <param name="json">The instance of <see cref="JObject"/> representing the team.</param> protected GitHubTeamItem(JObject json) : base(json) { Name = json.GetString("name"); Id = json.GetInt32("id"); NodeId = json.GetString("node_id"); Slug = json.GetString("slug"); Description = json.GetString("description"); Privacy = json.GetEnumWithFallbacks<GitHubTeamPrivacy>("privacy"); // TODO: Add support for the "url" property // TODO: Add support for the "html_url" property // TODO: Add support for the "members_url" property // TODO: Add support for the "repositories_url" property // TODO: Add support for the "url" property Permission = json.GetEnumWithFallbacks<GitHubPermissionLevel>("permission"); // TODO: Add support for the "parent" property } #endregion #region Static methods /// <summary> /// Parses the specified <paramref name="json"/> into an instance of <see cref="GitHubTeamItem"/>. /// </summary> /// <param name="json">The instance of <see cref="JObject"/> to be parsed.</param> /// <returns>An instance of <see cref="GitHubTeamItem"/>.</returns> public static GitHubTeamItem Parse(JObject json) { return json == null ? null : new GitHubTeamItem(json); } #endregion } }
32.175824
106
0.568306
[ "MIT" ]
abjerner/Skybrud.Social.GitHub
src/Skybrud.Social.GitHub/Models/Teams/GitHubTeamItem.cs
2,930
C#
// Developed by Softeq Development Corporation // http://www.softeq.com using Softeq.XToolkit.RemoteData; using Softeq.XToolkit.RemoteData.HttpClient; namespace Softeq.XToolkit.Chat.HttpClient.Requests { internal class GetMembersRequest : BaseRestRequest { public GetMembersRequest( string apiUrl, string nameFilter, int pageNumber, int pageSize) { var queryParams = new QueryStringBuilder() .AddParam("pageNumber", pageNumber.ToString()) .AddParam("pageSize", pageSize.ToString()) .AddParam("nameFilter", nameFilter) .Build(); EndpointUrl = $"{apiUrl}/member{queryParams}"; } public override string EndpointUrl { get; } public override bool UseOriginalEndpoint => true; } }
28.933333
62
0.614055
[ "MIT" ]
Softeq/XToolkit.Chat
Softeq.XToolkit.Chat.HttpClient/Requests/GetMembersRequest.cs
870
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Windows.Media; namespace Microsoft.Maui.Graphics.Xaml { public static class XamlGraphicsExtensions { public static System.Windows.Media.Color AsWpfColor(this Color target) { return System.Windows.Media.Color.FromArgb( (byte) (255 * target.Alpha), (byte) (255 * target.Red), (byte) (255 * target.Green), (byte) (255 * target.Blue)); } public static PointF AsPointF(this global::System.Windows.Point point) { return new PointF((float) point.X, (float) point.Y); } public static global::System.Windows.Point AsPoint(this PointF target) { return new global::System.Windows.Point(target.X, target.Y); } public static global::System.Windows.Point AsPoint(this PointF target, float ppu) { return new global::System.Windows.Point(target.X * ppu, target.Y * ppu); } [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public static PathGeometry AsPathGeometry(this PathF target, float scale = 1) { var geometry = new PathGeometry(); PathFigure figure = null; var pointIndex = 0; var arcAngleIndex = 0; var arcClockwiseIndex = 0; foreach (var type in target.SegmentTypes) { if (type == PathOperation.Move) { figure = new PathFigure(); geometry.Figures.Add(figure); figure.StartPoint = target[pointIndex++].AsPoint(scale); } else if (type == PathOperation.Line) { var lineSegment = new LineSegment {Point = target[pointIndex++].AsPoint(scale)}; figure.Segments.Add(lineSegment); } else if (type == PathOperation.Quad) { var quadSegment = new QuadraticBezierSegment { Point1 = target[pointIndex++].AsPoint(scale), Point2 = target[pointIndex++].AsPoint(scale) }; figure.Segments.Add(quadSegment); } else if (type == PathOperation.Cubic) { var cubicSegment = new BezierSegment() { Point1 = target[pointIndex++].AsPoint(scale), Point2 = target[pointIndex++].AsPoint(scale), Point3 = target[pointIndex++].AsPoint(scale), }; figure.Segments.Add(cubicSegment); } else if (type == PathOperation.Arc) { var topLeft = target[pointIndex++]; var bottomRight = target[pointIndex++]; var startAngle = target.GetArcAngle(arcAngleIndex++); var endAngle = target.GetArcAngle(arcAngleIndex++); var clockwise = target.GetArcClockwise(arcClockwiseIndex++); while (startAngle < 0) { startAngle += 360; } while (endAngle < 0) { endAngle += 360; } var sweep = Geometry.GetSweep(startAngle, endAngle, clockwise); var absSweep = Math.Abs(sweep); var rectX = topLeft.X * scale; var rectY = topLeft.Y * scale; var rectWidth = bottomRight.X * scale - topLeft.X * scale; var rectHeight = bottomRight.Y * scale - topLeft.Y * scale; var startPoint = Geometry.EllipseAngleToPoint(rectX, rectY, rectWidth, rectHeight, -startAngle); var endPoint = Geometry.EllipseAngleToPoint(rectX, rectY, rectWidth, rectHeight, -endAngle); if (figure == null) { figure = new PathFigure(); geometry.Figures.Add(figure); figure.StartPoint = startPoint.AsPoint(); } else { var lineSegment = new LineSegment() { Point = startPoint.AsPoint() }; figure.Segments.Add(lineSegment); } var arcSegment = new ArcSegment() { Point = new global::System.Windows.Point(endPoint.X, endPoint.Y), Size = new global::System.Windows.Size(rectWidth / 2, rectHeight / 2), SweepDirection = clockwise ? SweepDirection.Clockwise : SweepDirection.Counterclockwise, IsLargeArc = absSweep >= 180, }; figure.Segments.Add(arcSegment); } else if (type == PathOperation.Close) { figure.IsClosed = true; } } return geometry; } public static Transform AsTransform(this in Matrix3x2 transform) { if (transform.IsIdentity) { return Transform.Identity; } return new MatrixTransform(transform.M11, transform.M12, transform.M21, transform.M22, transform.M31, transform.M32); } } }
28.288591
120
0.659075
[ "MIT" ]
Mohsens22/Microsoft.Maui.Graphics
src/Microsoft.Maui.Graphics.Xaml.WPF/XamlGraphicsExtensions.cs
4,215
C#
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Utf8Json.Internal; namespace Utf8Json.Resolvers { public sealed partial class BuiltinResolver : IFormatterResolver { public static readonly BuiltinResolver Instance = new BuiltinResolver(); private BuiltinResolver() { } #if CSHARP_8_OR_NEWER public IJsonFormatter<T>? GetFormatter<T>() #else public IJsonFormatter<T> GetFormatter<T>() #endif { return FormatterCache<T>.Formatter; } public IntPtr GetSerializeStatic<T>() { return FormatterCache<T>.SerializeFunctionPointer; } public IntPtr GetDeserializeStatic<T>() { return FormatterCache<T>.DeserializeFunctionPointer; } public IntPtr GetCalcByteLengthForSerialization<T>() { return FormatterCache<T>.CalcByteLengthForSerializationFunctionPointer; } public IntPtr GetSerializeSpan<T>() { return FormatterCache<T>.SerializeSpanFunctionPointer; } public IJsonFormatter[] CollectCurrentRegisteredFormatters() { return formattersCache.ToArray(); } public IJsonFormatter #if CSHARP_8_OR_NEWER ? #endif GetFormatter(Type targetType) { formattersCache.TryGetValue(targetType, out var answer); return answer; } private readonly ThreadSafeTypeKeyReferenceHashTable<IJsonFormatter> formattersCache = BuiltinResolverGetFormatterHelper.GetFormatterCache(); private static class FormatterCache<T> { public static readonly IJsonFormatter<T> #if CSHARP_8_OR_NEWER ? #endif Formatter; public static readonly IntPtr SerializeFunctionPointer; public static readonly IntPtr DeserializeFunctionPointer; public static readonly IntPtr CalcByteLengthForSerializationFunctionPointer; public static readonly IntPtr SerializeSpanFunctionPointer; static FormatterCache() { (SerializeFunctionPointer, DeserializeFunctionPointer, CalcByteLengthForSerializationFunctionPointer, SerializeSpanFunctionPointer) = BuiltinResolverGetFormatterHelper.GetFunctionPointers(typeof(T)); BuiltinResolverGetFormatterHelper.GetFormatterCache().TryGetValue(typeof(T), out var formatter); Formatter = formatter as IJsonFormatter<T>; } } } }
32.823529
150
0.63871
[ "MIT" ]
pCYSl5EDgo/Utf8JsonV2
Utf8Json.UnityClient/Assets/Scripts/Utf8Json/Resolvers/BuiltinResolver.cs
2,792
C#
using UnityEngine; public interface ICreepSender { void CreepSent(GameObject obj); }
13
35
0.758242
[ "MIT" ]
ddark1990/3DMultiplayerMobileLineTowerDefense
Assets/_3DMultiplayerTowerDefense/_Scripts/Interfaces/ICreepSender.cs
93
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using UnityEditor.Rendering; using UnityEngine; using UnityEngine.Rendering; using UnityEditor.ShaderGraph.Internal; using UnityEditor.Graphing; namespace UnityEditor.ShaderGraph.Serialization { static class MultiJsonInternal { #region Unknown Data Handling public class UnknownJsonObject : JsonObject { public string typeInfo; public string jsonData; public JsonData<JsonObject> castedObject; public UnknownJsonObject(string typeInfo) { this.typeInfo = typeInfo; } public override void Deserailize(string typeInfo, string jsonData) { this.jsonData = jsonData; } public override string Serialize() { return jsonData; } public override void OnAfterDeserialize(string json) { if (castedObject.value != null) { Enqueue(castedObject, json.Trim()); } } public override void OnAfterMultiDeserialize(string json) { if (castedObject.value == null) { //Never got casted so nothing ever reffed this object //likely that some other unknown json object had a ref //to this thing. Need to include it in the serialization //step of the object still. if (jsonBlobs.TryGetValue(currentRoot.objectId, out var blobs)) { blobs[objectId] = jsonData.Trim(); } else { var lookup = new Dictionary<string, string>(); lookup[objectId] = jsonData.Trim(); jsonBlobs.Add(currentRoot.objectId, lookup); } } } public override T CastTo<T>() { if (castedObject.value != null) return castedObject.value.CastTo<T>(); Type t = typeof(T); if (t == typeof(AbstractMaterialNode) || t.IsSubclassOf(typeof(AbstractMaterialNode))) { UnknownNodeType unt = new UnknownNodeType(jsonData); valueMap[objectId] = unt; s_ObjectIdField.SetValue(unt, objectId); castedObject = unt; return unt.CastTo<T>(); } else if (t == typeof(Target) || t.IsSubclassOf(typeof(Target))) { UnknownTargetType utt = new UnknownTargetType(typeInfo, jsonData); valueMap[objectId] = utt; s_ObjectIdField.SetValue(utt, objectId); castedObject = utt; return utt.CastTo<T>(); } else if (t == typeof(SubTarget) || t.IsSubclassOf(typeof(SubTarget))) { UnknownSubTargetType ustt = new UnknownSubTargetType(typeInfo, jsonData); valueMap[objectId] = ustt; s_ObjectIdField.SetValue(ustt, objectId); castedObject = ustt; return ustt.CastTo<T>(); } else if (t == typeof(ShaderInput) || t.IsSubclassOf(typeof(ShaderInput))) { UnknownShaderPropertyType usp = new UnknownShaderPropertyType(typeInfo, jsonData); valueMap[objectId] = usp; s_ObjectIdField.SetValue(usp, objectId); castedObject = usp; return usp.CastTo<T>(); } else if (t == typeof(MaterialSlot) || t.IsSubclassOf(typeof(MaterialSlot))) { UnknownMaterialSlotType umst = new UnknownMaterialSlotType(typeInfo, jsonData); valueMap[objectId] = umst; s_ObjectIdField.SetValue(umst, objectId); castedObject = umst; return umst.CastTo<T>(); } else { Debug.LogError($"Unable to evaluate type {typeInfo} : {jsonData}"); } return null; } } public class UnknownTargetType : Target { public string jsonData; public UnknownTargetType() : base() { isHidden = true; } private List<BlockFieldDescriptor> m_activeBlocks = null; public UnknownTargetType(string displayName, string jsonData) { var split = displayName.Split('.'); var last = split[split.Length - 1]; this.displayName = last.Replace("Target", "") + " (Unknown)"; isHidden = false; this.jsonData = jsonData; } public override void Deserailize(string typeInfo, string jsonData) { this.jsonData = jsonData; base.Deserailize(typeInfo, jsonData); } public override string Serialize() { return jsonData.Trim(); } //When we first call GetActiveBlocks, we assume any unknown blockfielddescriptors are owned by this target public override void GetActiveBlocks(ref TargetActiveBlockContext context) { if (m_activeBlocks == null) { m_activeBlocks = new List<BlockFieldDescriptor>(); foreach (var cur in context.currentBlocks) { if (cur.isUnknown && !string.IsNullOrEmpty(cur.displayName)) { m_activeBlocks.Add(cur); } } } foreach (var block in m_activeBlocks) { context.AddBlock(block); } } public override void GetFields(ref TargetFieldContext context) { } public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action<string> registerUndo) { context.AddHelpBox(MessageType.Warning, "Cannot find the code for this Target, a package may be missing."); } public override bool IsActive() => false; public override void Setup(ref TargetSetupContext context) { } public override bool WorksWithSRP(RenderPipelineAsset scriptableRenderPipeline) => false; } private class UnknownSubTargetType : SubTarget { public string jsonData; public UnknownSubTargetType() : base() { isHidden = true; } public UnknownSubTargetType(string displayName, string jsonData) : base() { isHidden = false; this.displayName = displayName; this.jsonData = jsonData; } public override void Deserailize(string typeInfo, string jsonData) { this.jsonData = jsonData; base.Deserailize(typeInfo, jsonData); } public override string Serialize() { return jsonData.Trim(); } internal override Type targetType => typeof(UnknownTargetType); public override void GetActiveBlocks(ref TargetActiveBlockContext context) { } public override void GetFields(ref TargetFieldContext context) { } public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action<string> registerUndo) { context.AddHelpBox(MessageType.Warning, "Cannot find the code for this SubTarget, a package may be missing."); } public override bool IsActive() => false; public override void Setup(ref TargetSetupContext context) { } } internal class UnknownShaderPropertyType : AbstractShaderProperty { public string jsonData; public UnknownShaderPropertyType(string displayName, string jsonData) : base() { this.displayName = displayName; this.jsonData = jsonData; } public override void Deserailize(string typeInfo, string jsonData) { this.jsonData = jsonData; base.Deserailize(typeInfo, jsonData); } public override string Serialize() { return jsonData.Trim(); } internal override ConcreteSlotValueType concreteShaderValueType => ConcreteSlotValueType.Vector1; internal override bool isExposable => false; internal override bool isRenamable => false; internal override ShaderInput Copy() { // we CANNOT copy ourselves, as the serialized GUID in the jsonData would not match the json GUID return null; } public override PropertyType propertyType => PropertyType.Float; internal override void GetPropertyReferenceNames(List<string> result) { } internal override void GetPropertyDisplayNames(List<string> result) { } internal override string GetPropertyBlockString() { return ""; } internal override void AppendPropertyBlockStrings(ShaderStringBuilder builder) { builder.AppendLine("/* UNKNOWN PROPERTY: " + referenceName + " */"); } internal override bool AllowHLSLDeclaration(HLSLDeclaration decl) => false; internal override void ForeachHLSLProperty(Action<HLSLProperty> action) { action(new HLSLProperty(HLSLType._float, referenceName, HLSLDeclaration.Global, concretePrecision)); } internal override string GetPropertyAsArgumentString(string precisionString) { return ""; } internal override AbstractMaterialNode ToConcreteNode() { return null; } internal override PreviewProperty GetPreviewMaterialProperty() { return new PreviewProperty(propertyType) { name = referenceName, floatValue = 0.0f }; } public override string GetPropertyTypeString() { return ""; } } internal class UnknownMaterialSlotType : MaterialSlot { // used to deserialize some data out of an unknown MaterialSlot class SerializerHelper { [SerializeField] public string m_DisplayName = null; [SerializeField] public SlotType m_SlotType = SlotType.Input; [SerializeField] public bool m_Hidden = false; [SerializeField] public string m_ShaderOutputName = null; [SerializeField] public ShaderStageCapability m_StageCapability = ShaderStageCapability.All; } public string jsonData; public UnknownMaterialSlotType(string displayName, string jsonData) : base() { // copy some minimal information to try to keep the UI as similar as possible var helper = new SerializerHelper(); JsonUtility.FromJsonOverwrite(jsonData, helper); this.displayName = helper.m_DisplayName; this.hidden = helper.m_Hidden; this.stageCapability = helper.m_StageCapability; this.SetInternalData(helper.m_SlotType, helper.m_ShaderOutputName); // save the original json for saving this.jsonData = jsonData; } public override void Deserailize(string typeInfo, string jsonData) { this.jsonData = jsonData; base.Deserailize(typeInfo, jsonData); } public override string Serialize() { return jsonData.Trim(); } public override bool isDefaultValue => true; public override SlotValueType valueType => SlotValueType.Vector1; public override ConcreteSlotValueType concreteValueType => ConcreteSlotValueType.Vector1; public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) { } public override void CopyValuesFrom(MaterialSlot foundSlot) { // we CANNOT copy data from another slot, as the GUID in the serialized jsonData would not match our real GUID throw new NotSupportedException(); } } [NeverAllowedByTarget] internal class UnknownNodeType : AbstractMaterialNode { public string jsonData; public UnknownNodeType() : base() { jsonData = null; isValid = false; SetOverrideActiveState(ActiveState.ExplicitInactive, false); SetActive(false, false); } public UnknownNodeType(string jsonData) { this.jsonData = jsonData; isValid = false; SetOverrideActiveState(ActiveState.ExplicitInactive, false); SetActive(false, false); } public override void OnAfterDeserialize(string json) { jsonData = json; base.OnAfterDeserialize(json); } public override string Serialize() { EnqueSlotsForSerialization(); return jsonData.Trim(); } public override void ValidateNode() { base.ValidateNode(); owner.AddValidationError(objectId, "This node type could not be found. No function will be generated in the shader.", ShaderCompilerMessageSeverity.Warning); } // unknown node types cannot be copied, or else their GUID would not match the GUID in the serialized jsonDAta public override bool canCutNode => false; public override bool canCopyNode => false; } #endregion //Unknown Data Handling static readonly Dictionary<string, Type> k_TypeMap = CreateTypeMap(); internal static bool isDeserializing; internal static readonly Dictionary<string, JsonObject> valueMap = new Dictionary<string, JsonObject>(); static List<MultiJsonEntry> s_Entries; internal static bool isSerializing; internal static readonly List<JsonObject> serializationQueue = new List<JsonObject>(); internal static readonly HashSet<string> serializedSet = new HashSet<string>(); static JsonObject currentRoot = null; static Dictionary<string, Dictionary<string, string>> jsonBlobs = new Dictionary<string, Dictionary<string, string>>(); static Dictionary<string, Type> CreateTypeMap() { var map = new Dictionary<string, Type>(); foreach (var type in TypeCache.GetTypesDerivedFrom<JsonObject>()) { if (type.FullName != null) { map[type.FullName] = type; } } foreach (var type in TypeCache.GetTypesWithAttribute(typeof(FormerNameAttribute))) { if (type.IsAbstract || !typeof(JsonObject).IsAssignableFrom(type)) { continue; } foreach (var attribute in type.GetCustomAttributes(typeof(FormerNameAttribute), false)) { var legacyAttribute = (FormerNameAttribute)attribute; map[legacyAttribute.fullName] = type; } } return map; } public static Type ParseType(string typeString) { k_TypeMap.TryGetValue(typeString, out var type); return type; } public static List<MultiJsonEntry> Parse(string str) { var result = new List<MultiJsonEntry>(); const string separatorStr = "\n\n"; var startIndex = 0; var raw = new FakeJsonObject(); while (startIndex < str.Length) { var jsonBegin = str.IndexOf("{", startIndex, StringComparison.Ordinal); if (jsonBegin == -1) { break; } var jsonEnd = str.IndexOf(separatorStr, jsonBegin, StringComparison.Ordinal); if (jsonEnd == -1) { jsonEnd = str.IndexOf("\n\r\n", jsonBegin, StringComparison.Ordinal); if (jsonEnd == -1) { jsonEnd = str.LastIndexOf("}", StringComparison.Ordinal) + 1; } } var json = str.Substring(jsonBegin, jsonEnd - jsonBegin); JsonUtility.FromJsonOverwrite(json, raw); if (startIndex != 0 && string.IsNullOrWhiteSpace(raw.type)) { throw new InvalidOperationException($"Type is null or whitespace in JSON:\n{json}"); } result.Add(new MultiJsonEntry(raw.type, raw.id, json)); raw.Reset(); startIndex = jsonEnd + separatorStr.Length; } return result; } public static void Enqueue(JsonObject jsonObject, string json) { if (s_Entries == null) { throw new InvalidOperationException("Can only Enqueue during JsonObject.OnAfterDeserialize."); } valueMap.Add(jsonObject.objectId, jsonObject); s_Entries.Add(new MultiJsonEntry(jsonObject.GetType().FullName, jsonObject.objectId, json)); } public static JsonObject CreateInstanceForDeserialization(string typeString) { if (!k_TypeMap.TryGetValue(typeString, out var type)) { return new UnknownJsonObject(typeString); } var output = (JsonObject)Activator.CreateInstance(type, true); //This CreateInstance function is supposed to essentially create a blank copy of whatever class we end up deserializing into. //when we typically create new JsonObjects in all other cases, we want that object to be assumed to be the latest version. //This doesn't work if any json object was serialized before we had the idea of version, as the blank copy would have the //latest version on creation and since the serialized version wouldn't have a version member, it would not get overwritten //and we would automatically upgrade all previously serialized json objects incorrectly and without user action. To avoid this, //we default jsonObject version to 0, and if the serialized value has a different saved version it gets changed and if the serialized //version does not have a different saved value it remains 0 (earliest version) output.ChangeVersion(0); output.OnBeforeDeserialize(); return output; } private static FieldInfo s_ObjectIdField = typeof(JsonObject).GetField("m_ObjectId", BindingFlags.Instance | BindingFlags.NonPublic); public static void Deserialize(JsonObject root, List<MultiJsonEntry> entries, bool rewriteIds) { if (isDeserializing) { throw new InvalidOperationException("Nested MultiJson deserialization is not supported."); } try { isDeserializing = true; currentRoot = root; root.ChangeVersion(0); //Same issue as described in CreateInstance for (var index = 0; index < entries.Count; index++) { var entry = entries[index]; try { JsonObject value = null; if (index == 0) { value = root; } else { value = CreateInstanceForDeserialization(entry.type); } var id = entry.id; if (id != null) { // Need to make sure that references looking for the old ID will find it in spite of // ID rewriting. valueMap[id] = value; } if (rewriteIds || entry.id == null) { id = value.objectId; entries[index] = new MultiJsonEntry(entry.type, id, entry.json); valueMap[id] = value; } s_ObjectIdField.SetValue(value, id); } catch (Exception e) { // External code could throw exceptions, but we don't want that to fail the whole thing. // Potentially, the fallback type should also be used here. Debug.LogException(e); } } s_Entries = entries; // Not a foreach because `entries` can be populated by calls to `Enqueue` as we go. for (var i = 0; i < entries.Count; i++) { var entry = entries[i]; try { var value = valueMap[entry.id]; value.Deserailize(entry.type, entry.json); // Set ID again as it could be overwritten from JSON. s_ObjectIdField.SetValue(value, entry.id); value.OnAfterDeserialize(entry.json); } catch (Exception e) { if (!String.IsNullOrEmpty(entry.id)) { var value = valueMap[entry.id]; if (value != null) { Debug.LogError($"Exception thrown while deserialize object of type {entry.type}: {e.Message}"); } } Debug.LogException(e); } } s_Entries = null; foreach (var entry in entries) { try { var value = valueMap[entry.id]; value.OnAfterMultiDeserialize(entry.json); } catch (Exception e) { Debug.LogException(e); } } } finally { valueMap.Clear(); currentRoot = null; isDeserializing = false; } } public static string Serialize(JsonObject mainObject) { if (isSerializing) { throw new InvalidOperationException("Nested MultiJson serialization is not supported."); } try { isSerializing = true; serializedSet.Add(mainObject.objectId); serializationQueue.Add(mainObject); var idJsonList = new List<(string, string)>(); // Not a foreach because the queue is populated by `JsonData<T>`s as we go. for (var i = 0; i < serializationQueue.Count; i++) { var value = serializationQueue[i]; var json = value.Serialize(); idJsonList.Add((value.objectId, json)); } if (jsonBlobs.TryGetValue(mainObject.objectId, out var blobs)) { foreach (var blob in blobs) { if (!idJsonList.Contains((blob.Key, blob.Value))) idJsonList.Add((blob.Key, blob.Value)); } } idJsonList.Sort((x, y) => // Main object needs to be placed first x.Item1 == mainObject.objectId ? -1 : y.Item1 == mainObject.objectId ? 1 : // We sort everything else by ID to consistently maintain positions in the output x.Item1.CompareTo(y.Item1)); const string k_NewLineString = "\n"; var sb = new StringBuilder(); foreach (var (id, json) in idJsonList) { sb.Append(json); sb.Append(k_NewLineString); sb.Append(k_NewLineString); } return sb.ToString(); } finally { serializationQueue.Clear(); serializedSet.Clear(); isSerializing = false; } } public static void PopulateValueMap(JsonObject mainObject) { if (isSerializing) { throw new InvalidOperationException("Nested MultiJson serialization is not supported."); } try { isSerializing = true; serializedSet.Add(mainObject.objectId); serializationQueue.Add(mainObject); // Not a foreach because the queue is populated by `JsonRef<T>`s as we go. for (var i = 0; i < serializationQueue.Count; i++) { var value = serializationQueue[i]; value.Serialize(); valueMap[value.objectId] = value; } } finally { serializationQueue.Clear(); serializedSet.Clear(); isSerializing = false; } } } }
37.315934
173
0.513105
[ "MIT" ]
PULSAR2105/Boids-Bug
Library/PackageCache/com.unity.shadergraph@12.1.1/Editor/Serialization/MultiJsonInternal.cs
27,166
C#
// // EditableTorrent.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2006 Alan McGovern // // 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.Generic; using System.Linq; using MonoTorrent.BEncoding; namespace MonoTorrent { public abstract class EditableTorrent { static readonly BEncodedString AnnounceKey = "announce"; static readonly BEncodedString AnnounceListKey = "announce-list"; static readonly BEncodedString CommentKey = "comment"; static readonly BEncodedString CreatedByKey = "created by"; static readonly BEncodedString EncodingKey = "encoding"; static readonly BEncodedString InfoKey = "info"; private protected static readonly BEncodedString PieceLengthKey = "piece length"; static readonly BEncodedString PrivateKey = "private"; static readonly BEncodedString PublisherKey = "publisher"; static readonly BEncodedString PublisherUrlKey = "publisher-url"; public string Announce { get => GetString (Metadata, AnnounceKey); set => SetString (Metadata, AnnounceKey, value); } public List<List<string>> Announces { get; } protected bool CanEditSecureMetadata { get; set; } public string Comment { get => GetString (Metadata, CommentKey); set => SetString (Metadata, CommentKey, value); } public string CreatedBy { get => GetString (Metadata, CreatedByKey); set => SetString (Metadata, CreatedByKey, value); } public string Encoding { get => GetString (Metadata, EncodingKey); private set => SetString (Metadata, EncodingKey, value); } protected BEncodedDictionary InfoDict { get => GetDictionary (Metadata, InfoKey); private set => SetDictionary (Metadata, InfoKey, value); } protected BEncodedDictionary Metadata { get; private set; } public long PieceLength { get => GetLong (InfoDict, PieceLengthKey); set => SetLong (InfoDict, PieceLengthKey, value); } public bool Private { get => GetLong (InfoDict, PrivateKey) == 1; set => SetLong (InfoDict, PrivateKey, value ? 1 : 0); } public string Publisher { get => GetString (InfoDict, PublisherKey); set => SetString (InfoDict, PublisherKey, value); } public string PublisherUrl { get => GetString (InfoDict, PublisherUrlKey); set => SetString (InfoDict, PublisherUrlKey, value); } protected EditableTorrent () : this (new BEncodedDictionary ()) { } protected EditableTorrent (BEncodedDictionary metadata) { Check.Metadata (metadata); Announces = new List<List<string>> (); Initialise (BEncodedValue.Clone (metadata)); } void Initialise (BEncodedDictionary metadata) { Metadata = metadata; if (!Metadata.TryGetValue (AnnounceListKey, out BEncodedValue value)) { value = new BEncodedList (); Metadata.Add (AnnounceListKey, value); } if (value is BEncodedList tiers) foreach (var tier in tiers.OfType<BEncodedList> ()) Announces.Add (tier.OfType<BEncodedString> ().Select (t => t.Text).ToList ()); if (string.IsNullOrEmpty (Encoding)) Encoding = "UTF-8"; if (InfoDict == null) InfoDict = new BEncodedDictionary (); } protected void CheckCanEditSecure () { if (!CanEditSecureMetadata) throw new InvalidOperationException ("Cannot edit metadata which alters the infohash while CanEditSecureMetadata is false"); } public BEncodedValue GetCustom (BEncodedString key) { if (Metadata.TryGetValue (key, out BEncodedValue value)) return value; return null; } public BEncodedValue GetCustomSecure (BEncodedString key) { CheckCanEditSecure (); if (InfoDict.TryGetValue (key, out BEncodedValue value)) return value; return null; } public void SetCustom (BEncodedString key, BEncodedValue value) { Check.Key (key); Check.Value (value); if (InfoKey.Equals (key)) CheckCanEditSecure (); Metadata[key] = value; } public void SetCustomSecure (BEncodedString key, BEncodedValue value) { CheckCanEditSecure (); Check.Key (key); Check.Value (value); InfoDict[key] = value; } public void RemoveCustom (BEncodedString key) { Check.Key (key); Metadata.Remove (key); } public void RemoveCustomSecure (BEncodedString key) { CheckCanEditSecure (); Check.Key (key); InfoDict.Remove (key); } protected BEncodedDictionary GetDictionary (BEncodedDictionary dictionary, BEncodedString key) { // // Required? Probably. // if (dictionary == InfoDict) // CheckCanEditSecure (); if (dictionary.TryGetValue (key, out BEncodedValue value)) return (BEncodedDictionary) value; return null; } protected long GetLong (BEncodedDictionary dictionary, BEncodedString key) { if (dictionary.TryGetValue (key, out BEncodedValue value)) return ((BEncodedNumber) value).Number; throw new ArgumentException ($"The value for key {key} was not a BEncodedNumber"); } protected string GetString (BEncodedDictionary dictionary, BEncodedString key) { if (dictionary.TryGetValue (key, out BEncodedValue value)) return ((BEncodedString) value).Text; return null; } protected void SetDictionary (BEncodedDictionary dictionary, BEncodedString key, BEncodedDictionary value) { if (dictionary == InfoDict) CheckCanEditSecure (); dictionary[key] = value; } protected void SetLong (BEncodedDictionary dictionary, BEncodedString key, long value) { if (dictionary == InfoDict) CheckCanEditSecure (); dictionary[key] = new BEncodedNumber (value); } protected void SetString (BEncodedDictionary dictionary, BEncodedString key, string value) { if (dictionary == InfoDict) CheckCanEditSecure (); if (value == null) dictionary.Remove (key); else dictionary[key] = new BEncodedString (value); } } }
33.534694
140
0.59871
[ "MIT" ]
OneFingerCodingWarrior/monotorrent
src/MonoTorrent/MonoTorrent/EditableTorrent.cs
8,216
C#
// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Windows.Forms; using Microsoft.PowerToys.PreviewHandler.Pdf; using Microsoft.PowerToys.STATestExtension; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace PdfPreviewHandlerUnitTests { [STATestClass] public class PdfPreviewHandlerTest { [TestMethod] public void PdfPreviewHandlerControlAddsControlsToFormWhenDoPreviewIsCalled() { // Arrange using (var pdfPreviewHandlerControl = new PdfPreviewHandlerControl()) { // Act var file = File.ReadAllBytes("HelperFiles/sample.pdf"); pdfPreviewHandlerControl.DoPreview<IStream>(GetMockStream(file)); var flowLayoutPanel = pdfPreviewHandlerControl.Controls[0] as FlowLayoutPanel; // Assert Assert.AreEqual(1, pdfPreviewHandlerControl.Controls.Count); } } [TestMethod] public void PdfPreviewHandlerControlShouldAddValidInfoBarIfPdfPreviewThrows() { // Arrange using (var pdfPreviewHandlerControl = new PdfPreviewHandlerControl()) { var mockStream = new Mock<IStream>(); mockStream .Setup(x => x.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<IntPtr>())) .Throws(new Exception()); // Act pdfPreviewHandlerControl.DoPreview(mockStream.Object); var textBox = pdfPreviewHandlerControl.Controls[0] as RichTextBox; // Assert Assert.IsFalse(string.IsNullOrWhiteSpace(textBox.Text)); Assert.AreEqual(1, pdfPreviewHandlerControl.Controls.Count); Assert.AreEqual(DockStyle.Top, textBox.Dock); Assert.AreEqual(Color.LightYellow, textBox.BackColor); Assert.IsTrue(textBox.Multiline); Assert.IsTrue(textBox.ReadOnly); Assert.AreEqual(RichTextBoxScrollBars.None, textBox.ScrollBars); Assert.AreEqual(BorderStyle.None, textBox.BorderStyle); } } private static IStream GetMockStream(byte[] sourceArray) { var streamMock = new Mock<IStream>(); var firstCall = true; streamMock .Setup(x => x.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<IntPtr>())) .Callback<byte[], int, IntPtr>((buffer, countToRead, bytesReadPtr) => { if (firstCall) { Array.Copy(sourceArray, 0, buffer, 0, sourceArray.Length); Marshal.WriteInt32(bytesReadPtr, sourceArray.Length); firstCall = false; } else { Marshal.WriteInt32(bytesReadPtr, 0); } }); return streamMock.Object; } } }
38.111111
97
0.566764
[ "MIT" ]
CamperSamu/PowerToys
src/modules/previewpane/UnitTests-PdfPreviewHandler/PdfPreviewHandlerTest.cs
3,343
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the robomaker-2018-06-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RoboMaker.Model { /// <summary> /// Information about worlds that finished. /// </summary> public partial class FinishedWorldsSummary { private FailureSummary _failureSummary; private int? _finishedCount; private List<string> _succeededWorlds = new List<string>(); /// <summary> /// Gets and sets the property FailureSummary. /// <para> /// Information about worlds that failed. /// </para> /// </summary> public FailureSummary FailureSummary { get { return this._failureSummary; } set { this._failureSummary = value; } } // Check to see if FailureSummary property is set internal bool IsSetFailureSummary() { return this._failureSummary != null; } /// <summary> /// Gets and sets the property FinishedCount. /// <para> /// The total number of finished worlds. /// </para> /// </summary> public int FinishedCount { get { return this._finishedCount.GetValueOrDefault(); } set { this._finishedCount = value; } } // Check to see if FinishedCount property is set internal bool IsSetFinishedCount() { return this._finishedCount.HasValue; } /// <summary> /// Gets and sets the property SucceededWorlds. /// <para> /// A list of worlds that succeeded. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public List<string> SucceededWorlds { get { return this._succeededWorlds; } set { this._succeededWorlds = value; } } // Check to see if SucceededWorlds property is set internal bool IsSetSucceededWorlds() { return this._succeededWorlds != null && this._succeededWorlds.Count > 0; } } }
30.9375
108
0.592256
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/RoboMaker/Generated/Model/FinishedWorldsSummary.cs
2,970
C#
#nullable disable using System.Linq; using VocaDb.Model.Domain.Albums; using VocaDb.Model.Domain.Globalization; namespace VocaDb.Model.DataContracts.Albums { public class AlbumWithArchivedVersionsContract : AlbumContract { public AlbumWithArchivedVersionsContract(Album album, ContentLanguagePreference languagePreference) : base(album, languagePreference) { ParamIs.NotNull(() => album); ArchivedVersions = album.ArchivedVersionsManager.Versions.Select(a => new ArchivedAlbumVersionContract(a)).ToArray(); } public ArchivedAlbumVersionContract[] ArchivedVersions { get; init; } } }
28.545455
121
0.767516
[ "MIT" ]
Pyther99/vocadb
VocaDbModel/DataContracts/Albums/AlbumWithArchivedVersions.cs
628
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using CefSharp.Wpf; namespace PrintBrowser { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MenuHandler menuHandler = new MenuHandler(); webBrowser.MenuHandler = menuHandler; webBrowser.RegisterJsObject("Internal", new Internal()); } } }
24.666667
68
0.697789
[ "MIT" ]
liangminhua/PrintBrowser
PrintBrowser/MainWindow.xaml.cs
826
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using Microsoft.Practices.Unity.Configuration.Tests.ConfigFiles; using Microsoft.Practices.Unity.TestSupport; using Microsoft.Practices.Unity.TestSupport.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.Unity.Configuration.Tests { /// <summary> /// Summary description for When_ConfiguringContainerForPropertyInjection /// </summary> [TestClass] public class When_ConfiguringContainerForPropertyInjection : ContainerConfiguringFixture<ConfigFileLocator> { public When_ConfiguringContainerForPropertyInjection() : base("InjectingProperties", String.Empty) { } [TestMethod] public void Then_InjectedPropertyIsResolvedAccordingToConfiguration() { var expected = Container.Resolve<object>("special"); var result = Container.Resolve<ObjectWithTwoProperties>("singleProperty"); Assert.AreSame(expected, result.Obj1); } [TestMethod] public void Then_InjectedPropertyIsResolvedAccordingToConfigurationUsingAttributes() { var expected = Container.Resolve<object>("special"); var result = Container.Resolve<ObjectWithTwoProperties>("twoProperties"); Assert.AreSame(expected, result.Obj1); } [TestMethod] public void Then_InjectedPropertyIsProperType() { var result = Container.Resolve<ObjectWithTwoProperties>("injectingDifferentType"); Assert.IsInstanceOfType(result.Obj1, typeof(SpecialLogger)); } [TestMethod] public void Then_MultiplePropertiesGetInjected() { var expected = Container.Resolve<object>("special"); var result = Container.Resolve<ObjectWithTwoProperties>("injectingDifferentType"); Assert.IsInstanceOfType(result.Obj1, typeof(SpecialLogger)); Assert.AreSame(expected, result.Obj2); } } }
36.050847
122
0.693935
[ "Apache-2.0", "MIT" ]
drcarver/unity
source/Unity.Configuration/Tests/Unity.Configuration.Tests/When_ConfiguringContainerForPropertyInjection.cs
2,129
C#
using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("XCLCMS.Data.BLL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("XCLCMS.Data.BLL")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("d37abe49-5e8c-460a-bd0b-e958f1d69309")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.628571
59
0.713519
[ "Apache-2.0" ]
jiangnanwoniu/XCLCMS_asp.net
XCLCMS.Data/XCLCMS.Data.BLL/Properties/AssemblyInfo.cs
1,291
C#
namespace BattleCards.Data { using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(DatabaseConfiguration.ConnectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } }
25.85
85
0.682785
[ "MIT" ]
villdimova/SoftUni-WEB
ExamPreparation/BattleCards/Battle Cards_Skeleton/BattleCards/Data/ApplicationDbContext.cs
519
C#
// ReSharper disable InconsistentNaming using System; using System.Threading; using EasyNetQ.Producer; using Xunit; namespace EasyNetQ.Tests.Integration { [Explicit("Requires a local RabbitMQ instance to work")] public class PolymorphicRpc : IDisposable { private IBus bus; public PolymorphicRpc() { bus = RabbitHutch.CreateBus("host=localhost"); } public void Dispose() { bus.Dispose(); } [Fact] public void Should_request_some_animals() { var cat = new Cat { Name = "Gobbolino", Meow = "Purr" }; var dog = new Dog { Name = "Rover", Bark = "Woof" }; bus.Rpc.RequestAsync<IAnimal, IAnimal>(cat); bus.Rpc.RequestAsync<IAnimal, IAnimal>(dog); } [Fact] public void Should_request_respond_with_correct_message_types() { bus.Rpc.Respond<IAnimal, IAnimal>(@interface => { var cat = @interface as Cat; var dog = @interface as Dog; if (cat != null) { Console.Out.WriteLine("Name = {0}", cat.Name); Console.Out.WriteLine("Meow = {0}", cat.Meow); } else if (dog != null) { Console.Out.WriteLine("Name = {0}", dog.Name); Console.Out.WriteLine("Bark = {0}", dog.Bark); } else { Console.Out.WriteLine("message was not a dog or a cat"); } return @interface; }); Thread.Sleep(500); IAnimal request = new Cat { Name = "Gobbolino", Meow = "Purr" }; IAnimal response = bus.Rpc.Request<IAnimal, IAnimal>(request); Assert.Equal(request.Name, response.Name); Assert.Same(request.GetType(), response.GetType()); } } } // ReSharper restore InconsistentNaming
25.755814
76
0.46772
[ "MIT" ]
Eu-JinOoi/EasyNetQ
Source/EasyNetQ.Tests/Integration/PolymorphicRpc.cs
2,217
C#
using System; using System.Dynamic; namespace Ams.Data { internal class UpdateBuilderDynamic : BaseUpdateBuilder, IUpdateBuilderDynamic, IInsertUpdateBuilderDynamic { public dynamic Item { get; private set; } internal UpdateBuilderDynamic(IDbProvider dbProvider, IDbCommand command, string name, ExpandoObject item) : base(dbProvider, command, name) { Data.Item = item; Item = item; } public virtual IUpdateBuilderDynamic Where(string columnName, object value, DataTypes parameterType, int size) { Actions.WhereAction(columnName, value, parameterType, size); return this; } public IUpdateBuilderDynamic Column(string columnName, object value, DataTypes parameterType, int size) { Actions.ColumnValueAction(columnName, value, parameterType, size); return this; } public IUpdateBuilderDynamic Column(string propertyName, DataTypes parameterType, int size) { Actions.ColumnValueDynamic((ExpandoObject) Data.Item, propertyName, parameterType, size); return this; } public IUpdateBuilderDynamic Where(string name, DataTypes parameterType, int size) { var propertyValue = ReflectionHelper.GetPropertyValueDynamic(Data.Item, name); Where(name, propertyValue, parameterType, size); return this; } public IUpdateBuilderDynamic AutoMap(params string[] ignoreProperties) { Actions.AutoMapDynamicTypeColumnsAction(ignoreProperties); return this; } IInsertUpdateBuilderDynamic IInsertUpdateBuilderDynamic.Column(string columnName, object value, DataTypes parameterType, int size) { Actions.ColumnValueAction(columnName, value, parameterType, size); return this; } IInsertUpdateBuilderDynamic IInsertUpdateBuilderDynamic.Column(string propertyName, DataTypes parameterType, int size) { Actions.ColumnValueDynamic((ExpandoObject)Data.Item, propertyName, parameterType, size); return this; } public IUpdateBuilderDynamic Fill(Action<IInsertUpdateBuilderDynamic> fillMethod) { fillMethod(this); return this; } } }
30.253731
132
0.775037
[ "MIT" ]
SkyGrass/hippos_api_vm
Ams.Data/Builders/Update/UpdateBuilderDynamic.cs
2,029
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using AJS.Data.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; namespace AJS.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class LoginWithRecoveryCodeModel : PageModel { private readonly SignInManager<User> _signInManager; private readonly ILogger<LoginWithRecoveryCodeModel> _logger; private readonly IStringLocalizer<LoginWithRecoveryCodeModel> _localizer; public LoginWithRecoveryCodeModel(SignInManager<User> signInManager, ILogger<LoginWithRecoveryCodeModel> logger, IStringLocalizer<LoginWithRecoveryCodeModel> localizer) { _signInManager = signInManager; _logger = logger; _localizer = localizer; } [BindProperty] public InputModel Input { get; set; } public string ReturnUrl { get; set; } public class InputModel { [BindProperty] [Required] [DataType(DataType.Text)] [Display(Name = "Recovery Code")] public string RecoveryCode { get; set; } } public async Task<IActionResult> OnGetAsync(string returnUrl = null) { // Ensure the user has gone through the username & password screen first var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException(_localizer[$"Unable to load two-factor authentication user."]); } ReturnUrl = returnUrl; return Page(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { if (!ModelState.IsValid) { return Page(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException(_localizer[$"Unable to load two-factor authentication user."]); } var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty); var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id); return LocalRedirect(returnUrl ?? Url.Content("~/")); } if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return RedirectToPage("./Lockout"); } else { _logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id); ModelState.AddModelError(string.Empty, _localizer["Invalid recovery code entered."]); return Page(); } } } }
34.904255
176
0.618714
[ "Apache-2.0" ]
Valentin9003/AJS
AJS.Web/Areas/Identity/Pages/Account/LoginWithRecoveryCode.cshtml.cs
3,283
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; public partial class Default2 : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UserInputConnectionString"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { } }
25.166667
129
0.785872
[ "MIT" ]
Silight/MaintenanceLog
Maintenence/RequestForm/ManagerComplete.aspx.cs
455
C#
using Clr2Ts.Transpiler.Configuration; namespace Clr2Ts.Transpiler.Output { /// <summary> /// Represents the configuration that specifies how the code should be written to individual files. /// </summary> public sealed class OutputFilesConfiguration { /// <summary> /// Creates an <see cref="OutputFilesConfiguration"/>. /// </summary> /// <param name="directory">Directory, in which the files should be created.</param> /// <param name="mimicNamespacesWithSubdirectories">If set to true, files will be placed into subdirectories that correspond to the namespaces.</param> public OutputFilesConfiguration(string directory, bool mimicNamespacesWithSubdirectories) { if (string.IsNullOrWhiteSpace(directory)) throw new ConfigurationException("The directory for the files output must be specified."); Directory = directory; MimicNamespacesWithSubdirectories = mimicNamespacesWithSubdirectories; } /// <summary> /// Gets the directory, in which the files should be created. /// </summary> public string Directory { get; } /// <summary> /// Gets a value indicating if the files should be placed into subdirectories that correspond to the namespaces. /// </summary> public bool MimicNamespacesWithSubdirectories { get; } } }
42.757576
159
0.672573
[ "MIT" ]
Chips100/clr2ts
src/Clr2Ts.Transpiler/Output/OutputFilesConfiguration.cs
1,413
C#
using System.Data.Entity.ModelConfiguration; namespace Siege.Security.SQL.Mappings { public class UserMapper : DbContextMapper<User> { public override void Build(EntityTypeConfiguration<User> configuration) { configuration.HasKey(x => x.ID); configuration.Property(x => x.ID).HasColumnName("UserID"); configuration.Property(x => x.Name).HasColumnName("UserName"); configuration.Property(x => x.Salt).HasColumnName("PasswordSalt"); configuration.Property(x => x.SecretQuestion).HasColumnName("SecretQuestion"); configuration.Property(x => x.SecretAnswer).HasColumnName("SecretAnswer"); configuration.HasRequired(x => x.Consumer).WithMany(x => x.Users).Map(m => m.MapKey("ConsumerID")); configuration.Ignore(x => x.IsAuthenticated); configuration.Ignore(x => x.Permissions); configuration.HasMany(x => x.Roles) .WithMany(x => x.Users) .Map(map => { map.ToTable("UsersInRoles"); map.MapLeftKey("UserID"); map.MapRightKey("RoleID"); }); configuration.HasMany(x => x.Groups) .WithMany(x => x.Users) .Map(map => { map.ToTable("UsersInGroups"); map.MapLeftKey("UserID"); map.MapRightKey("GroupID"); }); configuration.HasMany(x => x.Applications) .WithMany(x => x.Users) .Map(map => { map.ToTable("UsersInApplications"); map.MapLeftKey("UserID"); map.MapRightKey("ApplicationID"); }); } } }
39.12766
111
0.519304
[ "Apache-2.0" ]
lokalan/Siege
Siege.Security/Siege.Security.SQL/Mappings/UserMapper.cs
1,841
C#
using System.Runtime.Serialization; namespace Service.BackofficeCreds.Grpc.Models { [DataContract] public class RemoveRoleRequest { [DataMember(Order = 1)] public string RoleName { get; set; } } }
22.1
68
0.696833
[ "MIT" ]
MyJetWallet/Service.BackofficeCreds
src/Service.BackofficeCreds.Grpc/Models/RemoveRoleRequest.cs
221
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.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions { /// <summary> /// Represents an operation between an expression and a type. /// </summary> [DebuggerTypeProxy(typeof(TypeBinaryExpressionProxy))] public sealed class TypeBinaryExpression : Expression { internal TypeBinaryExpression( Expression expression, Type typeOperand, ExpressionType nodeType ) { Expression = expression; TypeOperand = typeOperand; NodeType = nodeType; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type => typeof(bool); /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get; } /// <summary> /// Gets the expression operand of a type test operation. /// </summary> public Expression Expression { get; } /// <summary> /// Gets the type operand of a type test operation. /// </summary> public Type TypeOperand { get; } #region Reduce TypeEqual internal Expression ReduceTypeEqual() { Type cType = Expression.Type; if (cType.IsValueType || TypeOperand.IsPointer) { if (cType.IsNullableType()) { // If the expression type is a nullable type, it will match if // the value is not null and the type operand // either matches or is its type argument (T to its T?). if (cType.GetNonNullableType() != TypeOperand.GetNonNullableType()) { return Expression.Block(Expression, Utils.Constant(value: false)); } else { return Expression.NotEqual( Expression, Expression.Constant(null, Expression.Type) ); } } else { // For other value types (including Void), we can // determine the result now return Expression.Block( Expression, Utils.Constant(cType == TypeOperand.GetNonNullableType()) ); } } Debug.Assert( TypeUtils.AreReferenceAssignable(typeof(object), Expression.Type), "Expecting reference types only after this point." ); // Can check the value right now for constants. if (Expression.NodeType == ExpressionType.Constant) { return ReduceConstantTypeEqual(); } // expression is a ByVal parameter. Can safely reevaluate. var parameter = Expression as ParameterExpression; if (parameter != null && !parameter.IsByRef) { return ByValParameterTypeEqual(parameter); } // Create a temp so we only evaluate the left side once parameter = Expression.Parameter(typeof(object)); return Expression.Block( new TrueReadOnlyCollection<ParameterExpression>(parameter), new TrueReadOnlyCollection<Expression>( Expression.Assign(parameter, Expression), ByValParameterTypeEqual(parameter) ) ); } // Helper that is used when re-eval of LHS is safe. private Expression ByValParameterTypeEqual(ParameterExpression value) { Expression getType = Expression.Call(value, Object_GetType); // In remoting scenarios, obj.GetType() can return an interface. // But JIT32's optimized "obj.GetType() == typeof(ISomething)" codegen, // causing it to always return false. // We workaround this optimization by generating different, less optimal IL // if TypeOperand is an interface. if (TypeOperand.IsInterface) { ParameterExpression temp = Expression.Parameter(typeof(Type)); getType = Expression.Block( new TrueReadOnlyCollection<ParameterExpression>(temp), new TrueReadOnlyCollection<Expression>(Expression.Assign(temp, getType), temp) ); } // We use reference equality when comparing to null for correctness // (don't invoke a user defined operator), and reference equality // on types for performance (so the JIT can optimize the IL). return Expression.AndAlso( Expression.ReferenceNotEqual(value, Utils.Null), Expression.ReferenceEqual( getType, Expression.Constant(TypeOperand.GetNonNullableType(), typeof(Type)) ) ); } private Expression ReduceConstantTypeEqual() { ConstantExpression? ce = Expression as ConstantExpression; //TypeEqual(null, T) always returns false. if (ce!.Value == null) { return Utils.Constant(value: false); } else { return Utils.Constant(TypeOperand.GetNonNullableType() == ce.Value.GetType()); } } #endregion /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTypeBinary(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expression">The <see cref="Expression"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TypeBinaryExpression Update(Expression expression) { if (expression == Expression) { return this; } if (NodeType == ExpressionType.TypeIs) { return Expression.TypeIs(expression, TypeOperand); } return Expression.TypeEqual(expression, TypeOperand); } } public partial class Expression { /// <summary> /// Creates a <see cref="TypeBinaryExpression"/>. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="ExpressionType.TypeIs"/> and for which the <see cref="TypeBinaryExpression.Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeIs(Expression expression, Type type) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type)); return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs); } /// <summary> /// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="ExpressionType.TypeEqual"/> and for which the <see cref="TypeBinaryExpression.Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeEqual(Expression expression, Type type) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type)); return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual); } } }
42.583333
323
0.583376
[ "MIT" ]
belav/runtime
src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs
9,709
C#
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.EventGrid.Models; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DeadLetterSample { public static class WebhookSubscriptionFunction { /* This function will act as an event subscription endpoint for your event subscription. The function implements the validation handshake and returns a Bad Request response for all other incoming events. */ [FunctionName("WebhookSubscriptionFunction")] public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log) { log.Info($"C# HTTP trigger function begun"); string response = string.Empty; const string SubscriptionValidationEvent = "Microsoft.EventGrid.SubscriptionValidationEvent"; string requestContent = await req.Content.ReadAsStringAsync(); log.Info($"Received events: {requestContent}"); EventGridEvent[] eventGridEvents = JsonConvert.DeserializeObject<EventGridEvent[]>(requestContent); foreach (EventGridEvent eventGridEvent in eventGridEvents) { JObject dataObject = eventGridEvent.Data as JObject; // Deserialize the event data into the appropriate type based on event type if (string.Equals(eventGridEvent.EventType, SubscriptionValidationEvent, StringComparison.OrdinalIgnoreCase)) { var eventData = dataObject.ToObject<SubscriptionValidationEventData>(); log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode}, validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}"); // Do any additional validation (as required) such as validating that the Azure resource ID of the topic matches // the expected topic and then return back the below response var responseData = new SubscriptionValidationResponse(); responseData.ValidationResponse = eventData.ValidationCode; return req.CreateResponse(HttpStatusCode.OK, responseData); } } // Responding back with a 400 Bad Request is intentional and only for the purpose of demonstrating dead lettering. return req.CreateResponse(HttpStatusCode.BadRequest, response); } } }
51.596154
189
0.689899
[ "MIT" ]
Azure-Samples/event-grid-dotnet-handle-deadlettered-events
function-app/WebhookSubscriptionFunction.cs
2,683
C#
using System.Windows; using NHM.Wpf.ViewModels.Models; using NHM.Wpf.ViewModels.Plugins; using NHM.Wpf.Views.Common; namespace NHM.Wpf.Views.Plugins { /// <summary> /// Interaction logic for PluginWindow.xaml /// </summary> public partial class PluginWindow : Window { private readonly PluginVM _vm; public PluginWindow() { InitializeComponent(); _vm = this.AssertViewModel<PluginVM>(); WindowUtils.InitWindow(this); } private void PluginEntry_OnDetailsClick(object sender, PluginEventArgs e) { _vm.SetDetails(e.ViewModel); } private void PluginDetail_OnBackClick(object sender, RoutedEventArgs e) { _vm.SetToList(); } private void Window_Loaded(object sender, RoutedEventArgs e) { WindowUtils.SetForceSoftwareRendering(this); } } }
24.102564
81
0.617021
[ "MIT" ]
ARAisling/NiceHashMiner
src/NHM.Wpf/Views/Plugins/PluginWindow.xaml.cs
942
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request to get all the information of a flexible seating host instance. /// The response is either GroupFlexibleSeatingHostGetInstanceResponse22 or ErrorResponse. /// <see cref="GroupFlexibleSeatingHostGetInstanceResponse22"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""43afb2158d313a1d1a148124d7caba1e:183""}]")] public class GroupFlexibleSeatingHostGetInstanceRequest22 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceUserId; [XmlElement(ElementName = "serviceUserId", IsNullable = false, Namespace = "")] [Group(@"43afb2158d313a1d1a148124d7caba1e:183")] [MinLength(1)] [MaxLength(161)] public string ServiceUserId { get => _serviceUserId; set { ServiceUserIdSpecified = true; _serviceUserId = value; } } [XmlIgnore] protected bool ServiceUserIdSpecified { get; set; } } }
31.860465
129
0.662044
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupFlexibleSeatingHostGetInstanceRequest22.cs
1,370
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Rendering; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.ViewComponents; public class DefaultViewComponentActivatorTests { [Fact] public void DefaultViewComponentActivator_ActivatesViewComponentContext() { // Arrange var expectedInstance = new TestViewComponent(); var typeActivator = new Mock<ITypeActivatorCache>(); typeActivator .Setup(ta => ta.CreateInstance<object>(It.IsAny<IServiceProvider>(), It.IsAny<Type>())) .Returns(expectedInstance); var activator = new DefaultViewComponentActivator(typeActivator.Object); var context = CreateContext(typeof(TestViewComponent)); expectedInstance.ViewComponentContext = context; // Act var instance = activator.Create(context) as ViewComponent; // Assert Assert.NotNull(instance); Assert.Same(context, instance.ViewComponentContext); } [Fact] public void DefaultViewComponentActivator_ActivatesViewComponentContext_IgnoresNonPublic() { // Arrange var expectedInstance = new VisibilityViewComponent(); var typeActivator = new Mock<ITypeActivatorCache>(); typeActivator .Setup(ta => ta.CreateInstance<object>(It.IsAny<IServiceProvider>(), It.IsAny<Type>())) .Returns(expectedInstance); var activator = new DefaultViewComponentActivator(typeActivator.Object); var context = CreateContext(typeof(VisibilityViewComponent)); expectedInstance.ViewComponentContext = context; // Act var instance = activator.Create(context) as VisibilityViewComponent; // Assert Assert.NotNull(instance); Assert.Same(context, instance.ViewComponentContext); Assert.Null(instance.C); } [Fact] public async Task DefaultViewComponentActivator_ReleaseAsync_PrefersAsyncDisposableOverDisposable() { // Arrange var instance = new SyncAndAsyncDisposableViewComponent(); var activator = new DefaultViewComponentActivator(Mock.Of<ITypeActivatorCache>()); var context = CreateContext(typeof(SyncAndAsyncDisposableViewComponent)); // Act await activator.ReleaseAsync(context, instance); // Assert Assert.True(instance.AsyncDisposed); Assert.False(instance.SyncDisposed); } private static ViewComponentContext CreateContext(Type componentType) { return new ViewComponentContext { ViewComponentDescriptor = new ViewComponentDescriptor { TypeInfo = componentType.GetTypeInfo() }, ViewContext = new ViewContext { HttpContext = new DefaultHttpContext { RequestServices = Mock.Of<IServiceProvider>() } } }; } private class TestViewComponent : ViewComponent { public Task ExecuteAsync() { throw new NotImplementedException(); } } private class VisibilityViewComponent : ViewComponent { [ViewComponentContext] protected internal ViewComponentContext C { get; set; } } public class ActivablePropertiesViewComponent : IDisposable { [ViewComponentContext] public ViewComponentContext Context { get; set; } public bool Disposed { get; private set; } public void Dispose() { Disposed = true; } public string Invoke() { return "something"; } } public class AsyncDisposableViewComponent : IAsyncDisposable { [ViewComponentContext] public ViewComponentContext Context { get; set; } public bool Disposed { get; private set; } public ValueTask DisposeAsync() { Disposed = true; return default; } public string Invoke() { return "something"; } } public class SyncAndAsyncDisposableViewComponent : IDisposable, IAsyncDisposable { [ViewComponentContext] public ViewComponentContext Context { get; set; } public bool AsyncDisposed { get; private set; } public bool SyncDisposed { get; private set; } public void Dispose() => SyncDisposed = true; public ValueTask DisposeAsync() { AsyncDisposed = true; return default; } public string Invoke() { return "something"; } } }
27.988636
103
0.637028
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Mvc/Mvc.ViewFeatures/test/ViewComponents/DefaultViewComponentActivatorTests.cs
4,926
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("FileSystem")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FileSystem")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("3ef65919-ebe7-43e8-8fe0-0550f3820360")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.405405
57
0.686796
[ "Apache-2.0" ]
kcykkk/SimulativeFileSystem
FileSystem/Properties/AssemblyInfo.cs
1,328
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudResourceManager.v1beta1 { /// <summary>The CloudResourceManager Service.</summary> public class CloudResourceManagerService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudResourceManagerService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudResourceManagerService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Organizations = new OrganizationsResource(this); Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "cloudresourcemanager"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://cloudresourcemanager.googleapis.com/"; #else "https://cloudresourcemanager.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://cloudresourcemanager.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Resource Manager API.</summary> public class Scope { /// <summary>See, edit, configure, and delete your Google Cloud Platform data</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>View your data across Google Cloud Platform services</summary> public static string CloudPlatformReadOnly = "https://www.googleapis.com/auth/cloud-platform.read-only"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Resource Manager API.</summary> public static class ScopeConstants { /// <summary>See, edit, configure, and delete your Google Cloud Platform data</summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>View your data across Google Cloud Platform services</summary> public const string CloudPlatformReadOnly = "https://www.googleapis.com/auth/cloud-platform.read-only"; } /// <summary>Gets the Organizations resource.</summary> public virtual OrganizationsResource Organizations { get; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for CloudResourceManager requests.</summary> public abstract class CloudResourceManagerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudResourceManagerBaseServiceRequest instance.</summary> protected CloudResourceManagerBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudResourceManager parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "organizations" collection of methods.</summary> public class OrganizationsResource { private const string Resource = "organizations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OrganizationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Fetches an Organization resource identified by the specified resource name.</summary> /// <param name="name"> /// The resource name of the Organization to fetch. This is the organization's relative path in the API, /// formatted as "organizations/[organizationId]". For example, "organizations/1234". /// </param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Fetches an Organization resource identified by the specified resource name.</summary> public class GetRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Organization> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// The resource name of the Organization to fetch. This is the organization's relative path in the API, /// formatted as "organizations/[organizationId]". For example, "organizations/1234". /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary> /// The id of the Organization resource to fetch. This field is deprecated and will be removed in v1. Use /// name instead. /// </summary> [Google.Apis.Util.RequestParameterAttribute("organizationId", Google.Apis.Util.RequestParameterType.Query)] public virtual string OrganizationId { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^organizations/[^/]+$", }); RequestParameters.Add("organizationId", new Google.Apis.Discovery.Parameter { Name = "organizationId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Gets the access control policy for an Organization resource. May be empty if no such policy or resource /// exists. The `resource` field should be the organization's resource name, e.g. "organizations/123". /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy is being requested. See the operation documentation for the /// appropriate value for this field. /// </param> public virtual GetIamPolicyRequest GetIamPolicy(Google.Apis.CloudResourceManager.v1beta1.Data.GetIamPolicyRequest body, string resource) { return new GetIamPolicyRequest(service, body, resource); } /// <summary> /// Gets the access control policy for an Organization resource. May be empty if no such policy or resource /// exists. The `resource` field should be the organization's resource name, e.g. "organizations/123". /// </summary> public class GetIamPolicyRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Policy> { /// <summary>Constructs a new GetIamPolicy request.</summary> public GetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.GetIamPolicyRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy is being requested. See the operation documentation for the /// appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.GetIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "getIamPolicy"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+resource}:getIamPolicy"; /// <summary>Initializes GetIamPolicy parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^organizations/[^/]+$", }); } } /// <summary> /// Lists Organization resources that are visible to the user and satisfy the specified filter. This method /// returns Organizations in an unspecified order. New Organizations do not necessarily appear at the end of the /// list. /// </summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary> /// Lists Organization resources that are visible to the user and satisfy the specified filter. This method /// returns Organizations in an unspecified order. New Organizations do not necessarily appear at the end of the /// list. /// </summary> public class ListRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.ListOrganizationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// An optional query string used to filter the Organizations to return in the response. Filter rules are /// case-insensitive. Organizations may be filtered by `owner.directoryCustomerId` or by `domain`, where the /// domain is a G Suite domain, for example: * Filter `owner.directorycustomerid:123456789` returns /// Organization resources with `owner.directory_customer_id` equal to `123456789`. * Filter /// `domain:google.com` returns Organization resources corresponding to the domain `google.com`. This field /// is optional. /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// The maximum number of Organizations to return in the response. This field is optional. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A pagination token returned from a previous call to `ListOrganizations` that indicates from where /// listing should continue. This field is optional. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/organizations"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Sets the access control policy on an Organization resource. Replaces any existing policy. The `resource` /// field should be the organization's resource name, e.g. "organizations/123". /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy is being specified. See the operation documentation for the /// appropriate value for this field. /// </param> public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CloudResourceManager.v1beta1.Data.SetIamPolicyRequest body, string resource) { return new SetIamPolicyRequest(service, body, resource); } /// <summary> /// Sets the access control policy on an Organization resource. Replaces any existing policy. The `resource` /// field should be the organization's resource name, e.g. "organizations/123". /// </summary> public class SetIamPolicyRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Policy> { /// <summary>Constructs a new SetIamPolicy request.</summary> public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.SetIamPolicyRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy is being specified. See the operation documentation for the /// appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.SetIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "setIamPolicy"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+resource}:setIamPolicy"; /// <summary>Initializes SetIamPolicy parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^organizations/[^/]+$", }); } } /// <summary> /// Returns permissions that a caller has on the specified Organization. The `resource` field should be the /// organization's resource name, e.g. "organizations/123". /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for /// the appropriate value for this field. /// </param> public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsRequest body, string resource) { return new TestIamPermissionsRequest(service, body, resource); } /// <summary> /// Returns permissions that a caller has on the specified Organization. The `resource` field should be the /// organization's resource name, e.g. "organizations/123". /// </summary> public class TestIamPermissionsRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsResponse> { /// <summary>Constructs a new TestIamPermissions request.</summary> public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy detail is being requested. See the operation documentation /// for the appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "testIamPermissions"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+resource}:testIamPermissions"; /// <summary>Initializes TestIamPermissions parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^organizations/[^/]+$", }); } } /// <summary>Updates an Organization resource identified by the specified resource name.</summary> /// <param name="body">The body of the request.</param> /// <param name="name"> /// Output only. The resource name of the organization. This is the organization's relative path in the API. Its /// format is "organizations/[organization_id]". For example, "organizations/1234". /// </param> public virtual UpdateRequest Update(Google.Apis.CloudResourceManager.v1beta1.Data.Organization body, string name) { return new UpdateRequest(service, body, name); } /// <summary>Updates an Organization resource identified by the specified resource name.</summary> public class UpdateRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Organization> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.Organization body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary> /// Output only. The resource name of the organization. This is the organization's relative path in the API. /// Its format is "organizations/[organization_id]". For example, "organizations/1234". /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.Organization Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "update"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PUT"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/{+name}"; /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^organizations/[^/]+$", }); } } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Creates a Project resource. Initially, the Project resource is owned by its creator exclusively. The creator /// can later grant permission to others to read or update the Project. Several APIs are activated automatically /// for the Project, including Google Cloud Storage. The parent is identified by a specified ResourceId, which /// must include both an ID and a type, such as project, folder, or organization. This method does not associate /// the new project with a billing account. You can set or update the billing account associated with a project /// using the [`projects.updateBillingInfo`] (/billing/reference/rest/v1/projects/updateBillingInfo) method. /// </summary> /// <param name="body">The body of the request.</param> public virtual CreateRequest Create(Google.Apis.CloudResourceManager.v1beta1.Data.Project body) { return new CreateRequest(service, body); } /// <summary> /// Creates a Project resource. Initially, the Project resource is owned by its creator exclusively. The creator /// can later grant permission to others to read or update the Project. Several APIs are activated automatically /// for the Project, including Google Cloud Storage. The parent is identified by a specified ResourceId, which /// must include both an ID and a type, such as project, folder, or organization. This method does not associate /// the new project with a billing account. You can set or update the billing account associated with a project /// using the [`projects.updateBillingInfo`] (/billing/reference/rest/v1/projects/updateBillingInfo) method. /// </summary> public class CreateRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Project> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.Project body) : base(service) { Body = body; InitParameters(); } /// <summary>A now unused experiment opt-out option.</summary> [Google.Apis.Util.RequestParameterAttribute("useLegacyStack", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> UseLegacyStack { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.Project Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("useLegacyStack", new Google.Apis.Discovery.Parameter { Name = "useLegacyStack", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Marks the Project identified by the specified `project_id` (for example, `my-project-123`) for deletion. /// This method will only affect the Project if it has a lifecycle state of ACTIVE. This method changes the /// Project's lifecycle state from ACTIVE to DELETE_REQUESTED. The deletion starts at an unspecified time, at /// which point the project is no longer accessible. Until the deletion completes, you can check the lifecycle /// state checked by retrieving the Project with GetProject, and the Project remains visible to ListProjects. /// However, you cannot update the project. After the deletion completes, the Project is not retrievable by the /// GetProject and ListProjects methods. The caller must have delete permissions for this Project. /// </summary> /// <param name="projectId">The Project ID (for example, `foo-bar-123`).</param> public virtual DeleteRequest Delete(string projectId) { return new DeleteRequest(service, projectId); } /// <summary> /// Marks the Project identified by the specified `project_id` (for example, `my-project-123`) for deletion. /// This method will only affect the Project if it has a lifecycle state of ACTIVE. This method changes the /// Project's lifecycle state from ACTIVE to DELETE_REQUESTED. The deletion starts at an unspecified time, at /// which point the project is no longer accessible. Until the deletion completes, you can check the lifecycle /// state checked by retrieving the Project with GetProject, and the Project remains visible to ListProjects. /// However, you cannot update the project. After the deletion completes, the Project is not retrievable by the /// GetProject and ListProjects methods. The caller must have delete permissions for this Project. /// </summary> public class DeleteRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string projectId) : base(service) { ProjectId = projectId; InitParameters(); } /// <summary>The Project ID (for example, `foo-bar-123`).</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{projectId}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Retrieves the Project identified by the specified `project_id` (for example, `my-project-123`). The caller /// must have read permissions for this Project. /// </summary> /// <param name="projectId">Required. The Project ID (for example, `my-project-123`).</param> public virtual GetRequest Get(string projectId) { return new GetRequest(service, projectId); } /// <summary> /// Retrieves the Project identified by the specified `project_id` (for example, `my-project-123`). The caller /// must have read permissions for this Project. /// </summary> public class GetRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Project> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string projectId) : base(service) { ProjectId = projectId; InitParameters(); } /// <summary>Required. The Project ID (for example, `my-project-123`).</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{projectId}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Gets a list of ancestors in the resource hierarchy for the Project identified by the specified `project_id` /// (for example, `my-project-123`). The caller must have read permissions for this Project. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">Required. The Project ID (for example, `my-project-123`).</param> public virtual GetAncestryRequest GetAncestry(Google.Apis.CloudResourceManager.v1beta1.Data.GetAncestryRequest body, string projectId) { return new GetAncestryRequest(service, body, projectId); } /// <summary> /// Gets a list of ancestors in the resource hierarchy for the Project identified by the specified `project_id` /// (for example, `my-project-123`). The caller must have read permissions for this Project. /// </summary> public class GetAncestryRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.GetAncestryResponse> { /// <summary>Constructs a new GetAncestry request.</summary> public GetAncestryRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.GetAncestryRequest body, string projectId) : base(service) { ProjectId = projectId; Body = body; InitParameters(); } /// <summary>Required. The Project ID (for example, `my-project-123`).</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.GetAncestryRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "getAncestry"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{projectId}:getAncestry"; /// <summary>Initializes GetAncestry parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Returns the IAM access control policy for the specified Project. Permission is denied if the policy or the /// resource does not exist. For additional information about resource structure and identification, see /// [Resource Names](/apis/design/resource_names). /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy is being requested. See the operation documentation for the /// appropriate value for this field. /// </param> public virtual GetIamPolicyRequest GetIamPolicy(Google.Apis.CloudResourceManager.v1beta1.Data.GetIamPolicyRequest body, string resource) { return new GetIamPolicyRequest(service, body, resource); } /// <summary> /// Returns the IAM access control policy for the specified Project. Permission is denied if the policy or the /// resource does not exist. For additional information about resource structure and identification, see /// [Resource Names](/apis/design/resource_names). /// </summary> public class GetIamPolicyRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Policy> { /// <summary>Constructs a new GetIamPolicy request.</summary> public GetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.GetIamPolicyRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy is being requested. See the operation documentation for the /// appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.GetIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "getIamPolicy"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{resource}:getIamPolicy"; /// <summary>Initializes GetIamPolicy parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Lists Projects that the caller has the `resourcemanager.projects.get` permission on and satisfy the /// specified filter. This method returns Projects in an unspecified order. This method is eventually consistent /// with project mutations; this means that a newly created project may not appear in the results or recent /// updates to an existing project may not be reflected in the results. To retrieve the latest state of a /// project, use the GetProject method. NOTE: If the request filter contains a `parent.type` and `parent.id` and /// the caller has the `resourcemanager.projects.list` permission on the parent, the results will be drawn from /// an alternate index which provides more consistent results. In future versions of this API, this List method /// will be split into List and Search to properly capture the behavioral difference. /// </summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary> /// Lists Projects that the caller has the `resourcemanager.projects.get` permission on and satisfy the /// specified filter. This method returns Projects in an unspecified order. This method is eventually consistent /// with project mutations; this means that a newly created project may not appear in the results or recent /// updates to an existing project may not be reflected in the results. To retrieve the latest state of a /// project, use the GetProject method. NOTE: If the request filter contains a `parent.type` and `parent.id` and /// the caller has the `resourcemanager.projects.list` permission on the parent, the results will be drawn from /// an alternate index which provides more consistent results. In future versions of this API, this List method /// will be split into List and Search to properly capture the behavioral difference. /// </summary> public class ListRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.ListProjectsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// An expression for filtering the results of the request. Filter rules are case insensitive. If multiple /// fields are included in a filter query, the query will return results that match any of the fields. Some /// eligible fields for filtering are: + `name` + `id` + `labels.` (where *key* is the name of a label) + /// `parent.type` + `parent.id` Some examples of using labels as filters: | Filter | Description | /// |------------------|-----------------------------------------------------| | name:how* | The project's /// name starts with "how". | | name:Howl | The project's name is `Howl` or `howl`. | | name:HOWL | /// Equivalent to above. | | NAME:howl | Equivalent to above. | | labels.color:* | The project has the label /// `color`. | | labels.color:red | The project's label `color` has the value `red`. | | labels.color:red /// labels.size:big |The project's label `color` has the value `red` and its label `size` has the value /// `big`. | If no filter is specified, the call will return projects for which the user has the /// `resourcemanager.projects.get` permission. NOTE: To perform a by-parent query (eg., what projects are /// directly in a Folder), the caller must have the `resourcemanager.projects.list` permission on the parent /// and the filter must contain both a `parent.type` and a `parent.id` restriction (example: /// "parent.type:folder parent.id:123"). In this case an alternate search index is used which provides more /// consistent results. Optional. /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// The maximum number of Projects to return in the response. The server can return fewer Projects than /// requested. If unspecified, server picks an appropriate default. Optional. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A pagination token returned from a previous call to ListProjects that indicates from where listing /// should continue. Optional. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Sets the IAM access control policy for the specified Project. CAUTION: This method will replace the existing /// policy, and cannot be used to append additional IAM settings. NOTE: Removing service accounts from policies /// or changing their roles can render services completely inoperable. It is important to understand how the /// service account is being used before removing or updating its roles. The following constraints apply when /// using `setIamPolicy()`: + Project does not support `allUsers` and `allAuthenticatedUsers` as `members` in a /// `Binding` of a `Policy`. + The owner role can be granted to a `user`, `serviceAccount`, or a group that is /// part of an organization. For example, group@myownpersonaldomain.com could be added as an owner to a project /// in the myownpersonaldomain.com organization, but not the examplepetstore.com organization. + Service /// accounts can be made owners of a project directly without any restrictions. However, to be added as an /// owner, a user must be invited via Cloud Platform console and must accept the invitation. + A user cannot be /// granted the owner role using `setIamPolicy()`. The user must be granted the owner role using the Cloud /// Platform Console and must explicitly accept the invitation. + Invitations to grant the owner role cannot be /// sent using `setIamPolicy()`; they must be sent only using the Cloud Platform Console. + Membership changes /// that leave the project without any owners that have accepted the Terms of Service (ToS) will be rejected. + /// If the project is not part of an organization, there must be at least one owner who has accepted the Terms /// of Service (ToS) agreement in the policy. Calling `setIamPolicy()` to remove the last ToS-accepted owner /// from the policy will fail. This restriction also applies to legacy projects that no longer have owners who /// have accepted the ToS. Edits to IAM policies will be rejected until the lack of a ToS-accepting owner is /// rectified. Authorization requires the Google IAM permission `resourcemanager.projects.setIamPolicy` on the /// project /// </summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy is being specified. See the operation documentation for the /// appropriate value for this field. /// </param> public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CloudResourceManager.v1beta1.Data.SetIamPolicyRequest body, string resource) { return new SetIamPolicyRequest(service, body, resource); } /// <summary> /// Sets the IAM access control policy for the specified Project. CAUTION: This method will replace the existing /// policy, and cannot be used to append additional IAM settings. NOTE: Removing service accounts from policies /// or changing their roles can render services completely inoperable. It is important to understand how the /// service account is being used before removing or updating its roles. The following constraints apply when /// using `setIamPolicy()`: + Project does not support `allUsers` and `allAuthenticatedUsers` as `members` in a /// `Binding` of a `Policy`. + The owner role can be granted to a `user`, `serviceAccount`, or a group that is /// part of an organization. For example, group@myownpersonaldomain.com could be added as an owner to a project /// in the myownpersonaldomain.com organization, but not the examplepetstore.com organization. + Service /// accounts can be made owners of a project directly without any restrictions. However, to be added as an /// owner, a user must be invited via Cloud Platform console and must accept the invitation. + A user cannot be /// granted the owner role using `setIamPolicy()`. The user must be granted the owner role using the Cloud /// Platform Console and must explicitly accept the invitation. + Invitations to grant the owner role cannot be /// sent using `setIamPolicy()`; they must be sent only using the Cloud Platform Console. + Membership changes /// that leave the project without any owners that have accepted the Terms of Service (ToS) will be rejected. + /// If the project is not part of an organization, there must be at least one owner who has accepted the Terms /// of Service (ToS) agreement in the policy. Calling `setIamPolicy()` to remove the last ToS-accepted owner /// from the policy will fail. This restriction also applies to legacy projects that no longer have owners who /// have accepted the ToS. Edits to IAM policies will be rejected until the lack of a ToS-accepting owner is /// rectified. Authorization requires the Google IAM permission `resourcemanager.projects.setIamPolicy` on the /// project /// </summary> public class SetIamPolicyRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Policy> { /// <summary>Constructs a new SetIamPolicy request.</summary> public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.SetIamPolicyRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy is being specified. See the operation documentation for the /// appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.SetIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "setIamPolicy"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{resource}:setIamPolicy"; /// <summary>Initializes SetIamPolicy parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Returns permissions that a caller has on the specified Project.</summary> /// <param name="body">The body of the request.</param> /// <param name="resource"> /// REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for /// the appropriate value for this field. /// </param> public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsRequest body, string resource) { return new TestIamPermissionsRequest(service, body, resource); } /// <summary>Returns permissions that a caller has on the specified Project.</summary> public class TestIamPermissionsRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsResponse> { /// <summary>Constructs a new TestIamPermissions request.</summary> public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsRequest body, string resource) : base(service) { Resource = resource; Body = body; InitParameters(); } /// <summary> /// REQUIRED: The resource for which the policy detail is being requested. See the operation documentation /// for the appropriate value for this field. /// </summary> [Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)] public virtual string Resource { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.TestIamPermissionsRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "testIamPermissions"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{resource}:testIamPermissions"; /// <summary>Initializes TestIamPermissions parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter { Name = "resource", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Restores the Project identified by the specified `project_id` (for example, `my-project-123`). You can only /// use this method for a Project that has a lifecycle state of DELETE_REQUESTED. After deletion starts, the /// Project cannot be restored. The caller must have undelete permissions for this Project. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">Required. The project ID (for example, `foo-bar-123`).</param> public virtual UndeleteRequest Undelete(Google.Apis.CloudResourceManager.v1beta1.Data.UndeleteProjectRequest body, string projectId) { return new UndeleteRequest(service, body, projectId); } /// <summary> /// Restores the Project identified by the specified `project_id` (for example, `my-project-123`). You can only /// use this method for a Project that has a lifecycle state of DELETE_REQUESTED. After deletion starts, the /// Project cannot be restored. The caller must have undelete permissions for this Project. /// </summary> public class UndeleteRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Empty> { /// <summary>Constructs a new Undelete request.</summary> public UndeleteRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.UndeleteProjectRequest body, string projectId) : base(service) { ProjectId = projectId; Body = body; InitParameters(); } /// <summary>Required. The project ID (for example, `foo-bar-123`).</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.UndeleteProjectRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "undelete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{projectId}:undelete"; /// <summary>Initializes Undelete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Updates the attributes of the Project identified by the specified `project_id` (for example, /// `my-project-123`). The caller must have modify permissions for this Project. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="projectId">The project ID (for example, `my-project-123`).</param> public virtual UpdateRequest Update(Google.Apis.CloudResourceManager.v1beta1.Data.Project body, string projectId) { return new UpdateRequest(service, body, projectId); } /// <summary> /// Updates the attributes of the Project identified by the specified `project_id` (for example, /// `my-project-123`). The caller must have modify permissions for this Project. /// </summary> public class UpdateRequest : CloudResourceManagerBaseServiceRequest<Google.Apis.CloudResourceManager.v1beta1.Data.Project> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudResourceManager.v1beta1.Data.Project body, string projectId) : base(service) { ProjectId = projectId; Body = body; InitParameters(); } /// <summary>The project ID (for example, `my-project-123`).</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProjectId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudResourceManager.v1beta1.Data.Project Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "update"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PUT"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1beta1/projects/{projectId}"; /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.CloudResourceManager.v1beta1.Data { /// <summary>Identifying information for a single ancestor of a project.</summary> public class Ancestor : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Resource id of the ancestor.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resourceId")] public virtual ResourceId ResourceId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Specifies the audit configuration for a service. The configuration determines which permission types are logged, /// and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If /// there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used /// for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each /// AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service": /// "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ] /// }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com", /// "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [ /// "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ /// logging. It also exempts jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging. /// </summary> public class AuditConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The configuration for logging of each type of permission.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")] public virtual System.Collections.Generic.IList<AuditLogConfig> AuditLogConfigs { get; set; } /// <summary> /// Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, /// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("service")] public virtual string Service { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type": /// "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables /// 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ logging. /// </summary> public class AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Specifies the identities that do not cause logging for this type of permission. Follows the same format of /// Binding.members. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")] public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; } /// <summary>The log type that this config enables.</summary> [Newtonsoft.Json.JsonPropertyAttribute("logType")] public virtual string LogType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Associates `members` with a `role`.</summary> public class Binding : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding /// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to /// the current request. However, a different role binding might grant the same role to one or more of the /// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("condition")] public virtual Expr Condition { get; set; } /// <summary> /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following /// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a /// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated /// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific /// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that /// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: /// An email address that represents a Google group. For example, `admins@example.com`. * /// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that /// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is /// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * /// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a /// service account that has been recently deleted. For example, /// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, /// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the /// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing /// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. /// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role /// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that /// domain. For example, `google.com` or `example.com`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("members")] public virtual System.Collections.Generic.IList<string> Members { get; set; } /// <summary> /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata describing a long running folder operation</summary> public class CloudresourcemanagerGoogleCloudResourcemanagerV2alpha1FolderOperation : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The resource name of the folder or organization we are either creating the folder under or moving the folder /// to. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("destinationParent")] public virtual string DestinationParent { get; set; } /// <summary>The display name of the folder.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The type of this operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operationType")] public virtual string OperationType { get; set; } /// <summary> /// The resource name of the folder's parent. Only applicable when the operation_type is MOVE. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceParent")] public virtual string SourceParent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata describing a long running folder operation</summary> public class CloudresourcemanagerGoogleCloudResourcemanagerV2beta1FolderOperation : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The resource name of the folder or organization we are either creating the folder under or moving the folder /// to. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("destinationParent")] public virtual string DestinationParent { get; set; } /// <summary>The display name of the folder.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The type of this operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operationType")] public virtual string OperationType { get; set; } /// <summary> /// The resource name of the folder's parent. Only applicable when the operation_type is MOVE. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceParent")] public virtual string SourceParent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Runtime operation information for creating a TagKey.</summary> public class CreateTagKeyMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Runtime operation information for creating a TagValue.</summary> public class CreateTagValueMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Runtime operation information for deleting a TagKey.</summary> public class DeleteTagKeyMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Runtime operation information for deleting a TagValue.</summary> public class DeleteTagValueMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression /// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example /// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" /// expression: "document.summary.size() &amp;lt; 100" Example (Equality): title: "Requestor is owner" description: /// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" /// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly /// visible" expression: "document.type != 'private' &amp;amp;&amp;amp; document.type != 'internal'" Example (Data /// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." /// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that /// may be referenced within an expression are determined by the service that evaluates it. See the service /// documentation for additional information. /// </summary> public class Expr : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when /// hovered over it in a UI. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Textual representation of an expression in Common Expression Language syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expression")] public virtual string Expression { get; set; } /// <summary> /// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a /// position in the file. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary> /// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs /// which allow to enter the expression. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata describing a long running folder operation</summary> public class FolderOperation : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The resource name of the folder or organization we are either creating the folder under or moving the folder /// to. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("destinationParent")] public virtual string DestinationParent { get; set; } /// <summary>The display name of the folder.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The type of this operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operationType")] public virtual string OperationType { get; set; } /// <summary> /// The resource name of the folder's parent. Only applicable when the operation_type is MOVE. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sourceParent")] public virtual string SourceParent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A classification of the Folder Operation error.</summary> public class FolderOperationError : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The type of operation error experienced.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorMessageId")] public virtual string ErrorMessageId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The request sent to the [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetAncestry] method. /// </summary> public class GetAncestryRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response from the projects.getAncestry method.</summary> public class GetAncestryResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Ancestors are ordered from bottom to top of the resource hierarchy. The first ancestor is the project /// itself, followed by the project's parent, etc. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("ancestor")] public virtual System.Collections.Generic.IList<Ancestor> Ancestor { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for `GetIamPolicy` method.</summary> public class GetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("options")] public virtual GetPolicyOptions Options { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Encapsulates settings provided to GetIamPolicy.</summary> public class GetPolicyOptions : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests specifying an /// invalid value will be rejected. Requests for policies with any conditional bindings must specify version 3. /// Policies without any conditional bindings may specify any valid value or leave the field unset. To learn /// which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestedPolicyVersion")] public virtual System.Nullable<int> RequestedPolicyVersion { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response returned from the `ListOrganizations` method.</summary> public class ListOrganizationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A pagination token to be used to retrieve the next page of results. If the result is too large to fit within /// the page size specified in the request, this field will be set with a token that can be used to fetch the /// next page of results. If this field is empty, it indicates that this response contains the last page of /// results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of Organizations that matched the list query, possibly paginated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("organizations")] public virtual System.Collections.Generic.IList<Organization> Organizations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A page of the response received from the ListProjects method. A paginated response where more pages are /// available has `next_page_token` set. This token can be used in a subsequent request to retrieve the next request /// page. /// </summary> public class ListProjectsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Pagination token. If the result set is too large to fit in a single response, this token is returned. It /// encodes the position of the current result cursor. Feeding this value into a new list request with the /// `page_token` parameter gives the next page of the results. When `next_page_token` is not filled in, there is /// no next page and the list returned is the last page in the result set. Pagination tokens have a limited /// lifetime. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of Projects that matched the list filter. This list can be paginated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projects")] public virtual System.Collections.Generic.IList<Project> Projects { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The root node in the resource hierarchy to which a particular entity's (e.g., company) resources belong. /// </summary> public class Organization : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Timestamp when the Organization was created. Assigned by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("creationTime")] public virtual object CreationTime { get; set; } /// <summary> /// A human-readable string that refers to the Organization in the GCP Console UI. This string is set by the /// server and cannot be changed. The string will be set to the primary domain (for example, "google.com") of /// the G Suite customer that owns the organization. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The organization's current lifecycle state. Assigned by the server.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lifecycleState")] public virtual string LifecycleState { get; set; } /// <summary> /// Output only. The resource name of the organization. This is the organization's relative path in the API. Its /// format is "organizations/[organization_id]". For example, "organizations/1234". /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// An immutable id for the Organization that is assigned on creation. This should be omitted when creating a /// new Organization. This field is read-only. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("organizationId")] public virtual string OrganizationId { get; set; } /// <summary> /// The owner of this Organization. The owner should be specified on creation. Once set, it cannot be changed. /// This field is required. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("owner")] public virtual OrganizationOwner Owner { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The entity that owns an Organization. The lifetime of the Organization and all of its descendants are bound to /// the `OrganizationOwner`. If the `OrganizationOwner` is deleted, the Organization and all its descendants will be /// deleted. /// </summary> public class OrganizationOwner : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The G Suite customer id used in the Directory API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("directoryCustomerId")] public virtual string DirectoryCustomerId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A /// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can /// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of /// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google /// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to /// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of /// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the /// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { /// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", /// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, /// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { /// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time /// &amp;lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** /// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - /// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - /// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable /// access description: Does not grant access after Sep 2020 expression: request.time &amp;lt; /// timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a description of IAM and its /// features, see the [IAM documentation](https://cloud.google.com/iam/docs/). /// </summary> public class Policy : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Specifies cloud audit logging configuration for this policy.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")] public virtual System.Collections.Generic.IList<AuditConfig> AuditConfigs { get; set; } /// <summary> /// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and /// when the `bindings` are applied. Each of the `bindings` must contain at least one member. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("bindings")] public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; } /// <summary> /// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy /// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the /// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned /// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to /// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:** /// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit /// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the /// conditions in the version `3` policy are lost. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("etag")] public virtual string ETag { get; set; } /// <summary> /// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid /// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This /// requirement applies to the following operations: * Getting a policy that includes a conditional role binding /// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing /// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you /// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this /// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the /// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on /// that policy may specify any valid version or leave the field unset. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual System.Nullable<int> Version { get; set; } } /// <summary> /// A Project is a high-level Google Cloud Platform entity. It is a container for ACLs, APIs, App Engine Apps, VMs, /// and other Google Cloud Platform resources. /// </summary> public class Project : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Creation time. Read-only.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary> /// The labels associated with this Project. Label keys must be between 1 and 63 characters long and must /// conform to the following regular expression: a-z{0,62}. Label values must be between 0 and 63 characters /// long and must conform to the regular expression [a-z0-9_-]{0,63}. A label value can be empty. No more than /// 256 labels can be associated with a given resource. Clients should store labels in a representation such as /// JSON that does not depend on specific characters being disallowed. Example: `"environment" : "dev"` /// Read-write. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; } /// <summary>The Project lifecycle state. Read-only.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lifecycleState")] public virtual string LifecycleState { get; set; } /// <summary> /// The optional user-assigned display name of the Project. When present it must be between 4 to 30 characters. /// Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, /// and exclamation point. Example: `My Project` Read-write. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// An optional reference to a parent Resource. Supported parent types include "organization" and "folder". Once /// set, the parent cannot be cleared. The `parent` can be set on creation or using the `UpdateProject` method; /// the end user must have the `resourcemanager.projects.create` permission on the parent. Read-write. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("parent")] public virtual ResourceId Parent { get; set; } /// <summary> /// The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters, digits, or hyphens. It /// must start with a letter. Trailing hyphens are prohibited. Example: `tokyo-rain-123` Read-only after /// creation. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary>The number uniquely identifying the project. Example: `415104041262` Read-only.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectNumber")] public virtual System.Nullable<long> ProjectNumber { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A status object which is used as the `metadata` field for the Operation returned by CreateProject. It provides /// insight for when significant phases of Project creation have completed. /// </summary> public class ProjectCreationStatus : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Creation time of the project creation workflow.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary> /// True if the project can be retrieved using GetProject. No other operations on the project are guaranteed to /// work until the project creation is complete. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("gettable")] public virtual System.Nullable<bool> Gettable { get; set; } /// <summary>True if the project creation process is complete.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ready")] public virtual System.Nullable<bool> Ready { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// A container to reference an id for any resource type. A `resource` in Google Cloud Platform is a generic term /// for something you (a developer) may want to interact with through one of our API's. Some examples are an App /// Engine app, a Compute Engine instance, a Cloud SQL database, and so on. /// </summary> public class ResourceId : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required field for the type-specific id. This should correspond to the id used in the type-specific API's. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary> /// Required field representing the resource type this id is for. At present, the valid types are "project", /// "folder", and "organization". /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for `SetIamPolicy` method.</summary> public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few /// 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might /// reject them. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("policy")] public virtual Policy Policy { get; set; } /// <summary> /// OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be /// modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("updateMask")] public virtual object UpdateMask { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for `TestIamPermissions` method.</summary> public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') /// are not allowed. For more information see [IAM /// Overview](https://cloud.google.com/iam/docs/overview#permissions). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("permissions")] public virtual System.Collections.Generic.IList<string> Permissions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for `TestIamPermissions` method.</summary> public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("permissions")] public virtual System.Collections.Generic.IList<string> Permissions { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The request sent to the UndeleteProject method.</summary> public class UndeleteProjectRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Runtime operation information for updating a TagKey.</summary> public class UpdateTagKeyMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Runtime operation information for updating a TagValue.</summary> public class UpdateTagValueMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
52.317202
200
0.633131
[ "Apache-2.0" ]
DanFTRX/google-api-dotnet-client
Src/Generated/Google.Apis.CloudResourceManager.v1beta1/Google.Apis.CloudResourceManager.v1beta1.cs
109,186
C#
using SerializedObjectTest; using System.Collections; using System.Collections.Generic; using UnityEngine; //Testing the serialized object (armor class) public class SerializedObjectDropdownTestPlayer : MonoBehaviour { public SerializedObjectDatabaseTest database; //Testing Primitive type [Dropdown("database.PlayerNameList")] public string PlayerName; //Testing instance variable [Dropdown("database.HelmetDataList", "Name")] public HelmetData Helmet; //Testing collection item [Dropdown("database.ChestplateDataList", "MaterialTypeList[0].MaterialName")] public ChestplateData Chestplate; //Testing method return [Dropdown("database.LeggingsDataList", "GetFirstMaterialName()")] public LeggingsData Leggings; //Testing [float], [string], [instance variable] and [Enum] with [method] as arguments public string publicArrow = " ===> ";//private static string privateStaticArrow = " ---> ";//Test private static arrow [Dropdown("database.BootsDataList", "GetMaterialAt(0).GetMaterialNameWithPrefix(\"Material \").Insert(8, publicArrow ).Insert(0, \" \").Insert(0, Rareness.COMMON.ToString())")] public BootsData Boots; public void DisplayPlayerData() { Debug.Log($"I am {PlayerName}"); Debug.Log($"I am wearing {Helmet?.Name}"); Debug.Log($"I am wearing {Chestplate?.Name}"); Debug.Log($"I am wearing {Leggings?.Name}"); Debug.Log($"I am wearing {Boots?.Name}"); } private void Start() { DisplayPlayerData(); } }
34.955556
183
0.687858
[ "MIT" ]
SilvinWillemsen/ModularPhysModVR
Assets/DropdownAttributes/Example (Remove this)/Scripts/SerializedObjectTest/SerializedObjectDropdownTestPlayer.cs
1,575
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 cloudsearchdomain-2013-01-01.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.CloudSearchDomain; using Amazon.CloudSearchDomain.Model; using Amazon.CloudSearchDomain.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using Amazon.Util; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public partial class CloudSearchDomainMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("cloudsearchdomain-2013-01-01.normal.json", "cloudsearchdomain.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("CloudSearchDomain")] public void SearchMarshallTest() { var operation = service_model.FindOperation("Search"); var request = InstantiateClassGenerator.Execute<SearchRequest>(); var marshaller = new SearchRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("Search", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = SearchResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as SearchResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("CloudSearchDomain")] public void SuggestMarshallTest() { var operation = service_model.FindOperation("Suggest"); var request = InstantiateClassGenerator.Execute<SuggestRequest>(); var marshaller = new SuggestRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("Suggest", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = SuggestResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as SuggestResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("CloudSearchDomain")] public void UploadDocumentsMarshallTest() { var operation = service_model.FindOperation("UploadDocuments"); var request = InstantiateClassGenerator.Execute<UploadDocumentsRequest>(); var marshaller = new UploadDocumentsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UploadDocuments", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UploadDocumentsResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UploadDocumentsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
42.137681
161
0.656406
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/test/UnitTests/Generated/Marshalling/CloudSearchDomainMarshallingTests.cs
5,815
C#
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.DynamicProxy.Tests.GenClasses { using System.Collections.Generic; public abstract class ClassWithMethodWithArrayOfListOfT { public virtual void GenericMethodWithListArrayArgument<T>(List<T>[] action) { } } }
36.625
87
0.745165
[ "Apache-2.0" ]
belav/Core
src/Castle.Core.Tests/DynamicProxy.Tests/GenClasses/ClassWithMethodWithArrayOfListOfT.cs
879
C#
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Studio.V1.Flow.Engagement { /// <summary> /// Retrieve a list of all Steps for an Engagement. /// </summary> public class ReadStepOptions : ReadOptions<StepResource> { /// <summary> /// The SID of the Flow /// </summary> public string PathFlowSid { get; } /// <summary> /// The SID of the Engagement /// </summary> public string PathEngagementSid { get; } /// <summary> /// Construct a new ReadStepOptions /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathEngagementSid"> The SID of the Engagement </param> public ReadStepOptions(string pathFlowSid, string pathEngagementSid) { PathFlowSid = pathFlowSid; PathEngagementSid = pathEngagementSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// Retrieve a Step. /// </summary> public class FetchStepOptions : IOptions<StepResource> { /// <summary> /// The SID of the Flow /// </summary> public string PathFlowSid { get; } /// <summary> /// The SID of the Engagement /// </summary> public string PathEngagementSid { get; } /// <summary> /// The SID that identifies the resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchStepOptions /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathEngagementSid"> The SID of the Engagement </param> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> public FetchStepOptions(string pathFlowSid, string pathEngagementSid, string pathSid) { PathFlowSid = pathFlowSid; PathEngagementSid = pathEngagementSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
30.231579
93
0.546657
[ "MIT" ]
BrimmingDev/twilio-csharp
src/Twilio/Rest/Studio/V1/Flow/Engagement/StepOptions.cs
2,872
C#
using System.Collections.Generic; using System.Xml.Serialization; using Niue.Alipay.Domain; namespace Niue.Alipay.Response { /// <summary> /// MybankFinanceYulibaoPriceQueryResponse. /// </summary> public class MybankFinanceYulibaoPriceQueryResponse : AopResponse { /// <summary> /// 余利宝行情信息列表 /// </summary> [XmlArray("ylb_price_detail_infos")] [XmlArrayItem("y_l_b_price_detail_info")] public List<YLBPriceDetailInfo> YlbPriceDetailInfos { get; set; } } }
26.6
73
0.671053
[ "MIT" ]
P79N6A/abp-ant-design-pro-vue
Niue.Alipay/Response/MybankFinanceYulibaoPriceQueryResponse.cs
552
C#
namespace AssassinsCreedApp.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Genre")] public partial class Genre { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Genre() { Games = new HashSet<Game>(); } public int GenreId { get; set; } [Required] [StringLength(50)] public string GenreType { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Game> Games { get; set; } } }
29.892857
128
0.673835
[ "Apache-2.0" ]
GeorgeCimpoies/OOP-Repo
Assignments/AssassinsCreedApp/AssassinsCreedApp/Models/Genre.cs
837
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.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal interface IFindUsagesService : ILanguageService { /// <summary> /// Finds the references for the symbol at the specific position in the document, /// pushing the results into the context instance. /// </summary> Task FindReferencesAsync(Document document, int position, IFindUsagesContext context); /// <summary> /// Finds the implementations for the symbol at the specific position in the document, /// pushing the results into the context instance. /// </summary> Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context); } }
41.125
161
0.715299
[ "Apache-2.0" ]
20chan/roslyn
src/EditorFeatures/Core/FindUsages/IFindUsagesService.cs
989
C#
using BenchmarkDotNet.Attributes; using static Suckless.Asserts.Assertions; using Code = Seterlund.CodeGuard; using Seterlund.CodeGuard; using Dawn; using ArgumentAssertions.Generic; namespace Suckless.Asserts.Benchmark { public class CompareToOtherLibrieresTest { [Benchmark] public void DawnGuard() { var value = "any"; Dawn.Guard.Argument(value).NotNull().NotEmpty(); } [Benchmark] public void CodeGuardAssert() { var value = "any"; Code.Guard.That(value).IsNotNull().IsNotEmpty(); } [Benchmark] public void SucklessAssert() { var value = "any"; Assert(value).NotEmpty(); } [Benchmark] public void DawnGuardValueType() { var value = 0; Dawn.Guard.Argument(value).Zero(); } [Benchmark] public void CodeGuardAssertValueType() { var value = 1; Code.Guard.That(value).IsNotDefault(); } [Benchmark] public void SucklessAssertValueType() { var value = 0; Assert(value).Zero(); } [Benchmark] public void DawnGuardLambda() { var value = "any"; Dawn.Guard.Argument(() => value).NotNull().NotEmpty(); } [Benchmark] public void CodeGuardLambda() { var value = "any"; Code.Guard.That(() => value).IsNotNull().IsNotEmpty(); } [Benchmark] public void ArgumentAssertionsLambda() { var value = "any"; value.ThrowIf(() => value).Null().OrIf.EqualTo("sdfs"); } [Benchmark] public void SucklessAssertLambda() { var value = "any"; Assert(() => value).NotEmpty(); } [Benchmark] public void CodeGuardAssertLambdaNestedProperty() { var value = new PropsFieldsSut(); Code.Guard.That(() => value.Prop).IsNotNull().IsNotEmpty(); } [Benchmark] public void SucklessAssertLambdaNestedProperty() { var value = new PropsFieldsSut(); Assert(() => value.Prop).NotEmpty(); } } }
21.614679
71
0.514007
[ "MIT" ]
Ja-rek/Suckless.Assert
Suckless.Asserts.Benchmark/CompareToOtherLibriaresTest.cs
2,356
C#
using Loop54.User; using System; using System.Collections.Generic; namespace Loop54 { /// <summary> /// A client info that returns null values for all user-specific metadata such as Id, Referrer, etc. /// Useful for implementing engine requests where there is no context, such as batch jobs. /// </summary> public class NullClientInfo : IRemoteClientInfo { public Dictionary<string, string> Headers { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public string GetRequestHeader(string name) { if (Headers.TryGetValue(name, out string value)) return value; return null; } private Dictionary<string, string> _cookies = new Dictionary<string, string>(); public string GetCookie(string name) { if (_cookies.TryGetValue(name, out string value)) return value; return null; } public void SetCookie(string name, string value, DateTime expiryTime) { _cookies[name] = value; } public string Referrer { get; set; } = null; public string GetReferrer() => Referrer; public string UserAgent { get; set; } = null; public string GetUserAgent() => UserAgent; public string RemoteIp { get; set; } = null; public string GetRemoteIp() => RemoteIp; } }
28.156863
131
0.614206
[ "BSD-3-Clause" ]
LoopFiftyFour/.NET-Connector
Loop54.Shared/NullClientInfo.cs
1,436
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using BetfairNG; using BetfairNG.Data; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using BF_API.CacheManager; using BF_API.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using BF_API.Data.Engine; namespace BF_API { public static class BFMarketBook { [FunctionName("BFMarketBook")] public async static Task<BetfairServerResponse<List<MarketBook>>> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation("BFMarketBook BetFair API accessed, Date:" + new DateTime().ToString()); var marketId = req.Query["marketId"].ToString(); var marketIds = new List<string>() { marketId }; var apiConfig = new ApiConfig(context); log.LogInformation(""); return await apiConfig.BetfairClient.ListMarketBook( marketIds, new PriceProjection() { Virtualise = true, PriceData = new HashSet<PriceData>() { PriceData.SP_AVAILABLE, PriceData.SP_TRADED, PriceData.EX_TRADED, PriceData.EX_BEST_OFFERS, PriceData.EX_ALL_OFFERS } }, null); } } }
35.673913
235
0.68312
[ "MIT" ]
gareth-reid/BetsFriends
BF_API/SearchApi/BFMarketBook.cs
1,641
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Configuration; namespace KeepWifiConnected { class Program { static int timeRecheck = 0; static int timeoutRequest = 0; static string fileLogName = @""; static string urlRequest = @""; static void Main() { if (!SetConfig()) { Log("Errors in .config"); Thread.Sleep(10000); return; } Log("Start"); while (true) { string wifiNetworkName = GetWifiNetworkName(); if (wifiNetworkName.Length > 1) { Log("Wifi Network: " + wifiNetworkName); if (IsInternetOn()) { Log("Internet ON"); } else { Log("Internet OFF"); WifiReconnect(); Log("Reconnection"); } } else { Log("No Wifi Network"); } Thread.Sleep(timeRecheck); } } static string GetWifiNetworkName() { try { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"netsh.exe"; p.StartInfo.Arguments = @"wlan show interfaces"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); string s = p.StandardOutput.ReadToEnd(); if (s.IndexOf("SSID") < 0) return ""; string s1 = s.Substring(s.IndexOf("SSID")); s1 = s1.Substring(s1.IndexOf(":")); s1 = s1.Substring(2, s1.IndexOf("\n")).Trim(); p.WaitForExit(); return s1; } catch { return ""; } } static bool IsInternetOn() { try { WebRequest myWebRequest = WebRequest.Create(urlRequest); myWebRequest.Timeout = timeoutRequest; using (WebResponse myWebResponse = myWebRequest.GetResponse()) { return true; } } catch { return false; } } static void WifiConnect(string networkName) { try { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"netsh.exe"; p.StartInfo.Arguments = @"wlan connect name = """ + networkName + @""; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); } catch { } } static void WifiDisconnect() { try { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"netsh.exe"; p.StartInfo.Arguments = @"wlan disconnect"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); } catch { } } static void WifiReconnect() { try { string wifiNetworkName = GetWifiNetworkName(); if (wifiNetworkName.Length > 1) { WifiDisconnect(); WifiConnect(wifiNetworkName); } } catch { } } static void Log(string message) { try { string content = DateTime.Now + ": " + message; Console.WriteLine(content); if (fileLogName.Trim() != "") { string fileLogPath = Path.Combine(Directory.GetCurrentDirectory(), fileLogName); File.AppendAllText(fileLogPath, content); File.AppendAllText(fileLogPath, Environment.NewLine); } } catch { } } static bool SetConfig() { timeRecheck = Convert.ToInt32(ConfigurationManager.AppSettings["TimeRecheck"]); timeoutRequest = Convert.ToInt32(ConfigurationManager.AppSettings["TimeoutRequest"]); fileLogName = ConfigurationManager.AppSettings["FileLogName"]; urlRequest = ConfigurationManager.AppSettings["UrlRequest"]; if (timeRecheck == 0 || timeoutRequest == 0 || urlRequest == "" || urlRequest == null) { return false; } return true; } } }
31.04
101
0.439249
[ "Apache-2.0" ]
And96/KeepWifiConnected
KeepWifiConnected/Program.cs
5,434
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 cloudsearchdomain-2013-01-01.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudSearchDomain.Model; namespace Amazon.CloudSearchDomain { /// <summary> /// Interface for accessing CloudSearchDomain /// /// You use the AmazonCloudSearch2013 API to upload documents to a search domain and search /// those documents. /// /// /// <para> /// The endpoints for submitting <code>UploadDocuments</code>, <code>Search</code>, and /// <code>Suggest</code> requests are domain-specific. To get the endpoints for your domain, /// use the Amazon CloudSearch configuration service <code>DescribeDomains</code> action. /// The domain endpoints are also displayed on the domain dashboard in the Amazon CloudSearch /// console. You submit suggest requests to the search endpoint. /// </para> /// /// <para> /// For more information, see the <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide">Amazon /// CloudSearch Developer Guide</a>. /// </para> /// </summary> public partial interface IAmazonCloudSearchDomain : IDisposable { #region Search /// <summary> /// Initiates the asynchronous execution of the Search operation. /// <seealso cref="Amazon.CloudSearchDomain.IAmazonCloudSearchDomain"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Search operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SearchResponse> SearchAsync(SearchRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Suggest /// <summary> /// Initiates the asynchronous execution of the Suggest operation. /// <seealso cref="Amazon.CloudSearchDomain.IAmazonCloudSearchDomain"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Suggest operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SuggestResponse> SuggestAsync(SuggestRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UploadDocuments /// <summary> /// Initiates the asynchronous execution of the UploadDocuments operation. /// <seealso cref="Amazon.CloudSearchDomain.IAmazonCloudSearchDomain"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UploadDocuments operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UploadDocumentsResponse> UploadDocumentsAsync(UploadDocumentsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
42.441176
157
0.675676
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_WinRT/Amazon.CloudSearchDomain/IAmazonCloudSearchDomain.cs
4,329
C#
using System; using System.Text; using JetBrains.Annotations; using RestSharp.Extensions.MonoHttp; namespace WebsitePoller.FormRegistrator { public static class StringBuilderExtensions { [NotNull] public static StringBuilder AppendParameter( [NotNull]this StringBuilder builder, [NotNull]string name, [NotNull]string value, bool isFirst = false) { if(builder == null) throw new ArgumentNullException(nameof(builder)); if(name == null) throw new ArgumentNullException(nameof(name)); if(string.IsNullOrWhiteSpace(name)) throw new ArgumentException("May not be a white space.", nameof(name)); if(value == null) throw new ArgumentNullException(nameof(value)); var result = AppendParameterInternal(builder, name, value, isFirst); return result; } [NotNull] private static StringBuilder AppendParameterInternal( [NotNull] this StringBuilder builder, [NotNull] string name, [NotNull] string value, bool isFirst) { var encodedValue = HttpUtility.UrlEncode(value); if (!isFirst) builder.Append("&"); return builder.AppendFormat("tx_sozaltbau_pi1[{0}]={1}", name, encodedValue); } } }
36.184211
119
0.617455
[ "MIT" ]
MovGP0/WebsitePoller
WebsitePoller/FormRegistrator/StringBuilderExtensions.cs
1,377
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Powershell - NotificationHubs")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure Powershell")] [assembly: AssemblyCopyright("Copyright © Microsoft")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: Guid("9e93b969-6685-4a67-b07d-cfd5ebd0091e")] [assembly: AssemblyVersion("4.1.0")] [assembly: AssemblyFileVersion("4.1.0")] #if SIGN [assembly: InternalsVisibleTo("Microsoft.Azure.Commands.NotificationHubs.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #else [assembly: InternalsVisibleTo("Microsoft.Azure.Commands.NotificationHubs.Test")] #endif
52.857143
413
0.732432
[ "MIT" ]
fgasperij/azure-powershell
src/ResourceManager/NotificationHubs/Commands.NotificationHubs/Properties/AssemblyInfo.cs
1,817
C#