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 |
|---|---|---|---|---|---|---|---|---|
/* MIT License
Copyright (c) 2017 Uvi Vagabond, UnityBerserkers
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.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityBerserkersGizmos;
[ExecuteInEditMode]
public class Box2DRayIntersection : MonoBehaviour
{
[Header ("Definition of Ray")]
[SerializeField]Vector3 origin;
[SerializeField]Vector3 direction;
[Space (44)]
[SerializeField]float distance = 1;
RaycastHit2D hitByRayCast;
[Space (55)][Header ("Results:")]
[SerializeField]bool isSomethingHit;
void Update ()
{
isSomethingHit = Physics2D.GetRayIntersection (ray: new Ray (origin: origin, direction: direction), distance: distance);
}
void OnDrawGizmos ()
{
GizmosForPhysics2D.DrawGetRayIntersection (ray: new Ray (origin: origin, direction: direction), distance: distance);
}
}
| 36.46 | 122 | 0.787713 | [
"MIT"
] | uvivagabond/Visualization-of-physics-in-Unity | Assets/Scripts/Test Scripts For Box2D/Box2DRayIntersection.cs | 1,825 | C# |
//-----------------------------------------------------------------------
// <copyright file="TableCreate4Tests.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
//-----------------------------------------------------------------------
namespace InteropApiTests
{
using System;
using System.Runtime.InteropServices;
using Microsoft.Isam.Esent.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Test conversion to NATIVE_TABLECREATE4
/// </summary>
[TestClass]
public class TableCreate4Tests
{
/// <summary>
/// Managed version of the indexcreate structure.
/// </summary>
private JET_TABLECREATE managed;
/// <summary>
/// The native conditional column structure created from the JET_TABLECREATE
/// object.
/// </summary>
private NATIVE_TABLECREATE4 native;
/// <summary>
/// Setup the test fixture. This creates a native structure and converts
/// it to a managed object.
/// </summary>
[TestInitialize]
[Description("Initialize the TableCreate4Tests fixture")]
public void Setup()
{
JET_TABLEID tableidTemp = new JET_TABLEID()
{
Value = (IntPtr)456,
};
this.managed = new JET_TABLECREATE()
{
szTableName = "table7",
szTemplateTableName = "parentTable",
ulPages = 7,
ulDensity = 63,
rgcolumncreate = null,
cColumns = 0,
rgindexcreate = null,
cIndexes = 0,
szCallback = "module!FunkyFunction",
cbtyp = JET_cbtyp.AfterReplace,
grbit = CreateTableColumnIndexGrbit.FixedDDL,
pSeqSpacehints = null,
pLVSpacehints = null,
cbSeparateLV = 0x999,
tableid = tableidTemp,
cCreated = 3,
};
this.native = this.managed.GetNativeTableCreate4();
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets the structure size.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets the structure size.")]
public void VerifyConversionToNativeSetsCbStruct()
{
Assert.AreEqual((uint)Marshal.SizeOf(this.native), this.native.cbStruct);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets the table name.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets the table name.")]
public void VerifyConversionToNativeSetsName()
{
Assert.AreEqual("table7", this.native.szTableName);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets szTemplateTableName.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets szTemplateTableName.")]
public void VerifyConversionToNativeSetsSzTemplateTableName()
{
Assert.AreEqual("parentTable", this.native.szTemplateTableName);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets ulPages.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets ulPages.")]
public void VerifyConversionToNativeSetsUlPages()
{
Assert.AreEqual<uint>(7, this.native.ulPages);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets ulDensity.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets ulDensity.")]
public void VerifyConversionToNativeSetsUlDensity()
{
Assert.AreEqual<uint>(63, this.native.ulDensity);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets rgcolumncreate.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets rgcolumncreate.")]
public unsafe void VerifyConversionToNativeSetsRgcolumncreate()
{
Assert.IsTrue(this.native.rgcolumncreate == null);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets cColumns.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets cColumns.")]
public void VerifyConversionToNativeSetsCColumns()
{
Assert.AreEqual<uint>(0, this.native.cColumns);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets rgindexcreate.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets rgindexcreate.")]
public void VerifyConversionToNativeSetsRgindexcreate()
{
Assert.AreEqual(this.native.rgindexcreate, IntPtr.Zero);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets cIndexes.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets cIndexes.")]
public void VerifyConversionToNativeSetsCIndexes()
{
Assert.AreEqual<uint>(0, this.native.cIndexes);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets szCallback.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets szCallback.")]
public void VerifyConversionToNativeSetsSzCallback()
{
Assert.AreEqual("module!FunkyFunction", this.native.szCallback);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets cbtyp.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets cbtyp.")]
public void VerifyConversionToNativeSetsCbtyp()
{
Assert.AreEqual(0x10 /*JET_cbtyp.AfterReplace*/, (int)this.native.cbtyp);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets pSeqSpacehints.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets pSeqSpacehints.")]
public unsafe void VerifyConversionToNativeSetsPSeqSpacehints()
{
Assert.IsTrue(this.native.pSeqSpacehints == null);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets pLVSpacehints.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets pLVSpacehints.")]
public unsafe void VerifyConversionToNativeSetPpLVSpacehints()
{
// Set at pinvoke time.
Assert.IsTrue(null == this.native.pLVSpacehints);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets cbSeparateLV.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets cbSeparateLV.")]
public void VerifyConversionToNativeSetsCbSeparateLV()
{
Assert.AreEqual<uint>(0x999, this.native.cbSeparateLV);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets tableid.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets tableid.")]
public void VerifyConversionToNativeSetsTableid()
{
Assert.AreEqual<IntPtr>((IntPtr)456, this.native.tableid);
}
/// <summary>
/// Check the conversion to a NATIVE_TABLECREATE4 sets cCreated.
/// </summary>
[TestMethod]
[Priority(0)]
[Description("Check the conversion from JET_TABLECREATE to a NATIVE_TABLECREATE4 sets cCreated.")]
public void VerifyConversionToNativeSetsCCreated()
{
Assert.AreEqual<uint>(3, this.native.cCreated);
}
/// <summary>
/// Check that CheckMembersAreValid catches negative cColumns.
/// </summary>
[TestMethod]
[Priority(0)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Check that CheckMembersAreValid catches negative cColumns.")]
public void VerifyValidityCatchesNegativeCColumns()
{
var x = new JET_TABLECREATE()
{
rgcolumncreate = null,
cColumns = -1,
};
var y = new JET_TABLECREATE();
Assert.IsFalse(x.ContentEquals(y));
}
/// <summary>
/// Check that CheckMembersAreValid catches negative cIndexes.
/// </summary>
[TestMethod]
[Priority(0)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Check that CheckMembersAreValid catches negative cIndexes.")]
public void VerifyValidityCatchesNegativeCIndexes()
{
var x = new JET_TABLECREATE()
{
rgcolumncreate = null,
cIndexes = -1,
};
var y = new JET_TABLECREATE();
Assert.IsFalse(x.ContentEquals(y));
}
/// <summary>
/// Check that CheckMembersAreValid catches cIndexes that's too big.
/// </summary>
[TestMethod]
[Priority(0)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Check that CheckMembersAreValid catches cIndexes that's too big.")]
public void VerifyValidityCatchesCIndexesTooBig()
{
var x = new JET_TABLECREATE()
{
rgindexcreate = new JET_INDEXCREATE[]
{
new JET_INDEXCREATE(),
new JET_INDEXCREATE(),
},
cIndexes = 10,
};
var y = new JET_TABLECREATE();
Assert.IsFalse(x.ContentEquals(y));
}
/// <summary>
/// Check that CheckMembersAreValid catches cColumns that's too big.
/// </summary>
[TestMethod]
[Priority(0)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Check that CheckMembersAreValid catches cColumns that's too big.")]
public void VerifyValidityCatchesCColumnsTooBig()
{
var x = new JET_TABLECREATE()
{
rgcolumncreate = new JET_COLUMNCREATE[]
{
new JET_COLUMNCREATE(),
new JET_COLUMNCREATE(),
},
cColumns = 10,
};
var y = new JET_TABLECREATE();
Assert.IsFalse(x.ContentEquals(y));
}
/// <summary>
/// Check that CheckMembersAreValid catches non-zero cColumns when the array is null.
/// </summary>
[TestMethod]
[Priority(0)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Check that CheckMembersAreValid catches non-zero cColumns when the array is null.")]
public void VerifyValidityCatchesNonZeroCColumnsWithNullArray()
{
var x = new JET_TABLECREATE()
{
rgcolumncreate = null,
cColumns = 10,
};
x.CheckMembersAreValid();
}
/// <summary>
/// Check that CheckMembersAreValid catches non-zero cIndexes when the array is null.
/// </summary>
[TestMethod]
[Priority(0)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Description("Check that CheckMembersAreValid catches non-zero cIndexes when the array is null.")]
public void VerifyValidityCatchesNonZeroCIndexesWithNullArray()
{
var x = new JET_TABLECREATE()
{
rgindexcreate = null,
cIndexes = 10,
};
x.CheckMembersAreValid();
}
}
}
| 37.035912 | 118 | 0.566197 | [
"MIT"
] | Bhaskers-Blu-Org2/ManagedEsent | EsentInteropTests/TableCreate4Tests.cs | 13,407 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace SmartAdmin.WebUI.Pages.Page
{
public class ErrorModel : PageModel
{
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| 20.44 | 53 | 0.67319 | [
"MIT"
] | HybridSolutions/RazorPageCleanArchitecture | doc/templates/smartadmin-core-razor/src/SmartAdmin.WebUI/Pages/Page/Error.cshtml.cs | 511 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.Kubernetes.ResourceKinds;
namespace Microsoft.Kubernetes.Resources
{
public class CreatePatchParameters
{
public IResourceKind ResourceKind { get; set; }
public object ApplyResource { get; set; }
public object LastAppliedResource { get; set; }
public object LiveResource { get; set; }
}
}
| 26.6875 | 55 | 0.69555 | [
"MIT"
] | BennyM/reverse-proxy | src/OperatorFramework/src/Core/Resources/CreatePatchParameters.cs | 429 | 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Service.Gateway
{
using System.Runtime.Serialization;
[DataContract(Name = "Connection", Namespace = "http://schemas.microsoft.com/windowsazure")]
public class Connection : IExtensibleDataObject
{
[DataMember(Order = 1, EmitDefaultValue = false)]
public string ConnectivityState { get; set; }
[DataMember(Order = 2)]
public ulong EgressBytesTransferred { get; set; }
[DataMember(Order = 3)]
public ulong IngressBytesTransferred { get; set; }
[DataMember(Order = 4)]
public string LastConnectionEstablished { get; set; }
[DataMember(Order = 5)]
public GatewayEvent LastEvent { get; set; }
[DataMember(Order = 6)]
public string LocalNetworkSiteName { get; set; }
public ExtensionDataObject ExtensionData { get; set; }
}
}
| 39.348837 | 97 | 0.608156 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/ServiceManagement.Additions/Gateway/Connection.cs | 1,652 | C# |
namespace MassTransit.Containers.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GreenPipes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using TestFramework;
[TestFixture]
public class HealthCheck_Specs :
InMemoryTestFixture
{
[Test]
public async Task Should_be_degraded_after_stopping_a_connected_endpoint()
{
var collection = new ServiceCollection();
collection.AddSingleton<ILoggerFactory, NullLoggerFactory>();
collection.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
collection.AddMassTransit(configurator =>
{
configurator.AddBus(p => MassTransit.Bus.Factory.CreateUsingInMemory(cfg =>
{
cfg.UseHealthCheck(p);
cfg.ReceiveEndpoint("input-queue", e =>
{
e.UseMessageRetry(r => r.Immediate(5));
});
}));
})
.AddMassTransitHostedService();
IServiceProvider provider = collection.BuildServiceProvider(true);
var healthChecks = provider.GetService<HealthCheckService>();
var hostedServices = provider.GetRequiredService<IEnumerable<IHostedService>>();
await WaitForHealthStatus(healthChecks, HealthStatus.Unhealthy);
await Task.WhenAll(hostedServices.Select(x => x.StartAsync(TestCancellationToken)));
try
{
await WaitForHealthStatus(healthChecks, HealthStatus.Healthy);
var busControl = provider.GetRequiredService<IBusControl>();
var endpointHandle = busControl.ConnectReceiveEndpoint("another-queue", x =>
{
});
await endpointHandle.Ready;
await WaitForHealthStatus(healthChecks, HealthStatus.Healthy);
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await endpointHandle.StopAsync(false, stop.Token);
await WaitForHealthStatus(healthChecks, HealthStatus.Degraded);
}
finally
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await Task.WhenAll(hostedServices.Select(x => x.StopAsync(cts.Token)));
}
}
[Test]
public async Task Should_be_healthy_after_restarting()
{
var collection = new ServiceCollection();
collection.AddSingleton<ILoggerFactory, NullLoggerFactory>();
collection.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
collection.AddMassTransit(configurator =>
{
configurator.AddBus(p => MassTransit.Bus.Factory.CreateUsingInMemory(cfg =>
{
cfg.UseHealthCheck(p);
cfg.ReceiveEndpoint("input-queue", e =>
{
e.UseMessageRetry(r => r.Immediate(5));
});
}));
})
.AddMassTransitHostedService();
IServiceProvider provider = collection.BuildServiceProvider(true);
var healthChecks = provider.GetService<HealthCheckService>();
var hostedServices = provider.GetRequiredService<IEnumerable<IHostedService>>();
await WaitForHealthStatus(healthChecks, HealthStatus.Unhealthy);
await Task.WhenAll(hostedServices.Select(x => x.StartAsync(TestCancellationToken)));
try
{
await WaitForHealthStatus(healthChecks, HealthStatus.Healthy);
var busControl = provider.GetRequiredService<IBusControl>();
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await busControl.StopAsync(stop.Token);
await WaitForHealthStatus(healthChecks, HealthStatus.Unhealthy);
using var start = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await busControl.StartAsync(start.Token);
await WaitForHealthStatus(healthChecks, HealthStatus.Healthy);
}
finally
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await Task.WhenAll(hostedServices.Select(x => x.StopAsync(cts.Token)));
}
}
[Test]
public async Task Should_be_healthy_with_configured_receive_endpoints()
{
var collection = new ServiceCollection();
collection.AddSingleton<ILoggerFactory, NullLoggerFactory>();
collection.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
collection.AddMassTransit(configurator =>
{
configurator.AddBus(p => MassTransit.Bus.Factory.CreateUsingInMemory(cfg =>
{
cfg.UseHealthCheck(p);
cfg.ReceiveEndpoint("input-queue", e =>
{
e.UseMessageRetry(r => r.Immediate(5));
});
}));
})
.AddMassTransitHostedService();
IServiceProvider provider = collection.BuildServiceProvider(true);
var healthChecks = provider.GetService<HealthCheckService>();
var hostedServices = provider.GetRequiredService<IEnumerable<IHostedService>>();
var result = await healthChecks.CheckHealthAsync(TestCancellationToken);
Assert.That(result.Status == HealthStatus.Unhealthy);
await Task.WhenAll(hostedServices.Select(x => x.StartAsync(TestCancellationToken)));
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
do
{
result = await healthChecks.CheckHealthAsync(TestCancellationToken);
Console.WriteLine("Health Check: {0}", FormatHealthCheck(result));
await Task.Delay(100, TestCancellationToken);
}
while (result.Status == HealthStatus.Unhealthy);
Assert.That(result.Status == HealthStatus.Healthy);
}
finally
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await Task.WhenAll(hostedServices.Select(x => x.StopAsync(cts.Token)));
}
}
async Task WaitForHealthStatus(HealthCheckService healthChecks, HealthStatus expectedStatus)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
HealthReport result;
do
{
result = await healthChecks.CheckHealthAsync(TestCancellationToken);
await Task.Delay(100, TestCancellationToken);
}
while (result.Status != expectedStatus);
Assert.That(result.Status, Is.EqualTo(expectedStatus));
}
public string FormatHealthCheck(HealthReport result)
{
var json = new JObject(
new JProperty("status", result.Status.ToString()),
new JProperty("results", new JObject(result.Entries.Select(entry => new JProperty(entry.Key, new JObject(
new JProperty("status", entry.Value.Status.ToString()),
new JProperty("description", entry.Value.Description),
new JProperty("data", JObject.FromObject(entry.Value.Data))))))));
return json.ToString(Formatting.Indented);
}
}
}
| 38.205479 | 121 | 0.585873 | [
"ECL-2.0",
"Apache-2.0"
] | Excommunicated/MassTransit | tests/MassTransit.Containers.Tests/HealthCheck_Specs.cs | 8,367 | C# |
using Exasol.ErrorReporting;
using System;
namespace error_reporting_dotnet_tool_testproject
{
/// <summary>
/// This is a test project
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Don't pick this up");
//Case 1
Console.WriteLine("Something went wrong:" + ExaError.MessageBuilder("E-ECC-TEST-1").ToString());
//Case 2
var exaErrorString = ExaError.MessageBuilder("E-ECC-TEST-2").ToString();
//Case 3
var exaErrorObject1 = ExaError.MessageBuilder("E-ECC-TEST-3");
exaErrorObject1.Message("Woops! Something went wrong! 1");
//Case 4
var exaErrorObject2 = ExaError.MessageBuilder("E-ECC-TEST-4").Message("Woops! Something went wrong! 1");
var exaErrorObject3 = ExaError.MessageBuilder("E-ECC-TEST-4bis").Message("Woops! Something went wrong! 1").Message("Oh my! Something went wrong! 2"); ;
//
var exaErrorObjectMitigation1 = ExaError.MessageBuilder("E-ECC-TESTMIT-1").Message("Woops! Something went wrong!").Mitigation("Do something about it 1");
var exaErrorObjectMitigation2 = ExaError.MessageBuilder("E-ECC-TESTMIT-2").Message("Woops! Something went wrong!").Mitigation("Do something about it 1").Mitigation("Don't just sit there 2");
string somethingWentWrongValue = "Something went very wrong";
ExaError.MessageBuilder("E-ECC-TESTSI-1").Message($@"Woops! {somethingWentWrongValue}");
ExaError.MessageBuilder("E-ECC-TESTCONCAT-1").Message($@"Woops!" + "Woops!");
//TODO: maybe later, allow for this, add more robustness, check for context, identifiers ..
////mixed cases:
//var mixed1 = ExaError.MessageBuilder("E-ECC-MIXED-1");
//var mixed2 = ExaError.MessageBuilder("E-ECC-MIXED-2");
//mixed1.Message("Add something afterwards 1");
//mixed2.Message("Add something afterwards 2");
}
}
}
| 49 | 202 | 0.628766 | [
"MIT"
] | exasol/error-crawler-csharp | error-reporting-dotnet-tool-testproject/Program.cs | 2,060 | C# |
using System;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Duality;
using Duality.Editor.Properties;
using Duality.Editor.Forms;
using Duality.Editor.PackageManagement;
namespace Duality.Editor
{
internal static class Program
{
private const string DualityMainLicenseUrl = @"https://github.com/AdamsLair/duality/raw/master/LICENSE";
private static StreamWriter logfileWriter;
private static TextWriterLogOutput logfileOutput;
private static bool recoverFromPluginReload;
[STAThread]
private static void Main(string[] args)
{
// Parse command line arguments
ParseCommandLineArguments(args);
// Culture setup
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
// Set up a text logfile
ArchiveOldLogfile();
CreateLogfile();
// Winforms Setup
PrepareWinFormsApplication();
// Restore or remove packages to match package config
if (!VerifyPackageSetup())
{
Application.Exit();
return;
}
// Run the editor
SplashScreen splashScreen = new SplashScreen(recoverFromPluginReload);
splashScreen.Show();
Application.Run();
// Clean up the log file
CloseLogfile();
}
private static void ParseCommandLineArguments(string[] args)
{
recoverFromPluginReload = false;
foreach (string argument in args)
{
if (argument == "debug")
System.Diagnostics.Debugger.Launch();
else if (argument == "recover")
recoverFromPluginReload = true;
}
}
private static void PrepareWinFormsApplication()
{
Application.CurrentCulture = Thread.CurrentThread.CurrentCulture;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private static bool VerifyPackageSetup()
{
PackageManager packageManager = new PackageManager();
// On the first install startup, display a generic license agreement for Duality
if (packageManager.LocalSetup.IsFirstInstall)
{
LicenseAcceptDialog licenseDialog = new LicenseAcceptDialog
{
DescriptionText = GeneralRes.LicenseAcceptDialog_FirstStartGeneric,
LicenseUrl = new Uri(DualityMainLicenseUrl)
};
DialogResult result = licenseDialog.ShowDialog();
if (result != DialogResult.OK)
return false;
}
// Perform the initial package update - even before initializing the editor
if (packageManager.IsPackageSyncRequired)
{
Logs.Editor.Write("Synchronizing Local Package Setup...");
Logs.Editor.PushIndent();
ProcessingBigTaskDialog setupDialog = new ProcessingBigTaskDialog(
GeneralRes.TaskInstallPackages_Caption,
GeneralRes.TaskInstallPackages_Desc,
SynchronizePackages,
packageManager);
setupDialog.ShowInTaskbar = true;
setupDialog.MainThreadRequired = false;
setupDialog.ShowDialog();
Logs.Editor.PopIndent();
}
// Restart to apply the update. This will also trigger when there is a pending
// update from before that wasn't applied yet.
if (packageManager.ApplyUpdate())
{
return false;
}
// If we have nothing to apply, but still require a sync, something went wrong.
// Should this happen on our first start, we'll remind the user that the install
// requires an internet connection and refuse to start.
else if (packageManager.IsPackageSyncRequired && packageManager.LocalSetup.IsFirstInstall)
{
DialogResult result = MessageBox.Show(
GeneralRes.Msg_ErrorFirstDualityInstall_Desc,
GeneralRes.Msg_ErrorFirstDualityInstall_Caption,
MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
return true;
}
private static IEnumerable SynchronizePackages(ProcessingBigTaskDialog.WorkerInterface workerInterface)
{
PackageManager manager = workerInterface.Data as PackageManager;
// Set the working state and yield, so the UI can update properly in case we're in the main thread
workerInterface.Progress = 0.0f;
workerInterface.StateDesc = GeneralRes.TaskPrepareInfo;
yield return null;
// Retrieve all registered Duality packages and sort them so we don't accidentally install an old dependency
LocalPackage[] packagesToVerify = manager.LocalSetup.Packages.ToArray();
manager.OrderByDependencies(packagesToVerify);
yield return null;
// Uninstall all "shadow" Duality packages that are installed, but not registered
Logs.Editor.Write("Removing unregistered packages...");
Logs.Editor.PushIndent();
manager.UninstallNonRegisteredPackages();
Logs.Editor.PopIndent();
yield return null;
// Iterate over previously reigstered local packages and verify / install them.
Logs.Editor.Write("Verifying registered packages...");
Logs.Editor.PushIndent();
foreach (LocalPackage package in packagesToVerify)
{
// Update the task dialog's UI
if (package.Version != null)
workerInterface.StateDesc = string.Format("Package '{0}', Version {1}...", package.Id, package.Version);
else
workerInterface.StateDesc = string.Format("Package '{0}'...", package.Id);
workerInterface.Progress += 0.5f / packagesToVerify.Length;
yield return null;
// Verify / Install the local package as needed
try
{
manager.VerifyPackage(package);
}
catch (Exception e)
{
Logs.Editor.WriteError("An error occurred verifying Package '{0}', Version {1}: {2}",
package.Id,
package.Version,
LogFormat.Exception(e));
}
workerInterface.Progress += 0.5f / packagesToVerify.Length;
yield return null;
}
Logs.Editor.PopIndent();
yield break;
}
private static void ArchiveOldLogfile()
{
try
{
// If there is an existing logfile, archive it for diagnostic purposes
FileInfo prevLogfile = new FileInfo(DualityEditorApp.EditorLogfilePath);
if (prevLogfile.Exists)
{
if (!Directory.Exists(DualityEditorApp.EditorPrevLogfileDir))
Directory.CreateDirectory(DualityEditorApp.EditorPrevLogfileDir);
string timestampToken = prevLogfile.LastWriteTimeUtc.ToString("yyyy-MM-dd-T-HH-mm-ss");
string prevLogfileName = string.Format(DualityEditorApp.EditorPrevLogfileName, timestampToken);
string prevLogFilePath = Path.Combine(DualityEditorApp.EditorPrevLogfileDir, prevLogfileName);
prevLogfile.MoveTo(prevLogFilePath);
}
}
catch (Exception e)
{
Logs.Core.WriteWarning("Unable to archive old logfile: {0}", LogFormat.Exception(e));
}
}
private static void CreateLogfile()
{
if (logfileOutput != null || logfileWriter != null)
CloseLogfile();
try
{
logfileWriter = new StreamWriter(DualityEditorApp.EditorLogfilePath);
logfileWriter.AutoFlush = true;
logfileOutput = new TextWriterLogOutput(logfileWriter);
Logs.AddGlobalOutput(logfileOutput);
}
catch (Exception e)
{
Logs.Core.WriteWarning("Unable to create logfile: {0}", LogFormat.Exception(e));
}
}
private static void CloseLogfile()
{
if (logfileOutput != null)
{
Logs.RemoveGlobalOutput(logfileOutput);
logfileOutput = null;
}
if (logfileWriter != null)
{
logfileWriter.Flush();
logfileWriter.Close();
logfileWriter = null;
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Logs.Editor.WriteError(LogFormat.Exception(e.ExceptionObject as Exception));
}
catch (Exception) { /* Ensure we're not causing any further exception by logging... */ }
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
Logs.Editor.WriteError(LogFormat.Exception(e.Exception));
}
catch (Exception) { /* Ensure we're not causing any further exception by logging... */ }
}
}
}
| 31.391473 | 111 | 0.728979 | [
"MIT"
] | Limeless04/duality | Source/Editor/DualityEditor/Program.cs | 8,101 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Discord.Addons.Core
{
internal static class RWEx
{
[DebuggerStepThrough]
internal static AcquiredReadLock UsingReadLock(this ReaderWriterLockSlim readerWriterLock)
=> new AcquiredReadLock(readerWriterLock);
[DebuggerStepThrough]
internal static AcquiredWriteLock UsingWriteLock(this ReaderWriterLockSlim readerWriterLock)
=> new AcquiredWriteLock(readerWriterLock);
[DebuggerStepThrough]
internal static async Task<AcquiredSemaphoreSlim> UsingSemaphore(this SemaphoreSlim semaphore)
{
await semaphore.WaitAsync().ConfigureAwait(false);
return new AcquiredSemaphoreSlim(semaphore);
}
internal readonly struct AcquiredReadLock : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
[DebuggerStepThrough]
public AcquiredReadLock(ReaderWriterLockSlim @lock)
{
_lock = @lock;
_lock.EnterReadLock();
}
[DebuggerStepThrough]
void IDisposable.Dispose() => _lock.ExitReadLock();
}
internal readonly struct AcquiredWriteLock : IDisposable
{
private readonly ReaderWriterLockSlim _lock;
[DebuggerStepThrough]
public AcquiredWriteLock(ReaderWriterLockSlim @lock)
{
_lock = @lock;
_lock.EnterWriteLock();
}
[DebuggerStepThrough]
void IDisposable.Dispose() => _lock.ExitWriteLock();
}
internal readonly struct AcquiredSemaphoreSlim : IDisposable
{
private readonly SemaphoreSlim _semaphore;
[DebuggerStepThrough]
public AcquiredSemaphoreSlim(SemaphoreSlim semaphore)
{
_semaphore = semaphore;
}
[DebuggerStepThrough]
void IDisposable.Dispose() => _semaphore.Release();
}
}
}
| 31.939394 | 102 | 0.620019 | [
"MIT"
] | NeKzor/Discord.Addons | src/Discord.Addons.Core/RWEx.cs | 2,110 | C# |
using BEPUphysics.CollisionTests.CollisionAlgorithms;
using BEPUutilities.ResourceManagement;
namespace BEPUphysics.CollisionTests.Manifolds
{
public class TerrainSphereContactManifold : TerrainContactManifold
{
static LockingResourcePool<TriangleSpherePairTester> testerPool = new LockingResourcePool<TriangleSpherePairTester>();
protected override TrianglePairTester GetTester()
{
return testerPool.Take();
}
protected override void GiveBackTester(TrianglePairTester tester)
{
testerPool.GiveBack((TriangleSpherePairTester)tester);
}
}
}
| 30.285714 | 126 | 0.731132 | [
"MIT"
] | Ramobo/ge | src/BEPU/BEPUphysics/CollisionTests/Manifolds/TerrainSphereContactManifold.cs | 638 | C# |
#nullable disable
using System;
using System.Collections.Generic;
namespace RayCarrot.RCP.Metro;
/// <summary>
/// The Rayman 2 Demo 1 game info
/// </summary>
public sealed class GameInfo_Rayman2Demo1 : GameInfo_BaseRayman2Demo
{
#region Public Override Properties
/// <summary>
/// The game
/// </summary>
public override Games Game => Games.Demo_Rayman2_1;
/// <summary>
/// The game display name
/// </summary>
public override string DisplayName => "Rayman 2 Demo (1999/08/18)";
/// <summary>
/// The download URLs for the game if it can be downloaded. All sources must be compressed.
/// </summary>
public override IList<Uri> DownloadURLs => new Uri[]
{
new Uri(AppURLs.Games_R2Demo1_Url),
};
#endregion
} | 23.909091 | 95 | 0.656527 | [
"MIT"
] | RayCarrot/Rayman-Control-Panel-Metro | src/RayCarrot.RCP.Metro/Games/Info/Demo/GameInfo_Rayman2Demo1.cs | 791 | C# |
using System.Text.Json.Serialization;
namespace Going.Plaid.Entity
{
/// <summary>
/// Represents a user being identified during a call to generate a <c>link_token</c>.
/// </summary>
public class User
{
/// <summary>
/// Plaid requires that the endpoint used to create a <c>link_token</c> only be available to users that are logged in to your app.
/// Once your user is logged in, pass an identifier that uniquely identifies your user into the <see cref="ClientUserId"/> field.
/// The value of this id should not be personally identifiable information like an email or phone number.
///
/// Using <see cref="ClientUserId"/> will allow for easier debugging in the Dashboard logs.
/// You will be able to search for Link logs that belong to one of your end users.
/// </summary>
[JsonPropertyName("client_user_id")]
public string ClientUserId { get; init; } = null!;
}
}
| 40.954545 | 133 | 0.711432 | [
"MIT"
] | grcodemonkey/Going.Plaid | src/Plaid/Entity/User.cs | 903 | C# |
using System.Linq;
using NUnit.Framework;
using Unity.Collections;
using Unity.PerformanceTesting;
using UnityEngine;
namespace Unity.Serialization.Json.PerformanceTests
{
[TestFixture]
[Category("Performance")]
class PackedBinaryWriterPerformanceTests
{
JsonTokenizer m_Tokenizer;
[SetUp]
public void SetUp()
{
m_Tokenizer = new JsonTokenizer(Allocator.Persistent);
}
[TearDown]
public void TearDown()
{
m_Tokenizer.Dispose();
}
#if UNITY_2019_2_OR_NEWER
[Test, Performance]
#else
[PerformanceTest]
#endif
[TestCase(1000)]
[TestCase(10000)]
public unsafe void PerformanceTest_PackedBinaryWriter_Write_MockEntities(int count)
{
var json = JsonTestData.GetMockEntities(count);
fixed (char* ptr = json)
{
m_Tokenizer.Write(new UnsafeBuffer<char>(ptr, json.Length), 0, json.Length);
}
Measure.Method(() =>
{
using (var stream = new PackedBinaryStream(Allocator.TempJob))
using (var writer = new PackedBinaryWriter(stream, m_Tokenizer, Allocator.TempJob))
{
fixed (char* ptr = json)
{
writer.Write(new UnsafeBuffer<char>(ptr, json.Length), m_Tokenizer.TokenNextIndex);
}
}
})
.WarmupCount(1)
.MeasurementCount(100)
.Run();
PerformanceTest.Active.CalculateStatisticalValues();
var size = json.Length / (double) 1024 / 1024;
Debug.Log($"MB/s=[{size / (PerformanceTest.Active.SampleGroups.First().Median / 1000)}]");
}
}
}
| 29.707692 | 114 | 0.527188 | [
"Apache-2.0"
] | bsides44/MARSGeofencing | MARS geofencing/Library/PackageCache/com.unity.serialization@1.5.0-preview/Tests/Runtime/Unity.Serialization.PerformanceTests/Json/Parsing/PackedBinaryWriterPerformanceTests.cs | 1,931 | C# |
using System;
using OpenLogger.Extensions;
namespace OpenLogger
{
public class LogEventArgs : EventArgs
{
public LogEventArgs(LogSeverity severity, string origin, int groupId, string message, Exception exception, DateTime timestamp, object dataObject)
{
Severity = severity;
Origin = origin;
GroupId = groupId;
Message = message;
Exception = exception;
Timestamp = timestamp;
DataObject = dataObject;
}
public LogSeverity Severity { get; private set; }
public string Origin { get; private set; }
public int GroupId { get; private set; }
public string Message { get; private set; }
public Exception Exception { get; private set; }
public DateTime Timestamp { get; private set; }
public object DataObject { get; private set; }
public string SeverityString
{
get { return Severity.ToString("G"); }
}
public override string ToString()
{
return Timestamp + ": " + Origin + " - (" + SeverityString + ") " + Message + Exception.IfNotNull(x => " - " + x.Message) + " [" + DataObject.GetType() + "]";
}
}
}
| 33.810811 | 171 | 0.580336 | [
"MIT"
] | mtnman1010/OpenLogger | OpenLogger/LogEventArgs.cs | 1,253 | C# |
#if !NETSTANDARD13
/*
* 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 backup-2018-11-15.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.Backup.Model
{
/// <summary>
/// Paginator for the ListRecoveryPointsByResource operation
///</summary>
public interface IListRecoveryPointsByResourcePaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListRecoveryPointsByResourceResponse> Responses { get; }
}
}
#endif | 33.085714 | 104 | 0.713299 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Backup/Generated/Model/_bcl45+netstandard/IListRecoveryPointsByResourcePaginator.cs | 1,158 | 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("BarcodeFabric.Core.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BarcodeFabric.Core.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("bf29b9e5-9aeb-472a-8070-b12c7e1d243f")]
// 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.405405 | 84 | 0.746657 | [
"MIT"
] | joacar/BarcodeFabric | tests/BarcodeFabric.Core.Tests/Properties/AssemblyInfo.cs | 1,424 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30311.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NuGetGallery.Areas.Admin.DynamicData
{
public partial class Boolean_EditField
{
protected global::System.Web.UI.WebControls.CheckBox CheckBox1;
}
}
| 27.380952 | 81 | 0.492174 | [
"ECL-2.0",
"Apache-2.0"
] | JetBrains/ReSharperGallery | src/NuGetGallery/Areas/Admin/DynamicData/FieldTemplates/Boolean_Edit.ascx.designer.cs | 577 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeploymentCockpit.Interfaces
{
public interface IDeploymentJobExecutionService
{
void CleanUpAbortedJobs();
void ExecuteNextDeploymentJob();
}
}
| 20.066667 | 51 | 0.750831 | [
"Apache-2.0"
] | INaCloud/INaCloud-DeploymentCockpit | src/DeploymentCockpit.Core/Interfaces/IDeploymentJobExecutionService.cs | 303 | C# |
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)
using Framefield.Core;
using Framefield.Core.Commands;
using Framefield.Core.Rendering;
using Framefield.Tooll.Rendering;
using Newtonsoft.Json;
using SharpDX.Direct3D11;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
namespace Framefield.Tooll.Components.ParameterView.OperatorPresets
{
[JsonObject(MemberSerialization.OptIn)]
/**
* The preset manager handles the creation, display and application of operator presets
* in the ParamaterView. It users the following components:
*
* OperatorPreset - Model of a preset, gets serialized into a long list serialized to Config folder
* PresetImageManager - Loads and saves preset-images to disks
* PresetThumb - UserControl that handles rendering of a preset and forwards interaction to Manager
*
*/
public class OperatorPresetManager : DependencyObject, INotifyPropertyChanged
{
public OperatorPresetManager()
{
CurrentOperatorPresets = new ObservableCollection<OperatorPreset>();
LoadPresetsFromDisk();
}
public bool LivePreviewEnabled { get; set; }
/** This is called from Parameter-View on selection change */
public void FindAndShowPresetsForSelectedOp()
{
var op = App.Current.MainWindow.XParameterView.ShownOperator;
if (op == null || op.Definition == null || _operatorPresetsByMetaOpID == null)
return;
if (_operatorPresetsByMetaOpID.ContainsKey(op.Definition.ID))
{
CurrentOperatorPresets.Clear();
foreach (var p in _operatorPresetsByMetaOpID[op.Definition.ID])
{
if (p.IsInstancePreset && p.OperatorInstanceID != op.ID)
{
continue;
}
CurrentOperatorPresets.Add(p); // FIXME: This triggers update events for each preset. Needs refactoring to new custom observable collection that enables range setting
}
HighlightActivePreset();
}
else
{
CurrentOperatorPresets.Clear();
}
if (LivePreviewEnabled)
{
RerenderThumbnails();
}
}
/** Called when pressing the "save global preset"-button in preview region of parameter view */
public void SavePresetFromCurrentlyShownOperatorType()
{
var newPreset = TryToCreatePresetFromCurrentOperator();
if (newPreset == null)
return;
InsertAndSavePreset(newPreset);
}
/** Called when pressing the "save local preset"-button in preview region of parameter view */
public void SavePresetFromCurrentlyShownOperatorInstance()
{
var newPreset = TryToCreatePresetFromCurrentOperator();
if (newPreset == null)
return;
var op = App.Current.MainWindow.XParameterView.ShownOperator; // todo: remove access to parameter view!
if (op == null)
return;
newPreset.IsInstancePreset = true;
newPreset.OperatorInstanceID = op.ID;
PresetImageManager.RenderAndSaveThumbnail(newPreset);
InsertAndSavePreset(newPreset);
}
/** Should be used when duplicating an Operator-Definition */
public void CopyPresetsOfOpToAnother(MetaOperator source, MetaOperator target)
{
int idx = 0;
if (_operatorPresetsByMetaOpID.ContainsKey(source.ID))
{
foreach (var srcPreset in _operatorPresetsByMetaOpID[source.ID])
{
var newPreset = new OperatorPreset { MetaOperatorID = target.ID };
foreach (var srcEntry in srcPreset.ValuesByParameterID)
{
try
{
var srcInputIdx = (from input in source.Inputs
where input.ID == srcEntry.Key
select source.Inputs.IndexOf(input)).Single();
newPreset.ValuesByParameterID[target.Inputs[srcInputIdx].ID] = srcEntry.Value;
}
catch (Exception)
{
Logger.Warn("Could not copy preset parameter. This can happen when the preset contains obsolete parameters.");
}
}
if (newPreset.ValuesByParameterID.Count > 0)
AddPreset(newPreset, idx++);
else
Logger.Debug("Skipped a preset without any matching parameters");
}
}
FindAndShowPresetsForSelectedOp();
SaveAllPresets();
}
/** This is a left-over from autobackup */
public void SavePresetsAs(string filePath)
{
//FIXME: Implement to fix saving preset in autobackup
}
#region showing and using a preset
/** Called after click */
public void ApplyPreset(OperatorPreset preset)
{
App.Current.MainWindow.CompositionView.XTimeView.XAnimationCurveEditor.DisableCurveUpdatesOnModifiedEvent = true;
_isBlending = false;
Operator op = App.Current.MainWindow.XParameterView.ShownOperator;
if (op == null || _setValueGroupCommand == null || op.Definition.ID != preset.MetaOperatorID)
return;
App.Current.UndoRedoStack.Add(_setValueGroupCommand);
_tempOperatorPresetBeforePreview = null;
_setValueGroupCommand = null;
App.Current.UpdateRequiredAfterUserInteraction = true;
HighlightActivePreset();
}
private bool _isBlending = false;
public void StartBlending()
{
_isBlending = true;
}
public void BlendPreset(OperatorPreset preset, float factor)
{
Operator op = App.Current.MainWindow.XParameterView.ShownOperator;
if (op == null || op.Definition.ID != preset.MetaOperatorID || _setValueGroupCommand == null)
return;
var index = 0;
foreach (var input in op.Inputs)
{
var metaInput = input.Parent.GetMetaInput(input);
if (preset.ValuesByParameterID.ContainsKey(metaInput.ID) && _tempOperatorPresetBeforePreview != null)
{
float presetValue = preset.ValuesByParameterID[metaInput.ID];
float opValue = _tempOperatorPresetBeforePreview.ValuesByParameterID[metaInput.ID];
var newFloatValue = opValue + factor * (presetValue - opValue);
_setValueGroupCommand.UpdateFloatValueAtIndex(index, newFloatValue);
index++;
}
}
_setValueGroupCommand.Do();
App.Current.UpdateRequiredAfterUserInteraction = true;
}
public void CompleteBlendPreset(OperatorPreset preset)
{
App.Current.MainWindow.CompositionView.XTimeView.XAnimationCurveEditor.DisableCurveUpdatesOnModifiedEvent = false;
_isBlending = false;
HighlightActivePreset();
if (_setValueGroupCommand == null)
return;
App.Current.UndoRedoStack.Add(_setValueGroupCommand);
_tempOperatorPresetBeforePreview = null;
}
/** Returns false if preview was prevevent (e.g. because we're blending another preset with virutal slider) */
public bool PreviewPreset(OperatorPreset preset)
{
App.Current.MainWindow.CompositionView.XTimeView.XAnimationCurveEditor.DisableCurveUpdatesOnModifiedEvent = true;
if (_isBlending)
return false;
var entries = new List<SetValueGroupCommand.Entry>();
Operator op = App.Current.MainWindow.XParameterView.ShownOperator;
if (op != null && op.Definition.ID == preset.MetaOperatorID)
{
_tempOperatorPresetBeforePreview = CreatePresetFromOperator(op);
foreach (var input in op.Inputs)
{
var metaInput = input.Parent.GetMetaInput(input);
if (preset.ValuesByParameterID.ContainsKey(metaInput.ID))
{
entries.Add(new SetValueGroupCommand.Entry { OpPart = input, Value = new Float(preset.ValuesByParameterID[metaInput.ID]) });
}
}
App.Current.UpdateRequiredAfterUserInteraction = true;
}
_setValueGroupCommand = new SetValueGroupCommand(entries, App.Current.Model.GlobalTime);
_setValueGroupCommand.Do();
HighlightActivePreset();
return true;
}
/** Invoked after mouse leaves the thumbnail */
public void RestorePreviewPreset()
{
App.Current.MainWindow.CompositionView.XTimeView.XAnimationCurveEditor.DisableCurveUpdatesOnModifiedEvent = false;
if (_isBlending)
return;
if (_setValueGroupCommand != null)
{
_setValueGroupCommand.Undo();
_setValueGroupCommand = null;
App.Current.UpdateRequiredAfterUserInteraction = true;
}
}
public void RerenderThumbnails()
{
PresetImageManager.ReleasePreviousImages();
var keepList = CurrentOperatorPresets.ToArray();
CurrentOperatorPresets.Clear(); // We rebuild the list to trigger update notification of the observable collection
foreach (var preset in keepList)
{
PreviewPreset(preset);
if (!LivePreviewEnabled)
{
PresetImageManager.RenderAndSaveThumbnail(preset);
}
else
{
PresetImageManager.RenderImageForPreset(preset);
}
RestorePreviewPreset();
CurrentOperatorPresets.Add(preset);
}
}
public void DeletePreset(OperatorPreset preset)
{
Operator op = App.Current.MainWindow.XParameterView.ShownOperator; // todo: remove access to parameter view
if (op != null && op.Definition.ID == preset.MetaOperatorID)
{
_isBlending = false;
RestorePreviewPreset();
if (_operatorPresetsByMetaOpID.ContainsKey(op.Definition.ID))
{
_operatorPresetsByMetaOpID[op.Definition.ID].Remove(preset);
FindAndShowPresetsForSelectedOp();
SaveAllPresets();
App.Current.UpdateRequiredAfterUserInteraction = true;
}
}
}
#endregion
#region internal implementation
/** Tries to create a new preset from the current selection.
* will return NULL if selection is not valid or preset would be empty
* because the Operators does not include any floats */
private OperatorPreset TryToCreatePresetFromCurrentOperator()
{
var op = App.Current.MainWindow.XParameterView.ShownOperator; // todo: remove access to parameter view!
if (op == null)
return null;
var newPreset = CreatePresetFromOperator(op);
var hasParameters = newPreset.ValuesByParameterID.Count > 0;
if (!hasParameters)
return null;
return newPreset;
}
private void InsertAndSavePreset(OperatorPreset newPreset)
{
PresetImageManager.RenderAndSaveThumbnail(newPreset);
AddPreset(newPreset, 0);
FindAndShowPresetsForSelectedOp();
SaveAllPresets();
}
private void AddPreset(OperatorPreset newPreset, int idx)
{
if (!_operatorPresetsByMetaOpID.ContainsKey(newPreset.MetaOperatorID))
{
_operatorPresetsByMetaOpID[newPreset.MetaOperatorID] = new List<OperatorPreset>();
}
_operatorPresetsByMetaOpID[newPreset.MetaOperatorID].Insert(idx, newPreset);
}
private void HighlightActivePreset()
{
var preset = TryToCreatePresetFromCurrentOperator();
if (preset == null)
return;
foreach (var p in CurrentOperatorPresets)
{
bool matching = true;
foreach (var paramID in p.ValuesByParameterID.Keys)
{
if (preset.ValuesByParameterID.ContainsKey(paramID))
{
if (preset.ValuesByParameterID[paramID] != p.ValuesByParameterID[paramID])
{
matching = false;
break;
}
}
}
p.IsSelected = matching;
}
}
private OperatorPreset CreatePresetFromOperator(Operator op)
{
var newPreset = new OperatorPreset { MetaOperatorID = op.Definition.ID };
foreach (var input in op.Inputs)
{
if (input.Type == FunctionType.Float)
{
var metaInput = input.Parent.GetMetaInput(input);
var currentValue = OperatorPartUtilities.GetInputFloatValue(input);
newPreset.ValuesByParameterID[metaInput.ID] = currentValue;
}
}
return newPreset;
}
#endregion
#region serialization to disk
private void LoadPresetsFromDisk()
{
var localPresets = DeserializePresetDict(LOCAL_PRESETS_FILEPATH);
var globalPresets = DeserializePresetDict(PRESETS_FILEPATH);
// merge into united dict
_operatorPresetsByMetaOpID = new SortedDictionary<Guid, List<OperatorPreset>>();
SortPresetsFromAIntoB(localPresets, _operatorPresetsByMetaOpID);
SortPresetsFromAIntoB(globalPresets, _operatorPresetsByMetaOpID);
}
private SortedDictionary<Guid, List<OperatorPreset>> DeserializePresetDict(string filePath)
{
var dict = new SortedDictionary<Guid, List<OperatorPreset>>();
if (File.Exists(filePath))
{
using (var reader = new StreamReader(filePath))
{
var json = reader.ReadToEnd();
dict = JsonConvert.DeserializeObject<SortedDictionary<Guid, List<OperatorPreset>>>(json);
}
}
return dict;
}
private void SortPresetsFromAIntoB(SortedDictionary<Guid, List<OperatorPreset>> set, SortedDictionary<Guid, List<OperatorPreset>> combinedDict)
{
foreach (var list in set.Values)
{
foreach (var preset in list)
{
SortPresetIntoDict(preset, combinedDict);
}
}
}
/** Serialize all preset into two files (local and global). This avoid later merge conflicts */
public void SaveAllPresets()
{
var localPresets = new SortedDictionary<Guid, List<OperatorPreset>>();
var globalPresets = new SortedDictionary<Guid, List<OperatorPreset>>();
foreach (var list in _operatorPresetsByMetaOpID.Values)
{
foreach (var preset in list)
{
SortPresetIntoDict(preset, preset.IsInstancePreset ? localPresets
: globalPresets);
}
}
SerializePresetDict(localPresets, LOCAL_PRESETS_FILEPATH);
SerializePresetDict(globalPresets, PRESETS_FILEPATH);
}
private void SortPresetIntoDict(OperatorPreset preset, SortedDictionary<Guid, List<OperatorPreset>> sortedDict)
{
if (!sortedDict.ContainsKey(preset.MetaOperatorID))
{
sortedDict[preset.MetaOperatorID] = new List<OperatorPreset>();
}
sortedDict[preset.MetaOperatorID].Add(preset);
}
private void SerializePresetDict(SortedDictionary<Guid, List<OperatorPreset>> dict, string filePath)
{
var serializedPresets = JsonConvert.SerializeObject(dict, Formatting.Indented);
try
{
using (var sw = new StreamWriter(filePath))
{
sw.Write(serializedPresets);
}
}
catch (IOException e)
{
Logger.Debug(" can't save presets: " + e);
}
}
#endregion
#region notifier
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
#endregion
public ObservableCollection<OperatorPreset> CurrentOperatorPresets { get; private set; }
[JsonProperty]
private SortedDictionary<Guid, List<OperatorPreset>> _operatorPresetsByMetaOpID
= new SortedDictionary<Guid, List<OperatorPreset>>();
private SetValueGroupCommand _setValueGroupCommand;
private OperatorPreset _tempOperatorPresetBeforePreview;
internal PresetImageManager PresetImageManager = new PresetImageManager();
private static readonly string PRESETS_FILEPATH = @"Config/Presets.json";
private static readonly string LOCAL_PRESETS_FILEPATH = @"Config/UserPresets.json";
}
}
| 37.370809 | 187 | 0.565261 | [
"MIT"
] | kajott/tooll | Tooll/Components/ParameterView/OperatorPresets/OperatorPresetManager.cs | 18,949 | 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("IClearlyHaveEnough")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IClearlyHaveEnough")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("c384ac9e-cd2b-4af0-adde-899eff60bec4")]
// 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.945946 | 84 | 0.75 | [
"MIT"
] | ChippedChap/IClearlyHaveEnough | IClearlyHaveEnough/Properties/AssemblyInfo.cs | 1,407 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer4.EntityFramework.Options;
using Microsoft.EntityFrameworkCore;
using Skoruba.IdentityServer4.Admin.EntityFramework.Repositories;
using Skoruba.IdentityServer4.Admin.EntityFramework.Repositories.Interfaces;
using Skoruba.IdentityServer4.Admin.EntityFramework.Shared.DbContexts;
using Skoruba.IdentityServer4.Admin.UnitTests.Mocks;
using Xunit;
namespace Skoruba.IdentityServer4.Admin.UnitTests.Repositories
{
public class IdentityResourceRepositoryTests
{
private readonly DbContextOptions<IdentityServerConfigurationDbContext> _dbContextOptions;
private readonly ConfigurationStoreOptions _storeOptions;
private readonly OperationalStoreOptions _operationalStore;
private IIdentityResourceRepository GetIdentityResourceRepository(IdentityServerConfigurationDbContext context)
{
IIdentityResourceRepository identityResourceRepository = new IdentityResourceRepository<IdentityServerConfigurationDbContext>(context);
return identityResourceRepository;
}
public IdentityResourceRepositoryTests()
{
var databaseName = Guid.NewGuid().ToString();
_dbContextOptions = new DbContextOptionsBuilder<IdentityServerConfigurationDbContext>()
.UseInMemoryDatabase(databaseName)
.Options;
_storeOptions = new ConfigurationStoreOptions();
_operationalStore = new OperationalStoreOptions();
}
[Fact]
public async Task AddIdentityResourceAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var newIdentityResource = await context.IdentityResources.Where(x => x.Id == identityResource.Id).SingleAsync();
//Assert new identity resource
newIdentityResource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id));
}
}
[Fact]
public async Task GetIdentityResourceAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var newIdentityResource = await identityResourceRepository.GetIdentityResourceAsync(identityResource.Id);
//Assert new identity resource
newIdentityResource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id).Excluding(o => o.UserClaims));
newIdentityResource.UserClaims.Should().BeEquivalentTo(identityResource.UserClaims,
option => option.Excluding(x => x.Path.EndsWith("Id"))
.Excluding(x => x.Path.EndsWith("IdentityResource")));
}
}
[Fact]
public async Task DeleteIdentityResourceAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var newIdentityResource = await context.IdentityResources.Where(x => x.Id == identityResource.Id).SingleAsync();
//Assert new identity resource
newIdentityResource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id));
//Delete identity resource
await identityResourceRepository.DeleteIdentityResourceAsync(newIdentityResource);
//Get deleted identity resource
var deletedIdentityResource = await context.IdentityResources.Where(x => x.Id == identityResource.Id).SingleOrDefaultAsync();
//Assert if it not exist
deletedIdentityResource.Should().BeNull();
}
}
[Fact]
public async Task UpdateIdentityResourceAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var newIdentityResource = await context.IdentityResources.Where(x => x.Id == identityResource.Id).SingleOrDefaultAsync();
//Assert new identity resource
newIdentityResource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id));
//Detached the added item
context.Entry(newIdentityResource).State = EntityState.Detached;
//Generete new identity resource with added item id
var updatedIdentityResource = IdentityResourceMock.GenerateRandomIdentityResource(newIdentityResource.Id);
//Update identity resource
await identityResourceRepository.UpdateIdentityResourceAsync(updatedIdentityResource);
//Get updated identity resource
var updatedIdentityResourceEntity = await context.IdentityResources.Where(x => x.Id == updatedIdentityResource.Id).SingleAsync();
//Assert updated identity resource
updatedIdentityResource.Should().BeEquivalentTo(updatedIdentityResourceEntity);
}
}
[Fact]
public async Task AddIdentityResourcePropertyAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource without id
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var resource = await identityResourceRepository.GetIdentityResourceAsync(identityResource.Id);
//Assert new identity resource
resource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id)
.Excluding(o => o.UserClaims));
resource.UserClaims.Should().BeEquivalentTo(identityResource.UserClaims,
option => option.Excluding(x => x.Path.EndsWith("Id"))
.Excluding(x => x.Path.EndsWith("IdentityResource")));
//Generate random new identity resource property
var identityResourceProperty = IdentityResourceMock.GenerateRandomIdentityResourceProperty(0);
//Add new identity resource property
await identityResourceRepository.AddIdentityResourcePropertyAsync(resource.Id, identityResourceProperty);
//Get new identity resource property
var resourceProperty = await context.IdentityResourceProperties.Where(x => x.Id == identityResourceProperty.Id)
.SingleOrDefaultAsync();
resourceProperty.Should().BeEquivalentTo(identityResourceProperty,
options => options.Excluding(o => o.Id).Excluding(x => x.IdentityResource));
}
}
[Fact]
public async Task DeleteIdentityResourcePropertyAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource without id
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var resource = await identityResourceRepository.GetIdentityResourceAsync(identityResource.Id);
//Assert new identity resource
resource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id).Excluding(o => o.UserClaims));
resource.UserClaims.Should().BeEquivalentTo(identityResource.UserClaims,
option => option.Excluding(x => x.Path.EndsWith("Id"))
.Excluding(x => x.Path.EndsWith("IdentityResource")));
//Generate random new identity resource property
var identityResourceProperty = IdentityResourceMock.GenerateRandomIdentityResourceProperty(0);
//Add new identity resource property
await identityResourceRepository.AddIdentityResourcePropertyAsync(resource.Id, identityResourceProperty);
//Get new identity resource property
var property = await context.IdentityResourceProperties.Where(x => x.Id == identityResourceProperty.Id)
.SingleOrDefaultAsync();
//Assert
property.Should().BeEquivalentTo(identityResourceProperty,
options => options.Excluding(o => o.Id).Excluding(x => x.IdentityResource));
//Try delete it
await identityResourceRepository.DeleteIdentityResourcePropertyAsync(property);
//Get new identity resource property
var resourceProperty = await context.IdentityResourceProperties.Where(x => x.Id == identityResourceProperty.Id)
.SingleOrDefaultAsync();
//Assert
resourceProperty.Should().BeNull();
}
}
[Fact]
public async Task GetIdentityResourcePropertyAsync()
{
using (var context = new IdentityServerConfigurationDbContext(_dbContextOptions, _storeOptions))
{
var identityResourceRepository = GetIdentityResourceRepository(context);
//Generate random new identity resource without id
var identityResource = IdentityResourceMock.GenerateRandomIdentityResource(0);
//Add new identity resource
await identityResourceRepository.AddIdentityResourceAsync(identityResource);
//Get new identity resource
var resource = await identityResourceRepository.GetIdentityResourceAsync(identityResource.Id);
//Assert new identity resource
resource.Should().BeEquivalentTo(identityResource, options => options.Excluding(o => o.Id).Excluding(o => o.UserClaims));
resource.UserClaims.Should().BeEquivalentTo(identityResource.UserClaims,
option => option.Excluding(x => x.Path.EndsWith("Id"))
.Excluding(x => x.Path.EndsWith("IdentityResource")));
//Generate random new identity resource property
var identityResourceProperty = IdentityResourceMock.GenerateRandomIdentityResourceProperty(0);
//Add new identity resource property
await identityResourceRepository.AddIdentityResourcePropertyAsync(resource.Id, identityResourceProperty);
//Get new identity resource property
var resourceProperty = await identityResourceRepository.GetIdentityResourcePropertyAsync(identityResourceProperty.Id);
resourceProperty.Should().BeEquivalentTo(identityResourceProperty,
options => options.Excluding(o => o.Id).Excluding(x => x.IdentityResource));
}
}
}
}
| 44.643885 | 148 | 0.7051 | [
"MIT"
] | C-Romeo/IdentityServer4.Admin | tests/Skoruba.IdentityServer4.Admin.UnitTests/Repositories/IdentityResourceRepositoryTests.cs | 12,413 | C# |
using System;
using Xunit;
namespace Xunit.Xml.TestLogger.NetFull.Tests
{
public class UnitTest1
{
[Fact]
public void PassTest11()
{
}
[Fact]
public void FailTest11()
{
Assert.False(true);
}
}
public class UnitTest2
{
[Fact]
public void PAssTest21()
{
Assert.Equal(2, 2);
}
[Fact]
public void FailTest22()
{
Assert.False(true);
}
}
}
| 15.028571 | 44 | 0.454373 | [
"MIT"
] | Jensaarai/xunit.testlogger | test/Xunit.Xml.TestLogger.NetFull.Tests/UnitTest1.cs | 526 | C# |
using System.Collections;
//using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RobotStats : MonoBehaviour
{
[SerializeField] private Image blood_Stats;
private float actualHealth;
private GameObject head_Shot;
private void Start()
{
actualHealth = GetComponent<HealthScript>().initialHealth;
}
private void Awake()
{
head_Shot = GameObject.FindGameObjectWithTag("HeadShot");
head_Shot.SetActive(false);
}
public void DisplayBloodStats(float health){
health /= actualHealth;
blood_Stats.fillAmount = health;
}
public void DisplayHeadShot(){
if(!head_Shot.activeInHierarchy){
StartCoroutine(HeadShot());
}
}
private IEnumerator HeadShot(){
head_Shot.SetActive(true);
yield return new WaitForSeconds(0.25f);
head_Shot.SetActive(false);
}
} | 26.771429 | 66 | 0.660619 | [
"MIT"
] | Tharun-Kumar-Reddy-mara/Save_Chinni | Robot/RobotStats.cs | 937 | C# |
//
// DNN Corp - http://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DNN Corp
//
// 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 DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace DotNetNuke.Modules.Media
{
public sealed class RegExUtility
{
#region Constants
private const string POSITIVE_ONLY_PATTERN = "^\\d+(\\.\\d+)*?$";
private const string NEGATIVE_ALLOWED_PATTERN = "^\\-*\\d+(\\.\\d+)*?$";
private const string BOOLEAN_PATTERN = "^(1|0|true|false)$";
#endregion
/// <summary>
/// IsNumber - this method uses a regular expression to determine if the value object is in a valid numeric format.
/// </summary>
/// <param name="Value">Object - the object to parse to see if it's a number</param>
/// <returns>If true, the Value object was in a valid numeric format</returns>
/// <remarks>
/// This method does not consider commas (,) to be a valid character. This overload defaults PositiveOnly to True.
/// </remarks>
/// <history>
/// [wstrohl] - 20100130 - created
/// </history>
public static bool IsNumber(object Value)
{
return IsNumber(Value, true);
}
/// <summary>
/// IsNumber - this method uses a regular expression to determine if the value object is in a valid numeric format.
/// </summary>
/// <param name="Value">Object - the object to parse to see if it's a number</param>
/// <param name="PositiveOnly">Boolean - if true, a negative number will be considered valid</param>
/// <returns>If true, the Value object was in a valid numeric format</returns>
/// <remarks>
/// This method does not consider commas (,) to be a valid character.
/// </remarks>
/// <history>
/// [wstrohl] - 20100130 - created
/// </history>
public static bool IsNumber(object Value, bool PositiveOnly)
{
if (Value == null)
{
return false;
}
if (PositiveOnly)
{
return Regex.IsMatch(Value.ToString(), POSITIVE_ONLY_PATTERN);
}
else
{
return Regex.IsMatch(Value.ToString(), NEGATIVE_ALLOWED_PATTERN);
}
}
/// <summary>
/// IsBoolean - this method uses a regular expression to determine if the value object is in a valid boolean format.
/// </summary>
/// <param name="Value">Object - the object to parse to see if it is in a boolean fomat</param>
/// <returns>If true, the Value object was in a valid boolean format</returns>
/// <remarks>
/// This method looks for one of the following: 1, 0, true, false (case insensitive)
/// </remarks>
/// <history>
/// [wstrohl] - 20100130 - created
/// </history>
public static bool IsBoolean(object Value)
{
if (Value == null)
{
return false;
}
return Regex.IsMatch(Value.ToString(), BOOLEAN_PATTERN, RegexOptions.IgnoreCase);
}
}
} | 36.054054 | 118 | 0.701399 | [
"MIT"
] | DNNCommunity/DNN.Media | Modules/Media/Utilities/RegExUtility.cs | 4,004 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.IO;
using Microsoft.VisualStudio.ConnectedServices;
using EnvDTE;
using Moq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.OData.ConnectedService.CodeGeneration;
using Microsoft.OData.ConnectedService.Models;
using Microsoft.OData.ConnectedService.Templates;
using Microsoft.OData.ConnectedService.Tests.TestHelpers;
namespace Microsoft.OData.ConnectedService.Tests.CodeGeneration
{
[TestClass]
public class V4CodeGenDescriptorTest
{
readonly static string TestProjectRootPath = Path.Combine(Directory.GetCurrentDirectory(), "TempODataConnectedServiceTest");
readonly static string ServicesRootFolder = "ConnectedServicesRoot";
readonly static string MetadataUri = "http://service/$metadata";
[TestCleanup]
public void CleanUp()
{
try
{
Directory.Delete(TestProjectRootPath, true);
}
catch (DirectoryNotFoundException) { }
}
[DataTestMethod]
[DataRow(true, true, true, "Prefix", true)]
[DataRow(false, false, false, null, false)]
public void TestAddGeneratedClientCode_PassesServiceConfigOptionsToCodeGenerator(
bool useDSC, bool ignoreUnexpected, bool enableNamingAlias,
string namespacePrefix, bool makeTypesInternal)
{
var handlerHelper = new TestConnectedServiceHandlerHelper();
var codeGenFactory = new TestODataT4CodeGeneratorFactory();
var serviceConfig = new ServiceConfigurationV4()
{
UseDataServiceCollection = useDSC,
IgnoreUnexpectedElementsAndAttributes = ignoreUnexpected,
EnableNamingAlias = enableNamingAlias,
NamespacePrefix = namespacePrefix,
MakeTypesInternal = makeTypesInternal,
IncludeT4File = false
};
var codeGenDescriptor = SetupCodeGenDescriptor(serviceConfig, "TestService", codeGenFactory, handlerHelper);
codeGenDescriptor.AddGeneratedClientCode().Wait();
var generator = codeGenFactory.LastCreatedInstance;
Assert.AreEqual(useDSC, generator.UseDataServiceCollection);
Assert.AreEqual(enableNamingAlias, generator.EnableNamingAlias);
Assert.AreEqual(ignoreUnexpected, generator.IgnoreUnexpectedElementsAndAttributes);
Assert.AreEqual(makeTypesInternal, generator.MakeTypesInternal);
Assert.AreEqual(namespacePrefix, generator.NamespacePrefix);
Assert.AreEqual(MetadataUri, generator.MetadataDocumentUri);
Assert.AreEqual(ODataT4CodeGenerator.LanguageOption.CSharp, generator.TargetLanguage);
}
[TestMethod]
public void TestAddGeneratedClientCode_GeneratesAndSavesCodeFile()
{
var serviceName = "MyService";
ServiceConfiguration serviceConfig = new ServiceConfigurationV4()
{
MakeTypesInternal = true,
UseDataServiceCollection = false,
ServiceName = serviceName,
GeneratedFileNamePrefix = "MyFile",
IncludeT4File = false
};
var handlerHelper = new TestConnectedServiceHandlerHelper();
var codeGenDescriptor = SetupCodeGenDescriptor(serviceConfig, serviceName,
new TestODataT4CodeGeneratorFactory(), handlerHelper);
codeGenDescriptor.AddGeneratedClientCode().Wait();
using (var reader = new StreamReader(handlerHelper.AddedFileInputFileName))
{
var generatedCode = reader.ReadToEnd();
Assert.AreEqual("Generated code", generatedCode);
Assert.AreEqual(Path.Combine(TestProjectRootPath, ServicesRootFolder, serviceName, "MyFile.cs"),
handlerHelper.AddedFileTargetFilePath);
}
}
static V4CodeGenDescriptor SetupCodeGenDescriptor(ServiceConfiguration serviceConfig, string serviceName, IODataT4CodeGeneratorFactory codeGenFactory, TestConnectedServiceHandlerHelper handlerHelper)
{
var referenceFolderPath = Path.Combine(TestProjectRootPath, ServicesRootFolder, serviceName);
Directory.CreateDirectory(referenceFolderPath);
Project project = CreateTestProject(TestProjectRootPath);
var serviceInstance = new ODataConnectedServiceInstance()
{
ServiceConfig = serviceConfig,
Name = serviceName
};
handlerHelper.ServicesRootFolder = ServicesRootFolder;
ConnectedServiceHandlerContext context = new TestConnectedServiceHandlerContext(serviceInstance, handlerHelper);
return new TestV4CodeGenDescriptor(MetadataUri, context, project, codeGenFactory);
}
static Project CreateTestProject(string projectPath)
{
var fullPathPropertyMock = new Mock<Property>();
fullPathPropertyMock.SetupGet(p => p.Value).Returns(projectPath);
var projectPropertiesMock = new Mock<Properties>();
projectPropertiesMock.Setup(p => p.Item(It.Is<string>(s => s == "FullPath")))
.Returns(fullPathPropertyMock.Object);
var projectMock = new Mock<Project>();
projectMock.SetupGet(p => p.Properties)
.Returns(projectPropertiesMock.Object);
return projectMock.Object;
}
}
class TestV4CodeGenDescriptor: V4CodeGenDescriptor
{
public TestV4CodeGenDescriptor(string metadataUri, ConnectedServiceHandlerContext context, Project project, IODataT4CodeGeneratorFactory codeGenFactory)
: base(metadataUri, context, project, codeGenFactory)
{
}
protected override void Init() { }
}
class TestODataT4CodeGenerator: ODataT4CodeGenerator
{
public override string TransformText()
{
return "Generated code";
}
}
class TestODataT4CodeGeneratorFactory : IODataT4CodeGeneratorFactory
{
public ODataT4CodeGenerator LastCreatedInstance { get; private set; }
public ODataT4CodeGenerator Create()
{
var generator = new TestODataT4CodeGenerator();
LastCreatedInstance = generator;
return generator;
}
}
}
| 44.371622 | 207 | 0.672453 | [
"MIT"
] | KenitoInc/lab | ODataConnectedService/test/ODataConnectedService.Tests/CodeGeneration/V4CodeGenDescriptorTest.cs | 6,569 | C# |
/*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
namespace com.opengamma.strata.product.fx.type
{
using FromString = org.joda.convert.FromString;
using ToString = org.joda.convert.ToString;
using ReferenceData = com.opengamma.strata.basics.ReferenceData;
using ReferenceDataNotFoundException = com.opengamma.strata.basics.ReferenceDataNotFoundException;
using CurrencyPair = com.opengamma.strata.basics.currency.CurrencyPair;
using DaysAdjustment = com.opengamma.strata.basics.date.DaysAdjustment;
using ArgChecker = com.opengamma.strata.collect.ArgChecker;
using ExtendedEnum = com.opengamma.strata.collect.named.ExtendedEnum;
using Named = com.opengamma.strata.collect.named.Named;
using BuySell = com.opengamma.strata.product.common.BuySell;
/// <summary>
/// A market convention for FX Swap trades.
/// <para>
/// This defines the market convention for a FX swap based on a particular currency pair.
/// </para>
/// <para>
/// To manually create a convention, see <seealso cref="ImmutableFxSwapConvention"/>.
/// To register a specific convention, see {@code FxSwapConvention.ini}.
/// </para>
/// </summary>
public interface FxSwapConvention : TradeConvention, Named
{
/// <summary>
/// Obtains an instance from the specified unique name.
/// </summary>
/// <param name="uniqueName"> the unique name </param>
/// <returns> the convention </returns>
/// <exception cref="IllegalArgumentException"> if the name is not known </exception>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @FromString public static FxSwapConvention of(String uniqueName)
//JAVA TO C# CONVERTER TODO TASK: There is no equivalent in C# to Java static interface methods:
// public static FxSwapConvention of(String uniqueName)
// {
// ArgChecker.notNull(uniqueName, "uniqueName");
// return extendedEnum().lookup(uniqueName);
// }
/// <summary>
/// Gets the extended enum helper.
/// <para>
/// This helper allows instances of the convention to be looked up.
/// It also provides the complete set of available instances.
///
/// </para>
/// </summary>
/// <returns> the extended enum helper </returns>
//JAVA TO C# CONVERTER TODO TASK: There is no equivalent in C# to Java static interface methods:
// public static com.opengamma.strata.collect.named.ExtendedEnum<FxSwapConvention> extendedEnum()
// {
// return FxSwapConventions.ENUM_LOOKUP;
// }
//-------------------------------------------------------------------------
/// <summary>
/// Gets the currency pair of the convention.
/// </summary>
/// <returns> the currency pair </returns>
CurrencyPair CurrencyPair {get;}
/// <summary>
/// Gets the offset of the spot value date from the trade date.
/// <para>
/// The offset is applied to the trade date to find the start date.
/// A typical value is "plus 2 business days".
///
/// </para>
/// </summary>
/// <returns> the spot date offset, not null </returns>
DaysAdjustment SpotDateOffset {get;}
//-------------------------------------------------------------------------
/// <summary>
/// Creates a trade based on this convention.
/// <para>
/// This returns a trade based on the specified periods.
/// For example, a '3M x 6M' FX swap has a period from spot to the start date of 3 months and
/// a period from spot to the end date of 6 months
/// </para>
/// <para>
/// The notional is unsigned, with buy/sell determining the direction of the trade.
/// If buying the FX Swap, the amount in the first currency of the pair is received in the near leg and paid in the
/// far leg, while the second currency is paid in the near leg and received in the far leg.
///
/// </para>
/// </summary>
/// <param name="tradeDate"> the date of the trade </param>
/// <param name="periodToNear"> the period between the spot date and the near date </param>
/// <param name="periodToFar"> the period between the spot date and the far date </param>
/// <param name="buySell"> the buy/sell flag </param>
/// <param name="notional"> the notional amount, in the first currency of the currency pair </param>
/// <param name="nearFxRate"> the FX rate for the near leg </param>
/// <param name="farLegForwardPoints"> the FX points to be added to the FX rate at the far leg </param>
/// <param name="refData"> the reference data, used to resolve the trade dates </param>
/// <returns> the trade </returns>
/// <exception cref="ReferenceDataNotFoundException"> if an identifier cannot be resolved in the reference data </exception>
//JAVA TO C# CONVERTER TODO TASK: There is no equivalent in C# to Java default interface methods:
// public default com.opengamma.strata.product.fx.FxSwapTrade createTrade(java.time.LocalDate tradeDate, java.time.Period periodToNear, java.time.Period periodToFar, com.opengamma.strata.product.common.BuySell buySell, double notional, double nearFxRate, double farLegForwardPoints, com.opengamma.strata.basics.ReferenceData refData)
// {
//
// LocalDate spotValue = calculateSpotDateFromTradeDate(tradeDate, refData);
// LocalDate startDate = spotValue.plus(periodToNear);
// LocalDate endDate = spotValue.plus(periodToFar);
// return toTrade(tradeDate, startDate, endDate, buySell, notional, nearFxRate, farLegForwardPoints);
// }
/// <summary>
/// Creates a trade based on this convention.
/// <para>
/// This returns a trade based on the specified dates.
/// The notional is unsigned, with buy/sell determining the direction of the trade.
/// If buying the FX Swap, the amount in the first currency of the pair is received in the near leg and paid in the
/// far leg, while the second currency is paid in the near leg and received in the far leg.
///
/// </para>
/// </summary>
/// <param name="tradeDate"> the date of the trade </param>
/// <param name="startDate"> the start date </param>
/// <param name="endDate"> the end date </param>
/// <param name="buySell"> the buy/sell flag </param>
/// <param name="notional"> the notional amount, in the payment currency of the template </param>
/// <param name="nearFxRate"> the FX rate for the near leg </param>
/// <param name="farLegForwardPoints"> the FX points to be added to the FX rate at the far leg </param>
/// <returns> the trade </returns>
//JAVA TO C# CONVERTER TODO TASK: There is no equivalent in C# to Java default interface methods:
// public default com.opengamma.strata.product.fx.FxSwapTrade toTrade(java.time.LocalDate tradeDate, java.time.LocalDate startDate, java.time.LocalDate endDate, com.opengamma.strata.product.common.BuySell buySell, double notional, double nearFxRate, double farLegForwardPoints)
// {
//
// TradeInfo tradeInfo = TradeInfo.of(tradeDate);
// return toTrade(tradeInfo, startDate, endDate, buySell, notional, nearFxRate, farLegForwardPoints);
// }
/// <summary>
/// Creates a trade based on this convention.
/// <para>
/// This returns a trade based on the specified dates.
/// The notional is unsigned, with buy/sell determining the direction of the trade.
/// If buying the FX Swap, the amount in the first currency of the pair is received in the near leg and paid in the
/// far leg, while the second currency is paid in the near leg and received in the far leg.
///
/// </para>
/// </summary>
/// <param name="tradeInfo"> additional information about the trade </param>
/// <param name="startDate"> the start date </param>
/// <param name="endDate"> the end date </param>
/// <param name="buySell"> the buy/sell flag </param>
/// <param name="notional"> the notional amount, in the payment currency of the template </param>
/// <param name="nearFxRate"> the FX rate for the near leg </param>
/// <param name="farLegForwardPoints"> the FX points to be added to the FX rate at the far leg </param>
/// <returns> the trade </returns>
FxSwapTrade toTrade(TradeInfo tradeInfo, LocalDate startDate, LocalDate endDate, BuySell buySell, double notional, double nearFxRate, double farLegForwardPoints);
//-------------------------------------------------------------------------
/// <summary>
/// Calculates the spot date from the trade date.
/// </summary>
/// <param name="tradeDate"> the trade date </param>
/// <param name="refData"> the reference data, used to resolve the date </param>
/// <returns> the spot date </returns>
/// <exception cref="ReferenceDataNotFoundException"> if an identifier cannot be resolved in the reference data </exception>
//JAVA TO C# CONVERTER TODO TASK: There is no equivalent in C# to Java default interface methods:
// public default java.time.LocalDate calculateSpotDateFromTradeDate(java.time.LocalDate tradeDate, com.opengamma.strata.basics.ReferenceData refData)
// {
// return getSpotDateOffset().adjust(tradeDate, refData);
// }
//-------------------------------------------------------------------------
/// <summary>
/// Gets the name that uniquely identifies this convention.
/// <para>
/// This name is used in serialization and can be parsed using <seealso cref="#of(String)"/>.
///
/// </para>
/// </summary>
/// <returns> the unique name </returns>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ToString @Override public abstract String getName();
string Name {get;}
}
} | 50.46875 | 335 | 0.678535 | [
"Apache-2.0"
] | ckarcz/Strata.ConvertedToCSharp | modules/product/src/main/java/com/opengamma/strata/product/fx/type/FxSwapConvention.cs | 9,692 | C# |
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace WebAPIApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
string domain = $"https://{Configuration["Auth0:Domain"]}/";
string apiIdentifier = Configuration["Auth0:ApiIdentifier"];
string apiSecret = Configuration["Auth0:ApiSecret"];
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = domain,
ValidAudience = apiIdentifier,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret))
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
});
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 33.88 | 136 | 0.58717 | [
"MIT"
] | iamsunny/auth0-aspnetcore-webapi-samples | Samples/hs256/Startup.cs | 2,541 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class IngameEditor : GuiBase_Draggable
{
public Camera OverheadCam;
public static int TileX = 0;
public static int TileY = 0;
public ObjectLoaderInfo currObj;
private bool EditorHidden = false;
public Material UI_UNLIT;
public RawImage TileMapView;
public GameObject EditorBackground;
public InputField LevelNoToLoad;
public Dropdown TileTypeSelect;
public Dropdown FloorTextureSelect;
public Dropdown WallTextureSelect;
public Dropdown FloorTextureMapSelect;
public Dropdown WallTextureMapSelect;
public Dropdown DoorTextureMapSelect;
public Dropdown ObjectSelect;
public Dropdown ObjectItemIds;
public Toggle ObjectFlagisQuant;
public Toggle ObjectFlaginVis;
public Toggle ObjectFlagDoorDir;
public Toggle ObjectFlagEnchant;
public InputField ObjectFlagValue;
public InputField ObjectLink;
public InputField ObjectOwner;
public InputField ObjectQuality;
public InputField ObjectNext;
public InputField ObjectTileX;
public InputField ObjectTileY;
public InputField ObjectXPos;
public InputField ObjectYPos;
public InputField ObjectZPos;
public InputField TileRangeX;
public InputField TileRangeY;
public Text LevelDetails;
public Text TileDetails;
public InputField TileHeightDetails;
public RectTransform TileMapDetailsPanel;
public RectTransform ObjectDetailsPanel;
public RectTransform TextureMapDetailsPanel;
public RectTransform MobileObjectDetailsPanel;
public static IngameEditor instance;
public GridLayoutGroup FloorTextureMapDisplay;
public GridLayoutGroup WallTextureMapDisplay;
public GridLayoutGroup DoorTextureMapDisplay;
public RawImage SelectedTextureMap;
public Toggle LockTileType;
public Toggle LockTileHeight;
public Toggle LockFloorTextures;
public Toggle LockWallTextures;
public InputField npc_whoami;
public InputField npc_xhome;
public InputField npc_yhome;
public InputField npc_hp;
public Dropdown npc_goal;
public InputField npc_goaltarget;
public InputField npc_attitude;
public InputField npc_talkedto;
public InputField seed;
public static bool FollowMeMode = false;
void Awake()
{
instance = this;
}
public override void Start()
{
base.Start();
seed.text = UnderworldGenerator.instance.Seed.ToString();
if (GameWorldController.instance.LevelNo != -1)
{
SwitchPanel(0);//Tilemap
UpdateFloorTexturesDropDown();
UpdateWallTexturesDropDown();
UpdateDoorTexturesGrid();
RefreshTileMap();
RefreshTileInfo();
UpdateNPCGoals();
}
//Initiliase Item Ids
for (int i = 0; i <= GameWorldController.instance.objectMaster.objProp.GetUpperBound(0); i++)
{
ObjectItemIds.options.Add(new Dropdown.OptionData(GameWorldController.instance.objectMaster.objProp[i].desc));
}
}
void UpdateObjectsDropDown()
{
ObjectSelect.ClearOptions();
ObjectLoader objList = CurrentObjectList();
for (int i = 0; i <= objList.objInfo.GetUpperBound(0); i++)
{
if (objList.objInfo[i] != null)
{
string itemtext = ObjectLoader.UniqueObjectNameEditor(CurrentObjectList().objInfo[i]);
ObjectSelect.options.Add(new Dropdown.OptionData(itemtext));
}
}
ObjectSelect.RefreshShownValue();
}
void UpdateNPCGoals()
{
npc_goal.ClearOptions();
npc_goal.options.Add(new Dropdown.OptionData("0-Stand Still"));
npc_goal.options.Add(new Dropdown.OptionData("1-Random Movement"));
npc_goal.options.Add(new Dropdown.OptionData("2-Random Movement"));
npc_goal.options.Add(new Dropdown.OptionData("3-Follow Target"));
npc_goal.options.Add(new Dropdown.OptionData("4-Random Movement"));
npc_goal.options.Add(new Dropdown.OptionData("5-Attack Target"));
npc_goal.options.Add(new Dropdown.OptionData("6-Flee Target"));
npc_goal.options.Add(new Dropdown.OptionData("7-Stand Still"));
npc_goal.options.Add(new Dropdown.OptionData("8-Random Movement"));
npc_goal.options.Add(new Dropdown.OptionData("9-Attack Target"));
npc_goal.options.Add(new Dropdown.OptionData("10-Begin Conversation"));
npc_goal.options.Add(new Dropdown.OptionData("11-Stand Still"));
npc_goal.options.Add(new Dropdown.OptionData("12-Stand Still"));
npc_goal.RefreshShownValue();
}
void UpdateFloorTexturesDropDown()
{
FloorTextureSelect.ClearOptions();
FloorTextureMapSelect.ClearOptions();
foreach (Transform child in FloorTextureMapDisplay.transform)
{//Remove the texture maps loaded in the controls
GameObject.Destroy(child.gameObject);
}
switch (_RES)
{
case GAME_UW2:
for (int i = 0; i < 64; i++)//UW2 entire texture map
{
int index = CurrentTileMap().texture_map[i];
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
FloorTextureSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
CreateTextureMapButton(GameWorldController.instance.texLoader.LoadImageAt(index), i, index, FloorTextureMapDisplay.transform, TextureMapButton.TextureTypeFloor);
}
for (int index = 0; index < 256; index++) //All uw2 textures
{
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
FloorTextureMapSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
}
FloorTextureMapDisplay.constraintCount = 20;
FloorTextureMapDisplay.spacing = new Vector2(-18f, -20f);
break;
default:
{
for (int i = 48; i <= 57; i++)//Uw1 floor texturemap size
{
int index = CurrentTileMap().texture_map[i];
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
FloorTextureSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
CreateTextureMapButton(GameWorldController.instance.texLoader.LoadImageAt(index), i, index, FloorTextureMapDisplay.transform, TextureMapButton.TextureTypeFloor);
}
for (int index = 210; index <= 261; index++) //All floor textures
{
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
FloorTextureMapSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
}
break;
}
}
FloorTextureSelect.RefreshShownValue();
FloorTextureMapSelect.RefreshShownValue();
}
void UpdateWallTexturesDropDown()
{
WallTextureSelect.ClearOptions();
WallTextureMapSelect.ClearOptions();
foreach (Transform child in WallTextureMapDisplay.transform)
{//Remove the texture maps loaded in the controls
GameObject.Destroy(child.gameObject);
}
switch (_RES)
{
case GAME_UW2:
{
for (int i = 0; i < 64; i++)//Uw2 texturemap size
{
int index = CurrentTileMap().texture_map[i];
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
WallTextureSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
CreateTextureMapButton(GameWorldController.instance.texLoader.LoadImageAt(index), i, index, WallTextureMapDisplay.transform, TextureMapButton.TextureTypeWall);
}
for (int index = 0; index < 256; index++)
{
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
WallTextureMapSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
}
WallTextureMapDisplay.constraintCount = 20;
WallTextureMapDisplay.spacing = new Vector2(-18f, -20f);
break;
}
default:
{
for (int i = 0; i <= 47; i++)//Uw1 wall texturemap size
{
int index = CurrentTileMap().texture_map[i];
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
WallTextureSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
CreateTextureMapButton(GameWorldController.instance.texLoader.LoadImageAt(index), i, index, WallTextureMapDisplay.transform, TextureMapButton.TextureTypeWall);
}
for (int index = 0; index < 210; index++)
{
string itemtext = index.ToString() + " " + StringController.instance.GetTextureName(index);
Texture2D tex = GameWorldController.instance.texLoader.LoadImageAt(index);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));//THis does not work!!!
WallTextureMapSelect.options.Add(new Dropdown.OptionData(itemtext, sprite));
}
break;
}
}
WallTextureSelect.RefreshShownValue();
WallTextureMapSelect.RefreshShownValue();
}
void UpdateDoorTexturesGrid()
{
DoorTextureMapSelect.ClearOptions();
foreach (Transform child in DoorTextureMapDisplay.transform)
{//Remove the texture maps loaded in the controls
GameObject.Destroy(child.gameObject);
}
switch (_RES)
{
case GAME_UW2:
{
for (int i = 64; i < 70; i++)//Uw2 door textures
{
int index = CurrentTileMap().texture_map[i];
CreateTextureMapButton(GameWorldController.instance.MaterialDoors[index].mainTexture, i, index, DoorTextureMapDisplay.transform, TextureMapButton.TextureTypeDoor);
}
for (int i = 0; i <= GameWorldController.instance.MaterialDoors.GetUpperBound(0); i++)
{
DoorTextureMapSelect.options.Add(new Dropdown.OptionData("Door_" + i.ToString("D2")));
}
break;
}
default:
{
for (int i = 58; i < 64; i++)//Uw1 door textures
{
int index = CurrentTileMap().texture_map[i];
CreateTextureMapButton(GameWorldController.instance.MaterialDoors[index].mainTexture, i, index, DoorTextureMapDisplay.transform, TextureMapButton.TextureTypeDoor);
}
for (int i = 0; i <= GameWorldController.instance.MaterialDoors.GetUpperBound(0); i++)
{
DoorTextureMapSelect.options.Add(new Dropdown.OptionData("Door_" + i.ToString("D2")));
}
break;
}
}
DoorTextureMapSelect.RefreshShownValue();
}
static void CreateTextureMapButton(Texture tex, int index, int textureIndex, Transform parent, short textureType)
{
GameObject textureMapDisplay = (GameObject)Instantiate(Resources.Load("Prefabs/_TextureMapButton"));
textureMapDisplay.transform.parent = parent;
textureMapDisplay.GetComponent<TextureMapButton>().MapIndex = index;
textureMapDisplay.GetComponent<RawImage>().texture = tex;
textureMapDisplay.GetComponent<TextureMapButton>().img = textureMapDisplay.GetComponent<RawImage>();
textureMapDisplay.GetComponent<TextureMapButton>().textureType = textureType;
textureMapDisplay.GetComponent<TextureMapButton>().TextureIndex = textureIndex;
}
public void ChangeLevel()
{
int levelnotoload = 0;
if (int.TryParse(LevelNoToLoad.text, out levelnotoload))
{
if (levelnotoload <= GameWorldController.instance.Tilemaps.GetUpperBound(0))
{
GameWorldController.instance.SwitchLevel((short)levelnotoload);
RefreshTileMap();
RefreshTileInfo();
UpdateFloorTexturesDropDown();
UpdateWallTexturesDropDown();
UpdateObjectsDropDown();
}
else
{
UWHUD.instance.MessageScroll.Add("Invalid Level No");
}
}
}
public void RefreshTileMap()
{
AutoMap automap = CurrentAutoMap();
TileMap tilemap = CurrentTileMap();
//Mark all tiles as visited
for (int x = 0; x <= TileMap.TileMapSizeX; x++)
{
for (int y = 0; y <= TileMap.TileMapSizeY; y++)
{
automap.MarkTile(x, y, tilemap.Tiles[x, y].tileType, AutoMap.GetDisplayType(tilemap.Tiles[x, y]));
}
}
TileMapView.texture = CurrentAutoMap().TileMapImage();
LevelDetails.text = "Level + " + GameWorldController.instance.LevelNo;
}
public void ChangeTileX(int offset)
{
TileX += offset;
if (TileX > TileMap.TileMapSizeX) { TileX = 0; }
if (TileX < 0) { TileX = TileMap.TileMapSizeX; }
RefreshTileInfo();
}
public void ChangeTileY(int offset)
{
TileY += offset;
if (TileY > TileMap.TileMapSizeY) { TileY = 0; }
if (TileY < 0) { TileY = TileMap.TileMapSizeY; }
RefreshTileInfo();
}
public void RefreshTileInfo()
{
TileDetails.text = "X=" + TileX + " Y=" + TileY;
TileTypeSelect.value = CurrentTileMap().Tiles[TileX, TileY].tileType;
TileHeightDetails.text = ((float)CurrentTileMap().Tiles[TileX, TileY].floorHeight / 2f).ToString();
FloorTextureSelect.value = CurrentTileMap().Tiles[TileX, TileY].floorTexture;
WallTextureSelect.value = CurrentTileMap().Tiles[TileX, TileY].wallTexture;
RefreshTileMap();
}
public void UpdateTile()
{
int DimX = 0; int DimY = 0;
int FloorHeight = 0;
int WallTexture = WallTextureSelect.value;
int FloorTexture = FloorTextureSelect.value;
int TileTypeSelected = TileTypeSelect.value;
int.TryParse(TileHeightDetails.text, out FloorHeight);
if (LockTileHeight.isOn)
{
FloorHeight = -1;
}
if (LockTileType.isOn)
{
TileTypeSelected = -1;
}
if (LockFloorTextures.isOn)
{
FloorTexture = -1;
}
if (LockWallTextures.isOn)
{
WallTexture = -1;
}
if (!int.TryParse(TileRangeX.text, out DimX))
{
DimX = 0;
}
if (!int.TryParse(TileRangeY.text, out DimY))
{
DimY = 0;
}
if ((DimX == 0) && (DimY == 0))
{//Just update the specified tile
UpdateTile(TileX, TileY, TileTypeSelected, FloorTexture, WallTexture, FloorHeight);
}
else
{
//Find min and max, x & y values
int MinX = Mathf.Min(TileX, TileX + DimX);
int MaxX = Mathf.Max(TileX, TileX + DimX);
int MinY = Mathf.Min(TileY, TileY + DimY);
int MaxY = Mathf.Max(TileY, TileY + DimY);
switch (TileTypeSelected)
{
case -1://Not tile type change.
case TileMap.TILE_SOLID:
case TileMap.TILE_OPEN:
for (int x = MinX; x <= MaxX; x++)
{
for (int y = MinY; y <= MaxY; y++)
{
if (TileMap.ValidTile(x, y))
{
if (FloorHeight != -1)
{
CurrentTileMap().Tiles[x, y].floorHeight = (short)FloorHeight;
}
if ((TileTypeSelected == TileMap.TILE_OPEN) || (TileTypeSelected == -1))
{
CurrentTileMap().Tiles[x, y].VisibleFaces[TileMap.vTOP] = true;
}
else
{
CurrentTileMap().Tiles[x, y].VisibleFaces[TileMap.vTOP] = false;
}
UpdateTile(x, y, TileTypeSelected, FloorTexture, WallTexture, FloorHeight);
}
}
}
break;
case TileMap.TILE_SLOPE_E:
{
int HeightToSet = FloorHeight;
if (MinX < TileX)
{//Slopes up to this point
HeightToSet = (HeightToSet + (Mathf.Abs(DimX) * -1));
}
//else
//{//slopes up from this point
// HeightToSet= HeightToSet;//Mathf.Min(15, (HeightToSet + (DimX * 1)));
//}
for (int x = MinX; x <= MaxX; x++)
{
for (int y = MinY; y <= MaxY; y++)
{
if (
(TileMap.ValidTile(x, y))
&&
(HeightToSet >= 0)
&&
(HeightToSet <= 15)
)
{
CurrentTileMap().Tiles[x, y].VisibleFaces[TileMap.vTOP] = true;
if (FloorHeight != -1)
{
CurrentTileMap().Tiles[x, y].floorHeight = (short)HeightToSet;
}
CurrentTileMap().Tiles[x, y].shockSteep = 2;
UpdateTile(x, y, TileTypeSelected, FloorTexture, WallTexture, HeightToSet);
}
}
HeightToSet++;
}
}
break;
case TileMap.TILE_SLOPE_W:
{
int HeightToSet = FloorHeight;
if (MinX < TileX)
{//Slopes down this point
HeightToSet = (HeightToSet + (Mathf.Abs(DimX) * +1));
}
//else
//{//slopes down from this point
// HeightToSet= HeightToSet;//Mathf.Min(15, (HeightToSet + (DimX * 1)));
//}
for (int x = MinX; x <= MaxX; x++)
{
for (int y = MinY; y <= MaxY; y++)
{
if (
(TileMap.ValidTile(x, y))
&&
(HeightToSet >= 0)
&&
(HeightToSet <= 15)
)
{
CurrentTileMap().Tiles[x, y].VisibleFaces[TileMap.vTOP] = true;
if (FloorHeight != -1)
{
CurrentTileMap().Tiles[x, y].floorHeight = (short)HeightToSet;
}
CurrentTileMap().Tiles[x, y].shockSteep = 2;
UpdateTile(x, y, TileTypeSelected, FloorTexture, WallTexture, HeightToSet);
}
}
HeightToSet--;
}
}
break;
case TileMap.TILE_SLOPE_N:
{
int HeightToSet = FloorHeight;
if (MinY < TileY)
{//Slopes up to this point
HeightToSet = (HeightToSet + (Mathf.Abs(DimY) * -1));
}
//else
//{//slopes up from this point
// HeightToSet= HeightToSet;//Mathf.Min(15, (HeightToSet + (DimX * 1)));
//}
for (int y = MinY; y <= MaxY; y++)
{
for (int x = MinX; x <= MaxX; x++)
{
if (
(TileMap.ValidTile(x, y))
&&
(HeightToSet >= 0)
&&
(HeightToSet <= 15)
)
{
CurrentTileMap().Tiles[x, y].VisibleFaces[TileMap.vTOP] = true;
if (FloorHeight != -1)
{
CurrentTileMap().Tiles[x, y].floorHeight = (short)HeightToSet;
}
CurrentTileMap().Tiles[x, y].shockSteep = 2;
UpdateTile(x, y, TileTypeSelected, FloorTexture, WallTexture, HeightToSet);
}
}
HeightToSet++;
}
}
break;
case TileMap.TILE_SLOPE_S:
{
int HeightToSet = FloorHeight;
if (MinX < TileX)
{//Slopes down this point
HeightToSet = (HeightToSet + (Mathf.Abs(DimY) * +1));
}
//else
//{//slopes down from this point
// HeightToSet= HeightToSet;//Mathf.Min(15, (HeightToSet + (DimX * 1)));
//}
for (int y = MinY; y <= MaxY; y++)
{
for (int x = MinX; x <= MaxX; x++)
{
if (
(TileMap.ValidTile(x, y))
&&
(HeightToSet >= 0)
&&
(HeightToSet <= 15)
)
{
CurrentTileMap().Tiles[x, y].VisibleFaces[TileMap.vTOP] = true;
if (FloorHeight != -1)
{
CurrentTileMap().Tiles[x, y].floorHeight = (short)HeightToSet;
}
CurrentTileMap().Tiles[x, y].shockSteep = 2;
UpdateTile(x, y, TileTypeSelected, FloorTexture, WallTexture, HeightToSet);
}
}
HeightToSet--;
}
}
break;
case TileMap.TILE_DIAG_SE:
case TileMap.TILE_DIAG_NW:
{//Turns the smallest square of this tile type in the tile
int MinSquare = Mathf.Abs(Mathf.Min(DimX, DimY));
for (int xy = 0; xy <= MinSquare; xy++)
{
if (TileMap.ValidTile(MinX + xy, MinY + xy))
{
CurrentTileMap().Tiles[MinX + xy, MinY + xy].VisibleFaces[TileMap.vTOP] = true;
UpdateTile(MinX + xy, MinY + xy, TileTypeSelected, FloorTexture, WallTexture, FloorHeight);
}
}
break;
}
case TileMap.TILE_DIAG_SW:
case TileMap.TILE_DIAG_NE:
{//Turns the smallest square of this tile type in the tile
int MinSquare = Mathf.Abs(Mathf.Min(DimX, DimY));
for (int xy = 0; xy <= MinSquare; xy++)
{
if (TileMap.ValidTile(MaxX - xy, MinY + xy))
{
CurrentTileMap().Tiles[MaxX - xy, MinY + xy].VisibleFaces[TileMap.vTOP] = true;
UpdateTile(MaxX - xy, MinY + xy, TileTypeSelected, FloorTexture, WallTexture, FloorHeight);
}
}
break;
}
}
}
}
public void UpdateTile(int tileXtoUpdate, int tileYtoUpdate, int TileTypeSelected, int FloorTextureSelected, int WallTextureSelected, int FloorHeight)
{
bool ReRenderNeighbours = false;
if (!CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].NeedsReRender)
{
TileMapRenderer.DestroyTile(tileXtoUpdate, tileYtoUpdate);
}
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].TileNeedsUpdate();
if (TileTypeSelected != -1)
{
switch (TileTypeSelected)
{
case TileMap.TILE_SLOPE_E:
case TileMap.TILE_SLOPE_W:
case TileMap.TILE_SLOPE_N:
case TileMap.TILE_SLOPE_S:
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].shockSteep = 2;
break;
}
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].tileType = (short)TileTypeSelected;
}
if (FloorHeight != -1)
{
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].floorHeight = (short)(FloorHeight * 2);
}
if (FloorTextureSelected != -1)
{
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].floorTexture = (short)(FloorTextureSelected);
//int ActualTextureIndex = CurrentTileMap().texture_map[FloorTextureSelected + 48];
//water x CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].isWater = TileMap.isTextureWater(ActualTextureIndex);
//CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].isLava = TileMap.isTextureLava(ActualTextureIndex);
}
if (CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].wallTexture != WallTextureSelected)
{
if (CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].tileType == TileMap.TILE_SOLID)
{
if (WallTextureSelected != -1)
{
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].North = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].South = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].East = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].West = (short)WallTextureSelected;
}
}
if (WallTextureSelected != -1)
{
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate].wallTexture = (short)WallTextureSelected;
if (tileYtoUpdate > 0)
{//Change its neighbour, only if the neighbour is not a solid
if (CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate - 1].tileType > TileMap.TILE_SOLID)
{
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate - 1].North = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
else if ((FollowMeMode) && (WallTextureSelected != -1))
{//Repaint neighouring solid walls in follow mode
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].wallTexture = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].North = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].South = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].East = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].West = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
}
if (tileYtoUpdate < TileMap.TileMapSizeY)
{//Change its neighbour, only if the neighbour is not a solid
if (CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].tileType > TileMap.TILE_SOLID)
{
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].South = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
else if ((FollowMeMode) && (WallTextureSelected != -1))
{//Repaint neighouring solid walls in follow mode
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].wallTexture = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].North = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].South = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].East = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate, tileYtoUpdate + 1].West = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
}
if (tileXtoUpdate > 0)
{//Change its neighbour, only if the neighbour is not a solid
if (CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].tileType > TileMap.TILE_SOLID)
{
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].East = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
else if ((FollowMeMode) && (WallTextureSelected != -1))
{//Repaint neighouring solid walls in follow mode
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].wallTexture = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].North = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].South = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].East = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate - 1, tileYtoUpdate].West = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
}
if (tileXtoUpdate < TileMap.TileMapSizeX)
{//Change its neighbour, only if the neighbour is not a solid
if (CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].tileType > TileMap.TILE_SOLID)
{
CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].West = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
else if ((FollowMeMode) && (WallTextureSelected != -1))
{//Repaint neighouring solid walls in follow mode
CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].wallTexture = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].North = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].South = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].East = (short)WallTextureSelected;
CurrentTileMap().Tiles[tileXtoUpdate + 1, tileYtoUpdate].West = (short)WallTextureSelected;
ReRenderNeighbours = true;
}
}
}
}
if (ReRenderNeighbours)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (!((x == 0) && (y == 0)))//Not the middle
{
if ((x + tileXtoUpdate <= TileMap.TileMapSizeX) && (x + tileXtoUpdate >= 0))
{
if ((y + tileYtoUpdate <= TileMap.TileMapSizeY) && (y + tileYtoUpdate >= 0))
{
if (!CurrentTileMap().Tiles[x + tileXtoUpdate, y + tileYtoUpdate].NeedsReRender)
{
TileMapRenderer.DestroyTile(x + tileXtoUpdate, y + tileYtoUpdate);
}
CurrentTileMap().Tiles[x + tileXtoUpdate, y + tileYtoUpdate].TileNeedsUpdate();
}
}
}
}
}
}
}
public void Teleport()
{
float targetX = (float)TileX * 1.2f + 0.6f;
float targetY = (float)TileY * 1.2f + 0.6f;
if (ObjectDetailsPanel.gameObject.activeInHierarchy)
{
if (currObj.ObjectTileX != 99)
{
targetX = (float)currObj.ObjectTileX * 1.2f + 0.6f;
}
if (currObj.ObjectTileY != 99)
{
targetY = (float)currObj.ObjectTileY * 1.2f + 0.6f;
}
}
float Height = ((float)(CurrentTileMap().GetFloorHeight(TileX, TileY))) * 0.15f;
UWCharacter.Instance.gameObject.transform.position = new Vector3(targetX, Height + 0.3f, targetY);
}
public void SelectCurrentTile()
{
TileX = TileMap.visitTileX;
TileY = TileMap.visitTileY;
RefreshTileInfo();
}
public void SelectTile(int tileX, int tileY)
{
TileX = tileX;
TileY = tileY;
RefreshTileInfo();
}
public void SwitchPanel(int Panel)
{
TileMapDetailsPanel.gameObject.SetActive(Panel == 0);
ObjectDetailsPanel.gameObject.SetActive(Panel == 1);
TextureMapDetailsPanel.gameObject.SetActive(Panel == 2);
if (Panel == 1)
{
UpdateObjectsDropDown();
}
if (Panel != 1)
{
MobileObjectDetailsPanel.gameObject.SetActive(false);
}
}
public void TogglePanels()
{
if (!EditorHidden)
{
SwitchPanel(-1);
EditorHidden = true;
}
else
{
SwitchPanel(0);
EditorHidden = false;
}
EditorBackground.SetActive(!EditorHidden);
}
public void RefreshObjectInfo()
{
currObj = CurrentObjectList().objInfo[ObjectSelect.value];
//string ObjectName=ObjectLoader.UniqueObjectNameEditor(currObj);
ObjectItemIds.value = currObj.item_id;
ObjectFlagDoorDir.isOn = (currObj.doordir == 1);
ObjectFlagEnchant.isOn = (currObj.enchantment == 1);
ObjectFlaginVis.isOn = (currObj.invis == 1);
ObjectFlagisQuant.isOn = (currObj.is_quant == 1);
ObjectFlagValue.text = currObj.flags.ToString();
ObjectOwner.text = currObj.owner.ToString();
ObjectLink.text = currObj.link.ToString();
ObjectNext.text = currObj.next.ToString();
ObjectQuality.text = currObj.quality.ToString();
if (currObj.instance != null)
{
currObj.instance.UpdatePosition();
}
ObjectTileX.text = currObj.ObjectTileX.ToString();
ObjectTileY.text = currObj.ObjectTileY.ToString();
ObjectXPos.text = currObj.xpos.ToString();
ObjectYPos.text = currObj.ypos.ToString();
ObjectZPos.text = currObj.zpos.ToString();
MobileObjectDetailsPanel.gameObject.SetActive((currObj.index <= 255));
if (currObj.index <= 255)
{
//populate mobile data
npc_whoami.text = currObj.npc_whoami.ToString();
npc_xhome.text = currObj.npc_xhome.ToString();
npc_yhome.text = currObj.npc_yhome.ToString();
npc_hp.text = currObj.npc_hp.ToString();
npc_goal.value = currObj.npc_goal;
npc_goaltarget.text = currObj.npc_gtarg.ToString();
npc_attitude.text = currObj.npc_attitude.ToString();
npc_talkedto.text = currObj.npc_talkedto.ToString();
}
}
public void ToggleFollowMeMode()
{
FollowMeMode = !FollowMeMode;
UWHUD.instance.MessageScroll.Add("Follow me mode = " + FollowMeMode.ToString());
}
/// <summary>
/// Updates the tile based on the select parameters in the tile editor
/// </summary>
/// <param name="tileX">Tile x.</param>
/// <param name="tileY">Tile y.</param>
/// Will not change the tile type if the type is a solid
public static void UpdateFollowMeMode(int tileX, int tileY)
{
//int DimX=0;int DimY=0;
int FloorHeight = 0;
int WallTexture = instance.WallTextureSelect.value;
int FloorTexture = instance.FloorTextureSelect.value;
int TileTypeSelected = instance.TileTypeSelect.value;
int.TryParse(instance.TileHeightDetails.text, out FloorHeight);
if (instance.LockTileHeight.isOn)
{
FloorHeight = -1;
}
if ((instance.LockTileType.isOn) || (TileTypeSelected == TileMap.TILE_SOLID))
{
TileTypeSelected = -1;
}
if (instance.LockFloorTextures.isOn)
{
FloorTexture = -1;
}
if (instance.LockWallTextures.isOn)
{
WallTexture = -1;
}
CurrentTileMap().Tiles[tileX, tileY].VisibleFaces[TileMap.vTOP] = true;
IngameEditor.instance.UpdateTile(tileX, tileY, TileTypeSelected, FloorTexture, WallTexture, FloorHeight);
}
public void ObjectEditorApplyChanges()
{
currObj.item_id = ObjectItemIds.value;
if (ObjectFlagisQuant.isOn)
{
currObj.is_quant = 1;
}
else
{
currObj.is_quant = 0;
}
if (ObjectFlaginVis.isOn)
{
currObj.invis = 1;
}
else
{
currObj.invis = 0;
}
if (ObjectFlagDoorDir.isOn)
{
currObj.doordir = 1;
}
else
{
currObj.doordir = 0;
}
if (ObjectFlagEnchant.isOn)
{
currObj.enchantment = 1;
}
else
{
currObj.enchantment = 0;
}
int val = 0;
if (int.TryParse(ObjectFlagValue.text, out val))
{
currObj.flags = (short)(val & 0x7);
ObjectFlagValue.text = currObj.flags.ToString();
}
if (int.TryParse(ObjectOwner.text, out val))
{
currObj.owner = (short)(val & 0x3F);
ObjectOwner.text = currObj.owner.ToString();
}
if (int.TryParse(ObjectLink.text, out val))
{
currObj.link = (short)(val & 0x3FF);
ObjectLink.text = currObj.link.ToString();
}
if (int.TryParse(ObjectQuality.text, out val))
{
currObj.quality = (short)(val & 0x3F);
ObjectQuality.text = currObj.quality.ToString();
}
if (currObj.index <= 255)
{//A mobile object
if (int.TryParse(npc_whoami.text, out val))
{
currObj.npc_whoami = (short)(val);
npc_whoami.text = currObj.npc_whoami.ToString();
}
if (int.TryParse(npc_xhome.text, out val))
{
currObj.npc_xhome = (short)(val);
npc_xhome.text = currObj.npc_xhome.ToString();
}
if (int.TryParse(npc_yhome.text, out val))
{
currObj.npc_yhome = (short)(val);
npc_yhome.text = currObj.npc_yhome.ToString();
}
if (int.TryParse(npc_hp.text, out val))
{
currObj.npc_hp = (short)(val);
npc_hp.text = currObj.npc_hp.ToString();
}
currObj.npc_goal = (short)npc_goal.value;
if (int.TryParse(npc_goaltarget.text, out val))
{
currObj.npc_gtarg = (short)(val);
npc_goaltarget.text = currObj.npc_gtarg.ToString();
}
if (int.TryParse(npc_attitude.text, out val))
{
currObj.npc_attitude = (short)(val);
npc_attitude.text = currObj.npc_attitude.ToString();
}
if (int.TryParse(npc_talkedto.text, out val))
{
currObj.npc_talkedto = (short)(val & 0x1);
npc_talkedto.text = currObj.npc_talkedto.ToString();
}
}
switch (currObj.GetItemType())
{
case ObjectInteraction.LOCK:
case ObjectInteraction.A_USE_TRIGGER:
if (int.TryParse(ObjectNext.text, out val))
{
currObj.next = (short)(val & 0x3Ff);
ObjectNext.text = currObj.next.ToString();
}
break;
default:
break;//do not allow changing the next of an object. The engine normally handles this.
}
if (int.TryParse(ObjectTileX.text, out val))
{
if ((val < 0) || (val > TileMap.TileMapSizeX))
{
val = TileMap.ObjectStorageTile;
}
currObj.ObjectTileX = (short)(val);
ObjectTileX.text = currObj.ObjectTileX.ToString();
}
if (int.TryParse(ObjectTileY.text, out val))
{
if ((val < 0) || (val > TileMap.TileMapSizeY))
{
val = TileMap.ObjectStorageTile;
}
currObj.ObjectTileY = (short)(val);
ObjectTileY.text = currObj.ObjectTileY.ToString();
}
if (int.TryParse(ObjectXPos.text, out val))
{
currObj.xpos = (short)(val & 0x7);
ObjectXPos.text = currObj.xpos.ToString();
}
if (int.TryParse(ObjectYPos.text, out val))
{
currObj.ypos = (short)(val & 0x7);
ObjectYPos.text = currObj.ypos.ToString();
}
if (int.TryParse(ObjectZPos.text, out val))
{
currObj.zpos = (short)(val & 0x7F);
ObjectZPos.text = currObj.zpos.ToString();
}
if (currObj.instance != null)
{
Destroy(currObj.instance.gameObject);
Vector3 pos = ObjectLoader.CalcObjectXYZ(currObj.index, 0);
ObjectInteraction.CreateNewObject(CurrentTileMap(),
currObj, CurrentObjectList().objInfo, GameWorldController.instance.DynamicObjectMarker().gameObject,
pos);
}
else
{
if (currObj.ObjectTileX <= TileMap.TileMapSizeX)//A object is brought from off map.
{
currObj.InUseFlag = 1;
Vector3 pos = ObjectLoader.CalcObjectXYZ(currObj.index, 0);
ObjectInteraction.CreateNewObject(CurrentTileMap(),
currObj, CurrentObjectList().objInfo, GameWorldController.instance.DynamicObjectMarker().gameObject,
pos);
}
}
}
public void ToggleCamera()
{
if (!OverheadCam.gameObject.activeInHierarchy)
{
if (GameWorldController.instance.ceiling != null)
{
GameWorldController.instance.ceiling.SetActive(false);
}
OverheadCam.gameObject.SetActive(true);
UWCharacter.Instance.playerCam.tag = "Untagged";
UWCharacter.Instance.playerCam.enabled = false;
OverheadCam.tag = "MainCamera";
}
else
{
if (GameWorldController.instance.ceiling != null)
{
GameWorldController.instance.ceiling.SetActive(true);
}
OverheadCam.gameObject.SetActive(false);
UWCharacter.Instance.playerCam.tag = "MainCamera";
UWCharacter.Instance.playerCam.enabled = true;
OverheadCam.tag = "Untagged";
}
}
void OnGUI()
{
if (OverheadCam.gameObject.activeInHierarchy)
{
if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
if (Input.GetAxis("Mouse ScrollWheel") <= 0)
{
OverheadCam.orthographicSize += 1;
}
else
{
OverheadCam.orthographicSize -= 1;
}
}
if (OverheadCam.orthographicSize <= 0)
{
OverheadCam.orthographicSize = 1;
}
}
}
public override void Update()
{
base.Update();
if (OverheadCam.gameObject.activeInHierarchy)
{
if (Input.GetKey(KeyCode.RightArrow))
{
OverheadCam.gameObject.transform.Translate(new Vector3(10 * Time.deltaTime, 0, 0));
}
if (Input.GetKey(KeyCode.LeftArrow))
{
OverheadCam.gameObject.transform.Translate(new Vector3(-10 * Time.deltaTime, 0, 0));
}
if (Input.GetKey(KeyCode.DownArrow))
{
OverheadCam.gameObject.transform.Translate(new Vector3(0, -10 * Time.deltaTime, 0));
}
if (Input.GetKey(KeyCode.UpArrow))
{
OverheadCam.gameObject.transform.Translate(new Vector3(0, 10 * Time.deltaTime, 0));
}
}
}
public void GenerateRandomLevel()
{
int levelseed = 0;
if (int.TryParse(seed.text, out levelseed))
{
UnderworldGenerator.instance.GenerateLevel(levelseed);
UnderworldGenerator.instance.RoomsToTileMap(CurrentTileMap(), CurrentTileMap().Tiles);
GameWorldController.WorldReRenderPending = true;
GameWorldController.FullReRender = true;
float targetX = (float)UnderworldGenerator.instance.startX * 1.2f + 0.6f;
float targetY = (float)UnderworldGenerator.instance.startY * 1.2f + 0.6f;
float Height = ((float)(CurrentTileMap().GetFloorHeight(UnderworldGenerator.instance.startX, UnderworldGenerator.instance.startY))) * 0.15f;
UWCharacter.Instance.transform.position = new Vector3(targetX, Height + 0.1f, targetY);
}
}
} | 42.053659 | 188 | 0.502997 | [
"MIT"
] | KarlClinckspoor/UnderworldExporter | UnityScripts/scripts/World/IngameEditor.cs | 51,728 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.Direct3D11
{
[NativeName("Name", "CD3D11_TEXTURE2D_DESC")]
public unsafe partial struct CD3D11Texture2DDesc
{
public CD3D11Texture2DDesc
(
uint? width = null,
uint? height = null,
uint? mipLevels = null,
uint? arraySize = null,
Silk.NET.DXGI.Format? format = null,
Silk.NET.DXGI.SampleDesc? sampleDesc = null,
Usage? usage = null,
uint? bindFlags = null,
uint? cPUAccessFlags = null,
uint? miscFlags = null
) : this()
{
if (width is not null)
{
Width = width.Value;
}
if (height is not null)
{
Height = height.Value;
}
if (mipLevels is not null)
{
MipLevels = mipLevels.Value;
}
if (arraySize is not null)
{
ArraySize = arraySize.Value;
}
if (format is not null)
{
Format = format.Value;
}
if (sampleDesc is not null)
{
SampleDesc = sampleDesc.Value;
}
if (usage is not null)
{
Usage = usage.Value;
}
if (bindFlags is not null)
{
BindFlags = bindFlags.Value;
}
if (cPUAccessFlags is not null)
{
CPUAccessFlags = cPUAccessFlags.Value;
}
if (miscFlags is not null)
{
MiscFlags = miscFlags.Value;
}
}
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "Width")]
public uint Width;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "Height")]
public uint Height;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "MipLevels")]
public uint MipLevels;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "ArraySize")]
public uint ArraySize;
[NativeName("Type", "DXGI_FORMAT")]
[NativeName("Type.Name", "DXGI_FORMAT")]
[NativeName("Name", "Format")]
public Silk.NET.DXGI.Format Format;
[NativeName("Type", "DXGI_SAMPLE_DESC")]
[NativeName("Type.Name", "DXGI_SAMPLE_DESC")]
[NativeName("Name", "SampleDesc")]
public Silk.NET.DXGI.SampleDesc SampleDesc;
[NativeName("Type", "D3D11_USAGE")]
[NativeName("Type.Name", "D3D11_USAGE")]
[NativeName("Name", "Usage")]
public Usage Usage;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "BindFlags")]
public uint BindFlags;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "CPUAccessFlags")]
public uint CPUAccessFlags;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "MiscFlags")]
public uint MiscFlags;
}
}
| 26.971223 | 71 | 0.520672 | [
"MIT"
] | Ar37-rs/Silk.NET | src/Microsoft/Silk.NET.Direct3D11/Structs/CD3D11Texture2DDesc.gen.cs | 3,749 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Mono.Cecil;
using Mono.Documentation.Util;
namespace Mono.Documentation.Updater
{
class SlashDocMemberFormatter : MemberFormatter
{
protected override string[] GenericTypeContainer
{
get { return new string[] { "{", "}" }; }
}
private bool AddTypeCount = true;
private TypeReference genDeclType;
private MethodReference genDeclMethod;
protected override StringBuilder AppendTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
{
if (type is GenericParameter)
{
int l = buf.Length;
if (genDeclType != null)
{
IList<GenericParameter> genArgs = genDeclType.GenericParameters;
for (int i = 0; i < genArgs.Count; ++i)
{
if (genArgs[i].Name == type.Name)
{
buf.Append ('`').Append (i);
break;
}
}
}
if (genDeclMethod != null)
{
IList<GenericParameter> genArgs = null;
if (genDeclMethod.IsGenericMethod ())
{
genArgs = genDeclMethod.GenericParameters;
for (int i = 0; i < genArgs.Count; ++i)
{
if (genArgs[i].Name == type.Name)
{
buf.Append ("``").Append (i);
break;
}
}
}
}
if (genDeclType == null && genDeclMethod == null)
{
// Probably from within an explicitly implemented interface member,
// where CSC uses parameter names instead of indices (why?), e.g.
// MyList`2.Mono#DocTest#Generic#IFoo{A}#Method``1(`0,``0) instead of
// MyList`2.Mono#DocTest#Generic#IFoo{`0}#Method``1(`0,``0).
buf.Append (type.Name);
}
if (buf.Length == l)
{
throw new Exception (string.Format (
"Unable to translate generic parameter {0}; genDeclType={1}, genDeclMethod={2}",
type.Name, genDeclType, genDeclMethod));
}
}
else
{
base.AppendTypeName (buf, type, context);
if (AddTypeCount)
{
int numArgs = type.GenericParameters.Count;
if (type.DeclaringType != null)
numArgs -= type.GenericParameters.Count;
if (numArgs > 0)
{
buf.Append ('`').Append (numArgs);
}
}
}
return buf;
}
protected override StringBuilder AppendArrayModifiers (StringBuilder buf, ArrayType array)
{
buf.Append (ArrayDelimeters[0]);
int rank = array.Rank;
if (rank > 1)
{
buf.Append ("0:");
for (int i = 1; i < rank; ++i)
{
buf.Append (",0:");
}
}
return buf.Append (ArrayDelimeters[1]);
}
protected override StringBuilder AppendGenericType (StringBuilder buf, TypeReference type, DynamicParserContext context, bool appendGeneric = true)
{
if (!AddTypeCount)
base.AppendGenericType (buf, type, context);
else
AppendType (buf, type, context);
return buf;
}
private StringBuilder AppendType (StringBuilder buf, TypeReference type, DynamicParserContext context)
{
List<TypeReference> decls = DocUtils.GetDeclaringTypes (type);
bool insertNested = false;
int prevParamCount = 0;
foreach (var decl in decls)
{
if (insertNested)
buf.Append (NestedTypeSeparator);
insertNested = true;
base.AppendTypeName (buf, decl, context);
int argCount = DocUtils.GetGenericArgumentCount (decl);
int numArgs = argCount - prevParamCount;
prevParamCount = argCount;
if (numArgs > 0)
buf.Append ('`').Append (numArgs);
}
return buf;
}
protected override string GetConstructorName (MethodReference constructor)
{
return GetMethodDefinitionName (constructor, "#ctor");
}
protected override string GetMethodName (MethodReference method)
{
string name = null;
MethodDefinition methodDef = method as MethodDefinition;
if (methodDef == null || !DocUtils.IsExplicitlyImplemented (methodDef))
name = method.Name;
else
{
TypeReference iface;
MethodReference ifaceMethod;
DocUtils.GetInfoForExplicitlyImplementedMethod (methodDef, out iface, out ifaceMethod);
AddTypeCount = false;
name = GetTypeName (iface) + "." + ifaceMethod.Name;
AddTypeCount = true;
}
return GetMethodDefinitionName (method, name);
}
private string GetMethodDefinitionName (MethodReference method, string name)
{
StringBuilder buf = new StringBuilder ();
buf.Append (GetTypeName (method.DeclaringType));
buf.Append ('.');
buf.Append (name.Replace (".", "#"));
if (method.IsGenericMethod ())
{
IList<GenericParameter> genArgs = method.GenericParameters;
if (genArgs.Count > 0)
buf.Append ("``").Append (genArgs.Count);
}
IList<ParameterDefinition> parameters = method.Parameters;
try
{
genDeclType = method.DeclaringType;
genDeclMethod = method;
AppendParameters (buf, method.DeclaringType.GenericParameters, parameters);
}
finally
{
genDeclType = null;
genDeclMethod = null;
}
return buf.ToString ();
}
private StringBuilder AppendParameters (StringBuilder buf, IList<GenericParameter> genArgs, IList<ParameterDefinition> parameters)
{
if (parameters.Count == 0)
return buf;
buf.Append ('(');
AppendParameter (buf, genArgs, parameters[0]);
for (int i = 1; i < parameters.Count; ++i)
{
buf.Append (',');
AppendParameter (buf, genArgs, parameters[i]);
}
return buf.Append (')');
}
private StringBuilder AppendParameter (StringBuilder buf, IList<GenericParameter> genArgs, ParameterDefinition parameter)
{
AddTypeCount = false;
buf.Append (GetTypeName (parameter.ParameterType));
AddTypeCount = true;
return buf;
}
protected override string GetPropertyName (PropertyReference property)
{
string name = null;
PropertyDefinition propertyDef = property as PropertyDefinition;
MethodDefinition method = null;
if (propertyDef != null)
method = propertyDef.GetMethod ?? propertyDef.SetMethod;
if (method != null && !DocUtils.IsExplicitlyImplemented (method))
name = property.Name;
else
{
TypeReference iface;
MethodReference ifaceMethod;
DocUtils.GetInfoForExplicitlyImplementedMethod (method, out iface, out ifaceMethod);
AddTypeCount = false;
name = string.Join ("#", new string[]{
GetTypeName (iface).Replace (".", "#"),
DocUtils.GetMember (property.Name)
});
AddTypeCount = true;
}
StringBuilder buf = new StringBuilder ();
buf.Append (GetName (property.DeclaringType));
buf.Append ('.');
buf.Append (name);
IList<ParameterDefinition> parameters = property.Parameters;
if (parameters.Count > 0)
{
genDeclType = property.DeclaringType;
buf.Append ('(');
IList<GenericParameter> genArgs = property.DeclaringType.GenericParameters;
AppendParameter (buf, genArgs, parameters[0]);
for (int i = 1; i < parameters.Count; ++i)
{
buf.Append (',');
AppendParameter (buf, genArgs, parameters[i]);
}
buf.Append (')');
genDeclType = null;
}
return buf.ToString ();
}
protected override string GetFieldName (FieldReference field)
{
return string.Format ("{0}.{1}",
GetName (field.DeclaringType), field.Name);
}
protected override string GetEventName (EventReference e)
{
return string.Format ("{0}.{1}",
GetName (e.DeclaringType), e.Name);
}
protected override string GetTypeDeclaration (TypeDefinition type)
{
string name = GetName (type);
if (type == null)
return null;
return "T:" + name;
}
protected override string GetConstructorDeclaration (MethodDefinition constructor)
{
string name = GetName (constructor);
if (name == null)
return null;
return "M:" + name;
}
protected override string GetMethodDeclaration (MethodDefinition method)
{
string name = GetName (method);
if (name == null)
return null;
if (method.Name == "op_Implicit" || method.Name == "op_Explicit")
{
genDeclType = method.DeclaringType;
genDeclMethod = method;
name += "~" + GetName (method.ReturnType);
genDeclType = null;
genDeclMethod = null;
}
return "M:" + name;
}
protected override string GetPropertyDeclaration (PropertyDefinition property)
{
string name = GetName (property);
if (name == null)
return null;
return "P:" + name;
}
protected override string GetFieldDeclaration (FieldDefinition field)
{
string name = GetName (field);
if (name == null)
return null;
return "F:" + name;
}
protected override string GetEventDeclaration (EventDefinition e)
{
string name = GetName (e);
if (name == null)
return null;
return "E:" + name;
}
protected override string GetAttachedEventDeclaration(AttachedEventDefinition e)
{
string name = GetName(e);
if (name == null)
return null;
return "E:" + name;
}
protected override string GetAttachedPropertyDeclaration(AttachedPropertyDefinition a)
{
string name = GetName(a);
if (name == null)
return null;
return "P:" + name;
}
}
} | 35.597633 | 155 | 0.493268 | [
"MIT"
] | mhutch/api-doc-tools | mdoc/Mono.Documentation/Updater/Formatters/SlashDocMemberFormatter.cs | 12,034 | C# |
namespace NeedForSpeed
{
public class Vehicle
{
public Vehicle(int horsePower, double fuel)
{
this.HorsePower = horsePower;
this.Fuel = fuel;
this.DefaultFuelConsumption = 1.25;
}
public double DefaultFuelConsumption { get; set; }
public virtual double FuelConsumption { get; set; }
public double Fuel { get; set; }
public int HorsePower { get; set; }
public virtual void Drive(double kilometers)
{
if (this.Fuel >= kilometers* this.DefaultFuelConsumption)
{
this.Fuel -= kilometers * this.DefaultFuelConsumption;
}
else
{
System.Console.WriteLine("Not enough fuel!");
}
}
}
}
| 26.612903 | 70 | 0.526061 | [
"MIT"
] | DeyanDanailov/SoftUni-OOP | InheritanceExercise/NeedForSpeed/Vehicle.cs | 827 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Ogólne informacje o zestawie są kontrolowane poprzez następujący
// zestaw atrybutów. Zmień wartości tych atrybutów, aby zmodyfikować informacje
// powiązane z zestawem.
[assembly: AssemblyTitle("141299")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("141299")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Ustawienie elementu ComVisible na wartość false sprawia, że typy w tym zestawie są niewidoczne
// dla składników COM. Jeśli potrzebny jest dostęp do typu w tym zestawie z
// COM, ustaw wartość true dla atrybutu ComVisible tego typu.
[assembly: ComVisible(false)]
// Następujący identyfikator GUID jest identyfikatorem biblioteki typów w przypadku udostępnienia tego projektu w modelu COM
[assembly: Guid("4122a4e9-c607-4283-b672-624a41843847")]
// Informacje o wersji zestawu zawierają następujące cztery wartości:
//
// Wersja główna
// Wersja pomocnicza
// Numer kompilacji
// Poprawka
//
// Możesz określić wszystkie wartości lub użyć domyślnych numerów kompilacji i poprawki
// przy użyciu symbolu „*”, tak jak pokazano poniżej:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.324324 | 125 | 0.747319 | [
"MIT"
] | zw1nc3k/OOP2019-1 | zadania/Lesson2/141299/141299/Properties/AssemblyInfo.cs | 1,539 | 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 ssm-2014-11-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleSystemsManagement.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations
{
/// <summary>
/// Target Marshaller
/// </summary>
public class TargetMarshaller : IRequestMarshaller<Target, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(Target requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetKey())
{
context.Writer.WritePropertyName("Key");
context.Writer.Write(requestObject.Key);
}
if(requestObject.IsSetValues())
{
context.Writer.WritePropertyName("Values");
context.Writer.WriteArrayStart();
foreach(var requestObjectValuesListValue in requestObject.Values)
{
context.Writer.Write(requestObjectValuesListValue);
}
context.Writer.WriteArrayEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static TargetMarshaller Instance = new TargetMarshaller();
}
} | 33.246575 | 101 | 0.650597 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/TargetMarshaller.cs | 2,427 | C# |
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.
#if EF5 || EF6
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Z.EntityFramework.Plus;
#if EF5 || EF6
using System.Data.Entity;
#elif EFCORE
using Microsoft.Data.Entity;
#endif
namespace Z.Test.EntityFramework.Plus
{
public partial class Audit_EntityAdded
{
[TestMethod]
public void Entity_Complex()
{
var identitySeed = TestContext.GetIdentitySeed(x => x.Entity_Complexes);
TestContext.DeleteAll(x => x.AuditEntryProperties);
TestContext.DeleteAll(x => x.AuditEntries);
TestContext.DeleteAll(x => x.Entity_Complexes);
var audit = AuditHelper.AutoSaveAudit();
using (var ctx = new TestContext())
{
TestContext.Insert(ctx, x => x.Entity_Complexes, 3);
ctx.SaveChanges(audit);
}
// UnitTest - Audit
{
var entries = audit.Entries;
// Entries
{
// Entries Count
Assert.AreEqual(3, entries.Count);
// Entries State
Assert.AreEqual(AuditEntryState.EntityAdded, entries[0].State);
Assert.AreEqual(AuditEntryState.EntityAdded, entries[1].State);
Assert.AreEqual(AuditEntryState.EntityAdded, entries[2].State);
// Entries EntitySetName
Assert.AreEqual(TestContext.TypeName(x => x.Entity_Complexes), entries[0].EntitySetName);
Assert.AreEqual(TestContext.TypeName(x => x.Entity_Complexes), entries[1].EntitySetName);
Assert.AreEqual(TestContext.TypeName(x => x.Entity_Complexes), entries[2].EntitySetName);
// Entries TypeName
Assert.AreEqual(typeof (Entity_Complex).Name, entries[0].EntityTypeName);
Assert.AreEqual(typeof (Entity_Complex).Name, entries[1].EntityTypeName);
Assert.AreEqual(typeof (Entity_Complex).Name, entries[2].EntityTypeName);
}
// Properties
{
var propertyIndex = -1;
// Properties Count
Assert.AreEqual(4, entries[0].Properties.Count);
Assert.AreEqual(4, entries[1].Properties.Count);
Assert.AreEqual(4, entries[2].Properties.Count);
// ID
propertyIndex = 0;
Assert.AreEqual("ID", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ID", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ID", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual(identitySeed + 1, entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual(identitySeed + 2, entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual(identitySeed + 3, entries[2].Properties[propertyIndex].NewValue);
// ColumnInt
propertyIndex = 1;
Assert.AreEqual("ColumnInt", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ColumnInt", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ColumnInt", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual(0, entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual(1, entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual(2, entries[2].Properties[propertyIndex].NewValue);
// Info.ColumnInt
propertyIndex = 2;
Assert.AreEqual("Info.ColumnInt", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.ColumnInt", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.ColumnInt", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual(1000, entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual(1001, entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual(1002, entries[2].Properties[propertyIndex].NewValue);
// Info.Info.ColumnInt
propertyIndex = 3;
Assert.AreEqual("Info.Info.ColumnInt", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.Info.ColumnInt", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.Info.ColumnInt", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual(1000000, entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual(1000001, entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual(1000002, entries[2].Properties[propertyIndex].NewValue);
}
}
// UnitTest - Audit (Database)
{
using (var ctx = new TestContext())
{
// ENSURE order
var entries = ctx.AuditEntries.OrderBy(x => x.AuditEntryID).Include(x => x.Properties).ToList();
entries.ForEach(x => x.Properties = x.Properties.OrderBy(y => y.AuditEntryPropertyID).ToList());
// Entries
{
// Entries Count
Assert.AreEqual(3, entries.Count);
// Entries State
Assert.AreEqual(AuditEntryState.EntityAdded, entries[0].State);
Assert.AreEqual(AuditEntryState.EntityAdded, entries[1].State);
Assert.AreEqual(AuditEntryState.EntityAdded, entries[2].State);
// Entries EntitySetName
Assert.AreEqual(TestContext.TypeName(x => x.Entity_Complexes), entries[0].EntitySetName);
Assert.AreEqual(TestContext.TypeName(x => x.Entity_Complexes), entries[1].EntitySetName);
Assert.AreEqual(TestContext.TypeName(x => x.Entity_Complexes), entries[2].EntitySetName);
// Entries TypeName
Assert.AreEqual(typeof (Entity_Complex).Name, entries[0].EntityTypeName);
Assert.AreEqual(typeof (Entity_Complex).Name, entries[1].EntityTypeName);
Assert.AreEqual(typeof (Entity_Complex).Name, entries[2].EntityTypeName);
}
// Properties
{
var propertyIndex = -1;
// Properties Count
Assert.AreEqual(4, entries[0].Properties.Count);
Assert.AreEqual(4, entries[1].Properties.Count);
Assert.AreEqual(4, entries[2].Properties.Count);
// ID
propertyIndex = 0;
Assert.AreEqual("ID", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ID", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ID", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual((identitySeed + 1).ToString(), entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual((identitySeed + 2).ToString(), entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual((identitySeed + 3).ToString(), entries[2].Properties[propertyIndex].NewValue);
// ColumnInt
propertyIndex = 1;
Assert.AreEqual("ColumnInt", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ColumnInt", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("ColumnInt", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual("0", entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual("1", entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual("2", entries[2].Properties[propertyIndex].NewValue);
// Info.ColumnInt
propertyIndex = 2;
Assert.AreEqual("Info.ColumnInt", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.ColumnInt", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.ColumnInt", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual("1000", entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual("1001", entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual("1002", entries[2].Properties[propertyIndex].NewValue);
// Info.Info.ColumnInt
propertyIndex = 3;
Assert.AreEqual("Info.Info.ColumnInt", entries[0].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.Info.ColumnInt", entries[1].Properties[propertyIndex].PropertyName);
Assert.AreEqual("Info.Info.ColumnInt", entries[2].Properties[propertyIndex].PropertyName);
Assert.AreEqual(null, entries[0].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[1].Properties[propertyIndex].OldValue);
Assert.AreEqual(null, entries[2].Properties[propertyIndex].OldValue);
Assert.AreEqual("1000000", entries[0].Properties[propertyIndex].NewValue);
Assert.AreEqual("1000001", entries[1].Properties[propertyIndex].NewValue);
Assert.AreEqual("1000002", entries[2].Properties[propertyIndex].NewValue);
}
}
}
}
}
}
#endif | 58.926267 | 191 | 0.58231 | [
"MIT"
] | Ahmed-Abdelhameed/EntityFramework-Plus | src/Z.Test.EntityFramework.Plus.EFCore.Shared/Audit/EntityAdded/Entity_Complex.cs | 12,790 | C# |
using System;
using System.Linq;
namespace ToolBox.Runtime.Lookups
{
[Serializable]
public sealed class EnumLookup<K, V> : Lookup<K, V> where K : Enum
{
protected override K[] GetKeys() =>
Enum.GetValues(typeof(K)).Cast<K>().ToArray();
protected override void Process(SerializedDictionary<K, V> lookup)
{
for (int i = lookup.Count - 1; i >= 0; i--)
{
var key = lookup.Keys.ElementAt(i);
if (!Enum.IsDefined(typeof(K), key))
lookup.Remove(key);
}
}
}
}
| 20.541667 | 68 | 0.640974 | [
"MIT"
] | IntoTheDev/Core | Runtime/Lookups/EnumLookup.cs | 495 | C# |
#region Project Description [About this]
// =================================================================================
// The whole Project is Licensed under the MIT License
// =================================================================================
// =================================================================================
// Wiesend's Dynamic Link Library is a collection of reusable code that
// I've written, or found throughout my programming career.
//
// I tried my very best to mention all of the original copyright holders.
// I hope that all code which I've copied from others is mentioned and all
// their copyrights are given. The copied code (or code snippets) could
// already be modified by me or others.
// =================================================================================
#endregion of Project Description
#region Original Source Code [Links to all original source code]
// =================================================================================
// Original Source Code [Links to all original source code]
// =================================================================================
// https://github.com/JaCraig/Craig-s-Utility-Library
// =================================================================================
// I didn't wrote this source totally on my own, this class could be nearly a
// clone of the project of James Craig, I did highly get inspired by him, so
// this piece of code isn't totally mine, shame on me, I'm not the best!
// =================================================================================
#endregion of where is the original source code
#region Licenses [MIT Licenses]
#region MIT License [James Craig]
// =================================================================================
// Copyright(c) 2014 <a href="http://www.gutgames.com">James Craig</a>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// =================================================================================
#endregion of MIT License [James Craig]
#region MIT License [Dominik Wiesend]
// =================================================================================
// Copyright(c) 2016 Dominik Wiesend. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// =================================================================================
#endregion of MIT License [Dominik Wiesend]
#endregion of Licenses [MIT Licenses]
using System;
using Wiesend.IO.Messaging.Interfaces;
using Wiesend.IoC.Interfaces;
namespace Wiesend.IO.Messaging.Module
{
/// <summary>
/// Messaging module
/// </summary>
public class MessagingModule : IModule
{
/// <summary>
/// Order to run it in
/// </summary>
public int Order
{
get { return 0; }
}
/// <summary>
/// Loads the module
/// </summary>
/// <param name="Bootstrapper">Bootstrapper to register with</param>
[CLSCompliant(false)]
public void Load(IBootstrapper Bootstrapper)
{
Bootstrapper.RegisterAll<IFormatter>();
Bootstrapper.RegisterAll<IMessagingSystem>();
Bootstrapper.Register(new Manager(Bootstrapper.ResolveAll<IFormatter>(), Bootstrapper.ResolveAll<IMessagingSystem>()));
}
}
} | 52.59434 | 131 | 0.573274 | [
"MIT"
] | DominikWiesend/wiesend | projects/Wiesend.IO/IO/Messaging/Module/MessagingModule.cs | 5,577 | C# |
using RestSharp.Authenticators;
namespace PandaSharp.Framework.Rest.Contract
{
public interface IRestAuthentication
{
IAuthenticator CreateAuthenticator();
void UseBasic(string userName, string userPassword);
void UseOAuth(
string consumerKey,
string consumerSecret,
string oAuthAccessToken,
string oAuthTokenSecret);
}
} | 24.058824 | 60 | 0.665037 | [
"MIT"
] | Metablex/PandaSharp.Framework | PandaSharp.Framework/Rest/Contract/IRestAuthentication.cs | 411 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace UWPShop.Sensors
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 38.881188 | 99 | 0.614464 | [
"MIT"
] | AsimKhan2019/UWP-Shop-Analytics-Sample | UWPShop.Sensors/App.xaml.cs | 3,929 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801
{
using Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.PowerShell;
/// <summary>Defines the dependency override of the move resource.</summary>
[System.ComponentModel.TypeConverter(typeof(MoveResourceDependencyOverrideTypeConverter))]
public partial class MoveResourceDependencyOverride
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.MoveResourceDependencyOverride"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverride"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverride DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new MoveResourceDependencyOverride(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.MoveResourceDependencyOverride"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverride"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverride DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new MoveResourceDependencyOverride(content);
}
/// <summary>
/// Creates a new instance of <see cref="MoveResourceDependencyOverride" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverride FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.MoveResourceDependencyOverride"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal MoveResourceDependencyOverride(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("TargetId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).TargetId = (string) content.GetValueForProperty("TargetId",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).TargetId, global::System.Convert.ToString);
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.MoveResourceDependencyOverride"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal MoveResourceDependencyOverride(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("TargetId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).TargetId = (string) content.GetValueForProperty("TargetId",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20210801.IMoveResourceDependencyOverrideInternal)this).TargetId, global::System.Convert.ToString);
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Defines the dependency override of the move resource.
[System.ComponentModel.TypeConverter(typeof(MoveResourceDependencyOverrideTypeConverter))]
public partial interface IMoveResourceDependencyOverride
{
}
} | 63.986842 | 351 | 0.693091 | [
"MIT"
] | Agazoth/azure-powershell | src/ResourceMover/generated/api/Models/Api20210801/MoveResourceDependencyOverride.PowerShell.cs | 9,575 | C# |
using System;
using Newtonsoft.Json;
using NLog;
namespace CodeSaw.Web.Serialization
{
public class RevisionIdConverter : JsonConverter
{
private static readonly Logger Log = LogManager.GetLogger("RevisionIdConverter");
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Log.Warn("Usage of deprecated RevisionIdConverter");
var revisionId = value as RevisionId;
if (revisionId == null)
{
writer.WriteNull();
return;
}
var str = revisionId.Resolve(() => "base", s => s.Revision.ToString(), s => s.CommitHash);
writer.WriteValue(str);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return RevisionId.Parse(reader.Value.ToString());
}
public override bool CanConvert(Type objectType) => typeof(RevisionId).IsAssignableFrom(objectType);
}
} | 31.264706 | 124 | 0.631232 | [
"MIT"
] | ChainsawDevelopment/CodeSaw | CodeSaw.Web/Serialization/RevisionIdConverter.cs | 1,063 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.AspNetCore.Cryptography.SafeHandles
{
/// <summary>
/// Represents a handle returned by LocalAlloc.
/// </summary>
internal class LocalAllocHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Called by P/Invoke when returning SafeHandles
protected LocalAllocHandle() : base(ownsHandle: true) { }
// Do not provide a finalizer - SafeHandle's critical finalizer will call ReleaseHandle for you.
protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle); // actually calls LocalFree
return true;
}
}
}
| 33.846154 | 111 | 0.698864 | [
"Apache-2.0"
] | belav/aspnetcore | src/DataProtection/Cryptography.Internal/src/SafeHandles/LocalAllocHandle.cs | 880 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Rg.Web.Startup))]
namespace Rg.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 18.4 | 57 | 0.597826 | [
"MIT"
] | jenyayel/rgroup | src/Rg.Web/Startup.cs | 278 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Microsoft.MixedReality.WebRTC
{
/// <summary>
/// Interface for audio sources, whether local sources/tracks or remote tracks.
/// </summary>
/// <seealso cref="AudioTrackSource"/>
/// <seealso cref="LocalAudioTrack"/>
/// <seealso cref="RemoteAudioTrack"/>
public interface IAudioSource
{
/// <summary>
/// Event that occurs when a new audio frame is available from the source, either
/// because the source produced it locally (<see cref="AudioTrackSource"/>, <see cref="LocalAudioTrack"/>) or because
/// it received it from the remote peer (<see cref="RemoteAudioTrack"/>).
/// </summary>
/// <remarks>
/// WebRTC audio tracks produce an audio frame every 10 ms.
/// If you want to process the audio frames as soon as they are received, without conversions,
/// subscribe to <see cref="AudioFrameReady"/>.
/// If you want the audio frames to be buffered (and optionally resampled) automatically,
/// and you want the application to control when new audio data is read, create an
/// <see cref="AudioTrackReadBuffer"/> using <see cref="CreateReadBuffer"/>.
/// </remarks>
event AudioFrameDelegate AudioFrameReady;
/// <summary>
/// Enabled status of the source. If enabled, produces audio frames as expected. If
/// disabled, produces silence instead.
/// </summary>
bool Enabled { get; }
/// <summary>
/// Starts buffering the audio frames from in an <see cref="AudioTrackReadBuffer"/>.
/// </summary>
/// <remarks>
/// WebRTC audio tracks produce an audio frame every 10 ms.
/// If you want the audio frames to be buffered (and optionally resampled) automatically,
/// and you want the application to control when new audio data is read, create an
/// <see cref="AudioTrackReadBuffer"/> using <see cref="CreateReadBuffer"/>.
/// If you want to process the audio frames as soon as they are received, without conversions,
/// subscribe to <see cref="AudioFrameReady"/> instead.
/// </remarks>
AudioTrackReadBuffer CreateReadBuffer();
}
}
| 47.183673 | 125 | 0.639706 | [
"MIT"
] | AltspaceVR/MixedReality-WebRTC | libs/Microsoft.MixedReality.WebRTC/IAudioSource.cs | 2,312 | C# |
using System;
using System.Collections.Generic;
using DSerfozo.CefGlue.Contract.Common;
using static DSerfozo.CefGlue.Contract.Common.CefFactories;
namespace DSerfozo.RpcBindings.CefGlue.Common.Serialization
{
public sealed class ValueTypeSerializer : ITypeSerializer, ITypeDeserializer
{
public bool CanHandle(Type type)
{
return type == typeof(decimal) || type == typeof(DateTime);
}
public bool CanHandle(ICefValue cefValue, Type targetType)
{
return (targetType == typeof(decimal) && (cefValue.GetValueType() == CefValueType.Double ||
cefValue.GetValueType() == CefValueType.Int)) ||
(targetType == typeof(DateTime) && cefValue.IsType(CefTypes.Time));
}
public ICefValue Serialize(object obj, Stack<object> seen, ObjectSerializer objectSerializer)
{
var type = obj.GetType();
if (!CanHandle(type))
{
throw new InvalidOperationException();
}
var result = CefValue.Create();
if (type == typeof(DateTime))
{
result.SetTime((DateTime)obj);
}
else if (type == typeof(decimal))
{
result.SetDouble(Convert.ToDouble((decimal)obj));
}
return result;
}
public object Deserialize(ICefValue value, Type targetType, ObjectSerializer objectSerializer)
{
if (!CanHandle(value, targetType))
{
throw new InvalidOperationException();
}
object result = null;
if (value.IsType(CefTypes.Time) && targetType == typeof(DateTime))
{
result = value.GetTime();
}
else if(targetType == typeof(decimal))
{
var cefValueType = value.GetValueType();
switch (cefValueType)
{
case CefValueType.Int:
result = Convert.ToDecimal(value.GetInt());
break;
case CefValueType.Double:
result = Convert.ToDecimal(value.GetDouble());
break;
}
}
return result;
}
}
}
| 33.263889 | 103 | 0.518163 | [
"MIT"
] | rpc-bindings/cefglue | src/DSerfozo.RpcBindings.CefGlue/Common/Serialization/ValueTypeSerializer.cs | 2,397 | 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 datapipeline-2012-10-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.DataPipeline.Model;
using Amazon.DataPipeline.Model.Internal.MarshallTransformations;
using Amazon.DataPipeline.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.DataPipeline
{
/// <summary>
/// Implementation for accessing DataPipeline
///
/// AWS Data Pipeline configures and manages a data-driven workflow called a pipeline.
/// AWS Data Pipeline handles the details of scheduling and ensuring that data dependencies
/// are met so that your application can focus on processing the data.
///
///
/// <para>
/// AWS Data Pipeline provides a JAR implementation of a task runner called AWS Data Pipeline
/// Task Runner. AWS Data Pipeline Task Runner provides logic for common data management
/// scenarios, such as performing database queries and running data analysis using Amazon
/// Elastic MapReduce (Amazon EMR). You can use AWS Data Pipeline Task Runner as your
/// task runner, or you can write your own task runner to provide custom data management.
/// </para>
///
/// <para>
/// AWS Data Pipeline implements two main sets of functionality. Use the first set to
/// create a pipeline and define data sources, schedules, dependencies, and the transforms
/// to be performed on the data. Use the second set in your task runner application to
/// receive the next task ready for processing. The logic for performing the task, such
/// as querying the data, running data analysis, or converting the data from one format
/// to another, is contained within the task runner. The task runner performs the task
/// assigned to it by the web service, reporting progress to the web service as it does
/// so. When the task is done, the task runner reports the final success or failure of
/// the task to the web service.
/// </para>
/// </summary>
public partial class AmazonDataPipelineClient : AmazonServiceClient, IAmazonDataPipeline
{
private static IServiceMetadata serviceMetadata = new AmazonDataPipelineMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonDataPipelineClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonDataPipelineClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDataPipelineConfig()) { }
/// <summary>
/// Constructs AmazonDataPipelineClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonDataPipelineClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDataPipelineConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonDataPipelineClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonDataPipelineClient Configuration Object</param>
public AmazonDataPipelineClient(AmazonDataPipelineConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonDataPipelineClient(AWSCredentials credentials)
: this(credentials, new AmazonDataPipelineConfig())
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonDataPipelineClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonDataPipelineConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Credentials and an
/// AmazonDataPipelineClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonDataPipelineClient Configuration Object</param>
public AmazonDataPipelineClient(AWSCredentials credentials, AmazonDataPipelineConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDataPipelineConfig())
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDataPipelineConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDataPipelineClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonDataPipelineClient Configuration Object</param>
public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDataPipelineConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDataPipelineConfig())
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDataPipelineConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDataPipelineClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDataPipelineClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonDataPipelineClient Configuration Object</param>
public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDataPipelineConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region ActivatePipeline
/// <summary>
/// Validates the specified pipeline and starts processing pipeline tasks. If the pipeline
/// does not pass validation, activation fails.
///
///
/// <para>
/// If you need to pause the pipeline to investigate an issue with a component, such as
/// a data source or script, call <a>DeactivatePipeline</a>.
/// </para>
///
/// <para>
/// To activate a finished pipeline, modify the end date for the pipeline and then activate
/// it.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ActivatePipeline service method.</param>
///
/// <returns>The response from the ActivatePipeline service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ActivatePipeline">REST API Reference for ActivatePipeline Operation</seealso>
public virtual ActivatePipelineResponse ActivatePipeline(ActivatePipelineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ActivatePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = ActivatePipelineResponseUnmarshaller.Instance;
return Invoke<ActivatePipelineResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ActivatePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ActivatePipeline operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndActivatePipeline
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ActivatePipeline">REST API Reference for ActivatePipeline Operation</seealso>
public virtual IAsyncResult BeginActivatePipeline(ActivatePipelineRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ActivatePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = ActivatePipelineResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ActivatePipeline operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginActivatePipeline.</param>
///
/// <returns>Returns a ActivatePipelineResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ActivatePipeline">REST API Reference for ActivatePipeline Operation</seealso>
public virtual ActivatePipelineResponse EndActivatePipeline(IAsyncResult asyncResult)
{
return EndInvoke<ActivatePipelineResponse>(asyncResult);
}
#endregion
#region AddTags
/// <summary>
/// Adds or modifies tags for the specified pipeline.
/// </summary>
/// <param name="pipelineId">The ID of the pipeline.</param>
/// <param name="tags">The tags to add, as key/value pairs.</param>
///
/// <returns>The response from the AddTags service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso>
public virtual AddTagsResponse AddTags(string pipelineId, List<Tag> tags)
{
var request = new AddTagsRequest();
request.PipelineId = pipelineId;
request.Tags = tags;
return AddTags(request);
}
/// <summary>
/// Adds or modifies tags for the specified pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddTags service method.</param>
///
/// <returns>The response from the AddTags service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso>
public virtual AddTagsResponse AddTags(AddTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddTagsResponseUnmarshaller.Instance;
return Invoke<AddTagsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the AddTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddTags operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAddTags
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso>
public virtual IAsyncResult BeginAddTags(AddTagsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddTagsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the AddTags operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddTags.</param>
///
/// <returns>Returns a AddTagsResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso>
public virtual AddTagsResponse EndAddTags(IAsyncResult asyncResult)
{
return EndInvoke<AddTagsResponse>(asyncResult);
}
#endregion
#region CreatePipeline
/// <summary>
/// Creates a new, empty pipeline. Use <a>PutPipelineDefinition</a> to populate the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePipeline service method.</param>
///
/// <returns>The response from the CreatePipeline service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
public virtual CreatePipelineResponse CreatePipeline(CreatePipelineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreatePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreatePipelineResponseUnmarshaller.Instance;
return Invoke<CreatePipelineResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreatePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreatePipeline operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreatePipeline
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
public virtual IAsyncResult BeginCreatePipeline(CreatePipelineRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreatePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreatePipelineResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreatePipeline operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreatePipeline.</param>
///
/// <returns>Returns a CreatePipelineResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
public virtual CreatePipelineResponse EndCreatePipeline(IAsyncResult asyncResult)
{
return EndInvoke<CreatePipelineResponse>(asyncResult);
}
#endregion
#region DeactivatePipeline
/// <summary>
/// Deactivates the specified running pipeline. The pipeline is set to the <code>DEACTIVATING</code>
/// state until the deactivation process completes.
///
///
/// <para>
/// To resume a deactivated pipeline, use <a>ActivatePipeline</a>. By default, the pipeline
/// resumes from the last completed execution. Optionally, you can specify the date and
/// time to resume the pipeline.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeactivatePipeline service method.</param>
///
/// <returns>The response from the DeactivatePipeline service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeactivatePipeline">REST API Reference for DeactivatePipeline Operation</seealso>
public virtual DeactivatePipelineResponse DeactivatePipeline(DeactivatePipelineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeactivatePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeactivatePipelineResponseUnmarshaller.Instance;
return Invoke<DeactivatePipelineResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeactivatePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeactivatePipeline operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeactivatePipeline
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeactivatePipeline">REST API Reference for DeactivatePipeline Operation</seealso>
public virtual IAsyncResult BeginDeactivatePipeline(DeactivatePipelineRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeactivatePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeactivatePipelineResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeactivatePipeline operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeactivatePipeline.</param>
///
/// <returns>Returns a DeactivatePipelineResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeactivatePipeline">REST API Reference for DeactivatePipeline Operation</seealso>
public virtual DeactivatePipelineResponse EndDeactivatePipeline(IAsyncResult asyncResult)
{
return EndInvoke<DeactivatePipelineResponse>(asyncResult);
}
#endregion
#region DeletePipeline
/// <summary>
/// Deletes a pipeline, its pipeline definition, and its run history. AWS Data Pipeline
/// attempts to cancel instances associated with the pipeline that are currently being
/// processed by task runners.
///
///
/// <para>
/// Deleting a pipeline cannot be undone. You cannot query or restore a deleted pipeline.
/// To temporarily pause a pipeline instead of deleting it, call <a>SetStatus</a> with
/// the status set to <code>PAUSE</code> on individual components. Components that are
/// paused by <a>SetStatus</a> can be resumed.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePipeline service method.</param>
///
/// <returns>The response from the DeletePipeline service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
public virtual DeletePipelineResponse DeletePipeline(DeletePipelineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeletePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeletePipelineResponseUnmarshaller.Instance;
return Invoke<DeletePipelineResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeletePipeline operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeletePipeline operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeletePipeline
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
public virtual IAsyncResult BeginDeletePipeline(DeletePipelineRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeletePipelineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeletePipelineResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeletePipeline operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeletePipeline.</param>
///
/// <returns>Returns a DeletePipelineResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
public virtual DeletePipelineResponse EndDeletePipeline(IAsyncResult asyncResult)
{
return EndInvoke<DeletePipelineResponse>(asyncResult);
}
#endregion
#region DescribeObjects
/// <summary>
/// Gets the object definitions for a set of objects associated with the pipeline. Object
/// definitions are composed of a set of fields that define the properties of the object.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeObjects service method.</param>
///
/// <returns>The response from the DescribeObjects service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribeObjects">REST API Reference for DescribeObjects Operation</seealso>
public virtual DescribeObjectsResponse DescribeObjects(DescribeObjectsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeObjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeObjectsResponseUnmarshaller.Instance;
return Invoke<DescribeObjectsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeObjects operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeObjects operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeObjects
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribeObjects">REST API Reference for DescribeObjects Operation</seealso>
public virtual IAsyncResult BeginDescribeObjects(DescribeObjectsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeObjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeObjectsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeObjects operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeObjects.</param>
///
/// <returns>Returns a DescribeObjectsResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribeObjects">REST API Reference for DescribeObjects Operation</seealso>
public virtual DescribeObjectsResponse EndDescribeObjects(IAsyncResult asyncResult)
{
return EndInvoke<DescribeObjectsResponse>(asyncResult);
}
#endregion
#region DescribePipelines
/// <summary>
/// Retrieves metadata about one or more pipelines. The information retrieved includes
/// the name of the pipeline, the pipeline identifier, its current state, and the user
/// account that owns the pipeline. Using account credentials, you can retrieve metadata
/// about pipelines that you or your IAM users have created. If you are using an IAM user
/// account, you can retrieve metadata about only those pipelines for which you have read
/// permissions.
///
///
/// <para>
/// To retrieve the full pipeline definition instead of metadata about the pipeline, call
/// <a>GetPipelineDefinition</a>.
/// </para>
/// </summary>
/// <param name="pipelineIds">The IDs of the pipelines to describe. You can pass as many as 25 identifiers in a single call. To obtain pipeline IDs, call <a>ListPipelines</a>.</param>
///
/// <returns>The response from the DescribePipelines service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso>
public virtual DescribePipelinesResponse DescribePipelines(List<string> pipelineIds)
{
var request = new DescribePipelinesRequest();
request.PipelineIds = pipelineIds;
return DescribePipelines(request);
}
/// <summary>
/// Retrieves metadata about one or more pipelines. The information retrieved includes
/// the name of the pipeline, the pipeline identifier, its current state, and the user
/// account that owns the pipeline. Using account credentials, you can retrieve metadata
/// about pipelines that you or your IAM users have created. If you are using an IAM user
/// account, you can retrieve metadata about only those pipelines for which you have read
/// permissions.
///
///
/// <para>
/// To retrieve the full pipeline definition instead of metadata about the pipeline, call
/// <a>GetPipelineDefinition</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribePipelines service method.</param>
///
/// <returns>The response from the DescribePipelines service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso>
public virtual DescribePipelinesResponse DescribePipelines(DescribePipelinesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribePipelinesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribePipelinesResponseUnmarshaller.Instance;
return Invoke<DescribePipelinesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribePipelines operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribePipelines operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribePipelines
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso>
public virtual IAsyncResult BeginDescribePipelines(DescribePipelinesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribePipelinesRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribePipelinesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribePipelines operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribePipelines.</param>
///
/// <returns>Returns a DescribePipelinesResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso>
public virtual DescribePipelinesResponse EndDescribePipelines(IAsyncResult asyncResult)
{
return EndInvoke<DescribePipelinesResponse>(asyncResult);
}
#endregion
#region EvaluateExpression
/// <summary>
/// Task runners call <code>EvaluateExpression</code> to evaluate a string in the context
/// of the specified object. For example, a task runner can evaluate SQL queries stored
/// in Amazon S3.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EvaluateExpression service method.</param>
///
/// <returns>The response from the EvaluateExpression service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException">
/// The specified task was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/EvaluateExpression">REST API Reference for EvaluateExpression Operation</seealso>
public virtual EvaluateExpressionResponse EvaluateExpression(EvaluateExpressionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = EvaluateExpressionRequestMarshaller.Instance;
options.ResponseUnmarshaller = EvaluateExpressionResponseUnmarshaller.Instance;
return Invoke<EvaluateExpressionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the EvaluateExpression operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EvaluateExpression operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndEvaluateExpression
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/EvaluateExpression">REST API Reference for EvaluateExpression Operation</seealso>
public virtual IAsyncResult BeginEvaluateExpression(EvaluateExpressionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = EvaluateExpressionRequestMarshaller.Instance;
options.ResponseUnmarshaller = EvaluateExpressionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the EvaluateExpression operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginEvaluateExpression.</param>
///
/// <returns>Returns a EvaluateExpressionResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/EvaluateExpression">REST API Reference for EvaluateExpression Operation</seealso>
public virtual EvaluateExpressionResponse EndEvaluateExpression(IAsyncResult asyncResult)
{
return EndInvoke<EvaluateExpressionResponse>(asyncResult);
}
#endregion
#region GetPipelineDefinition
/// <summary>
/// Gets the definition of the specified pipeline. You can call <code>GetPipelineDefinition</code>
/// to retrieve the pipeline definition that you provided using <a>PutPipelineDefinition</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipelineDefinition service method.</param>
///
/// <returns>The response from the GetPipelineDefinition service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/GetPipelineDefinition">REST API Reference for GetPipelineDefinition Operation</seealso>
public virtual GetPipelineDefinitionResponse GetPipelineDefinition(GetPipelineDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetPipelineDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetPipelineDefinitionResponseUnmarshaller.Instance;
return Invoke<GetPipelineDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetPipelineDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetPipelineDefinition operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetPipelineDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/GetPipelineDefinition">REST API Reference for GetPipelineDefinition Operation</seealso>
public virtual IAsyncResult BeginGetPipelineDefinition(GetPipelineDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetPipelineDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetPipelineDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetPipelineDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetPipelineDefinition.</param>
///
/// <returns>Returns a GetPipelineDefinitionResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/GetPipelineDefinition">REST API Reference for GetPipelineDefinition Operation</seealso>
public virtual GetPipelineDefinitionResponse EndGetPipelineDefinition(IAsyncResult asyncResult)
{
return EndInvoke<GetPipelineDefinitionResponse>(asyncResult);
}
#endregion
#region ListPipelines
/// <summary>
/// Lists the pipeline identifiers for all active pipelines that you have permission to
/// access.
/// </summary>
///
/// <returns>The response from the ListPipelines service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
public virtual ListPipelinesResponse ListPipelines()
{
return ListPipelines(new ListPipelinesRequest());
}
/// <summary>
/// Lists the pipeline identifiers for all active pipelines that you have permission to
/// access.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPipelines service method.</param>
///
/// <returns>The response from the ListPipelines service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
public virtual ListPipelinesResponse ListPipelines(ListPipelinesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListPipelinesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListPipelinesResponseUnmarshaller.Instance;
return Invoke<ListPipelinesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListPipelines operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListPipelines operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPipelines
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
public virtual IAsyncResult BeginListPipelines(ListPipelinesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListPipelinesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListPipelinesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListPipelines operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPipelines.</param>
///
/// <returns>Returns a ListPipelinesResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
public virtual ListPipelinesResponse EndListPipelines(IAsyncResult asyncResult)
{
return EndInvoke<ListPipelinesResponse>(asyncResult);
}
#endregion
#region PollForTask
/// <summary>
/// Task runners call <code>PollForTask</code> to receive a task to perform from AWS Data
/// Pipeline. The task runner specifies which tasks it can perform by setting a value
/// for the <code>workerGroup</code> parameter. The task returned can come from any of
/// the pipelines that match the <code>workerGroup</code> value passed in by the task
/// runner and that was launched using the IAM user credentials specified by the task
/// runner.
///
///
/// <para>
/// If tasks are ready in the work queue, <code>PollForTask</code> returns a response
/// immediately. If no tasks are available in the queue, <code>PollForTask</code> uses
/// long-polling and holds on to a poll connection for up to a 90 seconds, during which
/// time the first newly scheduled task is handed to the task runner. To accomodate this,
/// set the socket timeout in your task runner to 90 seconds. The task runner should not
/// call <code>PollForTask</code> again on the same <code>workerGroup</code> until it
/// receives a response, and this can take up to 90 seconds.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PollForTask service method.</param>
///
/// <returns>The response from the PollForTask service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException">
/// The specified task was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PollForTask">REST API Reference for PollForTask Operation</seealso>
public virtual PollForTaskResponse PollForTask(PollForTaskRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PollForTaskRequestMarshaller.Instance;
options.ResponseUnmarshaller = PollForTaskResponseUnmarshaller.Instance;
return Invoke<PollForTaskResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the PollForTask operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PollForTask operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPollForTask
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PollForTask">REST API Reference for PollForTask Operation</seealso>
public virtual IAsyncResult BeginPollForTask(PollForTaskRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = PollForTaskRequestMarshaller.Instance;
options.ResponseUnmarshaller = PollForTaskResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the PollForTask operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPollForTask.</param>
///
/// <returns>Returns a PollForTaskResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PollForTask">REST API Reference for PollForTask Operation</seealso>
public virtual PollForTaskResponse EndPollForTask(IAsyncResult asyncResult)
{
return EndInvoke<PollForTaskResponse>(asyncResult);
}
#endregion
#region PutPipelineDefinition
/// <summary>
/// Adds tasks, schedules, and preconditions to the specified pipeline. You can use <code>PutPipelineDefinition</code>
/// to populate a new pipeline.
///
///
/// <para>
/// <code>PutPipelineDefinition</code> also validates the configuration as it adds it
/// to the pipeline. Changes to the pipeline are saved unless one of the following three
/// validation errors exists in the pipeline.
/// </para>
/// <ol> <li>An object is missing a name or identifier field.</li> <li>A string or reference
/// field is empty.</li> <li>The number of objects in the pipeline exceeds the maximum
/// allowed objects.</li> <li>The pipeline is in a FINISHED state.</li> </ol>
/// <para>
/// Pipeline object definitions are passed to the <code>PutPipelineDefinition</code>
/// action and returned by the <a>GetPipelineDefinition</a> action.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutPipelineDefinition service method.</param>
///
/// <returns>The response from the PutPipelineDefinition service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition">REST API Reference for PutPipelineDefinition Operation</seealso>
public virtual PutPipelineDefinitionResponse PutPipelineDefinition(PutPipelineDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutPipelineDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutPipelineDefinitionResponseUnmarshaller.Instance;
return Invoke<PutPipelineDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the PutPipelineDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutPipelineDefinition operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutPipelineDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition">REST API Reference for PutPipelineDefinition Operation</seealso>
public virtual IAsyncResult BeginPutPipelineDefinition(PutPipelineDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutPipelineDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutPipelineDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the PutPipelineDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutPipelineDefinition.</param>
///
/// <returns>Returns a PutPipelineDefinitionResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition">REST API Reference for PutPipelineDefinition Operation</seealso>
public virtual PutPipelineDefinitionResponse EndPutPipelineDefinition(IAsyncResult asyncResult)
{
return EndInvoke<PutPipelineDefinitionResponse>(asyncResult);
}
#endregion
#region QueryObjects
/// <summary>
/// Queries the specified pipeline for the names of objects that match the specified set
/// of conditions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the QueryObjects service method.</param>
///
/// <returns>The response from the QueryObjects service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects">REST API Reference for QueryObjects Operation</seealso>
public virtual QueryObjectsResponse QueryObjects(QueryObjectsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = QueryObjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = QueryObjectsResponseUnmarshaller.Instance;
return Invoke<QueryObjectsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the QueryObjects operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the QueryObjects operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndQueryObjects
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects">REST API Reference for QueryObjects Operation</seealso>
public virtual IAsyncResult BeginQueryObjects(QueryObjectsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = QueryObjectsRequestMarshaller.Instance;
options.ResponseUnmarshaller = QueryObjectsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the QueryObjects operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginQueryObjects.</param>
///
/// <returns>Returns a QueryObjectsResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects">REST API Reference for QueryObjects Operation</seealso>
public virtual QueryObjectsResponse EndQueryObjects(IAsyncResult asyncResult)
{
return EndInvoke<QueryObjectsResponse>(asyncResult);
}
#endregion
#region RemoveTags
/// <summary>
/// Removes existing tags from the specified pipeline.
/// </summary>
/// <param name="pipelineId">The ID of the pipeline.</param>
/// <param name="tagKeys">The keys of the tags to remove.</param>
///
/// <returns>The response from the RemoveTags service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso>
public virtual RemoveTagsResponse RemoveTags(string pipelineId, List<string> tagKeys)
{
var request = new RemoveTagsRequest();
request.PipelineId = pipelineId;
request.TagKeys = tagKeys;
return RemoveTags(request);
}
/// <summary>
/// Removes existing tags from the specified pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveTags service method.</param>
///
/// <returns>The response from the RemoveTags service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso>
public virtual RemoveTagsResponse RemoveTags(RemoveTagsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveTagsResponseUnmarshaller.Instance;
return Invoke<RemoveTagsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the RemoveTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemoveTags operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRemoveTags
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso>
public virtual IAsyncResult BeginRemoveTags(RemoveTagsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveTagsRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveTagsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the RemoveTags operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRemoveTags.</param>
///
/// <returns>Returns a RemoveTagsResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso>
public virtual RemoveTagsResponse EndRemoveTags(IAsyncResult asyncResult)
{
return EndInvoke<RemoveTagsResponse>(asyncResult);
}
#endregion
#region ReportTaskProgress
/// <summary>
/// Task runners call <code>ReportTaskProgress</code> when assigned a task to acknowledge
/// that it has the task. If the web service does not receive this acknowledgement within
/// 2 minutes, it assigns the task in a subsequent <a>PollForTask</a> call. After this
/// initial acknowledgement, the task runner only needs to report progress every 15 minutes
/// to maintain its ownership of the task. You can change this reporting time from 15
/// minutes by specifying a <code>reportProgressTimeout</code> field in your pipeline.
///
///
/// <para>
/// If a task runner does not report its status after 5 minutes, AWS Data Pipeline assumes
/// that the task runner is unable to process the task and reassigns the task in a subsequent
/// response to <a>PollForTask</a>. Task runners should call <code>ReportTaskProgress</code>
/// every 60 seconds.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ReportTaskProgress service method.</param>
///
/// <returns>The response from the ReportTaskProgress service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException">
/// The specified task was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskProgress">REST API Reference for ReportTaskProgress Operation</seealso>
public virtual ReportTaskProgressResponse ReportTaskProgress(ReportTaskProgressRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ReportTaskProgressRequestMarshaller.Instance;
options.ResponseUnmarshaller = ReportTaskProgressResponseUnmarshaller.Instance;
return Invoke<ReportTaskProgressResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ReportTaskProgress operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ReportTaskProgress operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndReportTaskProgress
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskProgress">REST API Reference for ReportTaskProgress Operation</seealso>
public virtual IAsyncResult BeginReportTaskProgress(ReportTaskProgressRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ReportTaskProgressRequestMarshaller.Instance;
options.ResponseUnmarshaller = ReportTaskProgressResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ReportTaskProgress operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginReportTaskProgress.</param>
///
/// <returns>Returns a ReportTaskProgressResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskProgress">REST API Reference for ReportTaskProgress Operation</seealso>
public virtual ReportTaskProgressResponse EndReportTaskProgress(IAsyncResult asyncResult)
{
return EndInvoke<ReportTaskProgressResponse>(asyncResult);
}
#endregion
#region ReportTaskRunnerHeartbeat
/// <summary>
/// Task runners call <code>ReportTaskRunnerHeartbeat</code> every 15 minutes to indicate
/// that they are operational. If the AWS Data Pipeline Task Runner is launched on a resource
/// managed by AWS Data Pipeline, the web service can use this call to detect when the
/// task runner application has failed and restart a new instance.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat service method.</param>
///
/// <returns>The response from the ReportTaskRunnerHeartbeat service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskRunnerHeartbeat">REST API Reference for ReportTaskRunnerHeartbeat Operation</seealso>
public virtual ReportTaskRunnerHeartbeatResponse ReportTaskRunnerHeartbeat(ReportTaskRunnerHeartbeatRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ReportTaskRunnerHeartbeatRequestMarshaller.Instance;
options.ResponseUnmarshaller = ReportTaskRunnerHeartbeatResponseUnmarshaller.Instance;
return Invoke<ReportTaskRunnerHeartbeatResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ReportTaskRunnerHeartbeat operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndReportTaskRunnerHeartbeat
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskRunnerHeartbeat">REST API Reference for ReportTaskRunnerHeartbeat Operation</seealso>
public virtual IAsyncResult BeginReportTaskRunnerHeartbeat(ReportTaskRunnerHeartbeatRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ReportTaskRunnerHeartbeatRequestMarshaller.Instance;
options.ResponseUnmarshaller = ReportTaskRunnerHeartbeatResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ReportTaskRunnerHeartbeat operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginReportTaskRunnerHeartbeat.</param>
///
/// <returns>Returns a ReportTaskRunnerHeartbeatResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskRunnerHeartbeat">REST API Reference for ReportTaskRunnerHeartbeat Operation</seealso>
public virtual ReportTaskRunnerHeartbeatResponse EndReportTaskRunnerHeartbeat(IAsyncResult asyncResult)
{
return EndInvoke<ReportTaskRunnerHeartbeatResponse>(asyncResult);
}
#endregion
#region SetStatus
/// <summary>
/// Requests that the status of the specified physical or logical pipeline objects be
/// updated in the specified pipeline. This update might not occur immediately, but is
/// eventually consistent. The status that can be set depends on the type of object (for
/// example, DataNode or Activity). You cannot perform this operation on <code>FINISHED</code>
/// pipelines and attempting to do so returns <code>InvalidRequestException</code>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SetStatus service method.</param>
///
/// <returns>The response from the SetStatus service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetStatus">REST API Reference for SetStatus Operation</seealso>
public virtual SetStatusResponse SetStatus(SetStatusRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SetStatusRequestMarshaller.Instance;
options.ResponseUnmarshaller = SetStatusResponseUnmarshaller.Instance;
return Invoke<SetStatusResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the SetStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetStatus operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSetStatus
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetStatus">REST API Reference for SetStatus Operation</seealso>
public virtual IAsyncResult BeginSetStatus(SetStatusRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = SetStatusRequestMarshaller.Instance;
options.ResponseUnmarshaller = SetStatusResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the SetStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetStatus.</param>
///
/// <returns>Returns a SetStatusResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetStatus">REST API Reference for SetStatus Operation</seealso>
public virtual SetStatusResponse EndSetStatus(IAsyncResult asyncResult)
{
return EndInvoke<SetStatusResponse>(asyncResult);
}
#endregion
#region SetTaskStatus
/// <summary>
/// Task runners call <code>SetTaskStatus</code> to notify AWS Data Pipeline that a task
/// is completed and provide information about the final status. A task runner makes this
/// call regardless of whether the task was sucessful. A task runner does not need to
/// call <code>SetTaskStatus</code> for tasks that are canceled by the web service during
/// a call to <a>ReportTaskProgress</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SetTaskStatus service method.</param>
///
/// <returns>The response from the SetTaskStatus service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException">
/// The specified task was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetTaskStatus">REST API Reference for SetTaskStatus Operation</seealso>
public virtual SetTaskStatusResponse SetTaskStatus(SetTaskStatusRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SetTaskStatusRequestMarshaller.Instance;
options.ResponseUnmarshaller = SetTaskStatusResponseUnmarshaller.Instance;
return Invoke<SetTaskStatusResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the SetTaskStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetTaskStatus operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSetTaskStatus
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetTaskStatus">REST API Reference for SetTaskStatus Operation</seealso>
public virtual IAsyncResult BeginSetTaskStatus(SetTaskStatusRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = SetTaskStatusRequestMarshaller.Instance;
options.ResponseUnmarshaller = SetTaskStatusResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the SetTaskStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetTaskStatus.</param>
///
/// <returns>Returns a SetTaskStatusResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetTaskStatus">REST API Reference for SetTaskStatus Operation</seealso>
public virtual SetTaskStatusResponse EndSetTaskStatus(IAsyncResult asyncResult)
{
return EndInvoke<SetTaskStatusResponse>(asyncResult);
}
#endregion
#region ValidatePipelineDefinition
/// <summary>
/// Validates the specified pipeline definition to ensure that it is well formed and can
/// be run without error.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ValidatePipelineDefinition service method.</param>
///
/// <returns>The response from the ValidatePipelineDefinition service method, as returned by DataPipeline.</returns>
/// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException">
/// An internal service error occurred.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException">
/// The request was not valid. Verify that your request was properly formatted, that the
/// signature was generated with the correct credentials, and that you haven't exceeded
/// any of the service limits for your account.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException">
/// The specified pipeline has been deleted.
/// </exception>
/// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException">
/// The specified pipeline was not found. Verify that you used the correct user and account
/// identifiers.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ValidatePipelineDefinition">REST API Reference for ValidatePipelineDefinition Operation</seealso>
public virtual ValidatePipelineDefinitionResponse ValidatePipelineDefinition(ValidatePipelineDefinitionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ValidatePipelineDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ValidatePipelineDefinitionResponseUnmarshaller.Instance;
return Invoke<ValidatePipelineDefinitionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ValidatePipelineDefinition operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ValidatePipelineDefinition operation on AmazonDataPipelineClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndValidatePipelineDefinition
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ValidatePipelineDefinition">REST API Reference for ValidatePipelineDefinition Operation</seealso>
public virtual IAsyncResult BeginValidatePipelineDefinition(ValidatePipelineDefinitionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ValidatePipelineDefinitionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ValidatePipelineDefinitionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ValidatePipelineDefinition operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginValidatePipelineDefinition.</param>
///
/// <returns>Returns a ValidatePipelineDefinitionResult from DataPipeline.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ValidatePipelineDefinition">REST API Reference for ValidatePipelineDefinition Operation</seealso>
public virtual ValidatePipelineDefinitionResponse EndValidatePipelineDefinition(IAsyncResult asyncResult)
{
return EndInvoke<ValidatePipelineDefinitionResponse>(asyncResult);
}
#endregion
}
} | 56.635446 | 191 | 0.673493 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/DataPipeline/Generated/_bcl35/AmazonDataPipelineClient.cs | 100,981 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UIVisualizerService.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#if NET || SL5
namespace Catel.Services
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using MVVM;
using Logging;
using MVVM.Properties;
using Reflection;
using Catel.Windows.Threading;
#if NET
using Windows;
#endif
#if NETFX_CORE
using global::Windows.UI.Xaml;
#else
using System.Windows.Controls;
#endif
/// <summary>
/// Service to show modal or non-modal popup windows.
/// <para/>
/// All windows will have to be registered manually or are be resolved via the <see cref="Catel.MVVM.IViewLocator"/>.
/// </summary>
public class UIVisualizerService : ViewModelServiceBase, IUIVisualizerService
{
#region Fields
/// <summary>
/// The log.
/// </summary>
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Dictionary of registered windows.
/// </summary>
protected readonly Dictionary<string, Type> RegisteredWindows = new Dictionary<string, Type>();
/// <summary>
/// The view locator.
/// </summary>
private readonly IViewLocator _viewLocator;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="UIVisualizerService"/> class.
/// </summary>
/// <param name="viewLocator">The view locator.</param>
/// <exception cref="ArgumentNullException">The <paramref name="viewLocator"/> is <c>null</c>.</exception>
public UIVisualizerService(IViewLocator viewLocator)
{
Argument.IsNotNull(() => viewLocator);
_viewLocator = viewLocator;
}
#region Properties
/// <summary>
/// Gets the type of the window that this implementation of the <see cref="IUIVisualizerService"/> interface
/// supports.
/// <para />
/// The default value is <c>Window</c> in WPF and <c>ChildWindow</c> in Silverlight.
/// </summary>
/// <value>
/// The type of the window.
/// </value>
protected virtual Type WindowType
{
get { return typeof(ContentControl); }
}
#endregion
#region Methods
/// <summary>
/// Determines whether the specified name is registered.
/// </summary>
/// <param name="name">The name.</param>
/// <returns><c>true</c> if the specified name is registered; otherwise, <c>false</c>.</returns>
/// <exception cref="ArgumentException">The <paramref name="name"/> is <c>null</c> or whitespace.</exception>
public virtual bool IsRegistered(string name)
{
Argument.IsNotNullOrWhitespace("name", name);
lock (RegisteredWindows)
{
return RegisteredWindows.ContainsKey(name);
}
}
/// <summary>
/// Registers the specified view model and the window type. This way, Catel knowns what
/// window to show when a specific view model window is requested.
/// </summary>
/// <param name="name">Name of the registered window.</param>
/// <param name="windowType">Type of the window.</param>
/// <param name="throwExceptionIfExists">if set to <c>true</c>, this method will throw an exception when already registered.</param>
/// <exception cref="System.InvalidOperationException"></exception>
/// <exception cref="ArgumentException">The <paramref name="name" /> is <c>null</c> or whitespace.</exception>
/// <exception cref="ArgumentException">The <paramref name="windowType" /> is not of type <see cref="WindowType" />.</exception>
public virtual void Register(string name, Type windowType, bool throwExceptionIfExists = true)
{
Argument.IsNotNullOrWhitespace("name", name);
Argument.IsNotNull("windowType", windowType);
Argument.IsOfType("windowType", windowType, WindowType);
lock (RegisteredWindows)
{
if (RegisteredWindows.ContainsKey(name))
{
if (throwExceptionIfExists)
{
throw new InvalidOperationException(Exceptions.ViewModelAlreadyRegistered);
}
}
RegisteredWindows.Add(name, windowType);
Log.Debug("Registered view model '{0}' in combination with '{1}' in the UIVisualizerService", name, windowType.FullName);
}
}
/// <summary>
/// This unregisters the specified view model.
/// </summary>
/// <param name="name">Name of the registered window.</param>
/// <returns>
/// <c>true</c> if the view model is unregistered; otherwise <c>false</c>.
/// </returns>
public virtual bool Unregister(string name)
{
lock (RegisteredWindows)
{
var result = RegisteredWindows.Remove(name);
if (result)
{
Log.Debug("Unregistered view model '{0}' in UIVisualizerService", name);
}
return result;
}
}
/// <summary>
/// Shows a window that is registered with the specified view model in a non-modal state.
/// </summary>
/// <param name="viewModel">The view model.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// <c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception>
/// <exception cref="ViewModelNotRegisteredException">The <paramref name="viewModel"/> is not registered by the <see cref="Register(string,System.Type,bool)"/> method first.</exception>
public virtual bool? Show(IViewModel viewModel, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNull("viewModel", viewModel);
var viewModelType = viewModel.GetType();
var viewModelTypeName = viewModelType.FullName;
RegisterViewForViewModelIfRequired(viewModelType);
return Show(viewModelTypeName, viewModel, completedProc);
}
/// <summary>
/// Shows a window that is registered with the specified view model in a non-modal state.
/// </summary>
/// <param name="viewModel">The view model.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// <c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception>
/// <exception cref="ViewModelNotRegisteredException">The <paramref name="viewModel"/> is not registered by the <see cref="Register(string,System.Type,bool)"/> method first.</exception>
public virtual async Task<bool?> ShowAsync(IViewModel viewModel, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNull("viewModel", viewModel);
var viewModelType = viewModel.GetType();
var viewModelTypeName = viewModelType.FullName;
RegisterViewForViewModelIfRequired(viewModelType);
return await ShowAsync(viewModelTypeName, viewModel, completedProc);
}
/// <summary>
/// Shows a window that is registered with the specified view model in a non-modal state.
/// </summary>
/// <param name="name">The name that the window is registered with.</param>
/// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// <c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
/// </returns>
/// <exception cref="ArgumentException">The <paramref name="name"/> is <c>null</c> or whitespace.</exception>
/// <exception cref="WindowNotRegisteredException">The <paramref name="name"/> is not registered by the <see cref="Register(string,System.Type, bool)"/> method first.</exception>
public virtual bool? Show(string name, object data, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNullOrWhitespace("name", name);
EnsureViewIsRegistered(name);
var window = CreateWindow(name, data, completedProc, false);
if (window != null)
{
return ShowWindow(window, false);
}
return false;
}
/// <summary>
/// Shows a window that is registered with the specified view model in a non-modal state.
/// </summary>
/// <param name="name">The name that the window is registered with.</param>
/// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// <c>true</c> if the popup window is successfully opened; otherwise <c>false</c>.
/// </returns>
/// <exception cref="ArgumentException">The <paramref name="name"/> is <c>null</c> or whitespace.</exception>
/// <exception cref="WindowNotRegisteredException">The <paramref name="name"/> is not registered by the <see cref="Register(string,System.Type, bool)"/> method first.</exception>
public virtual async Task<bool?> ShowAsync(string name, object data, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNullOrWhitespace("name", name);
EnsureViewIsRegistered(name);
var window = CreateWindow(name, data, completedProc, false);
if (window != null)
{
return await ShowWindowAsync(window, false);
}
return false;
}
/// <summary>
/// Shows a window that is registered with the specified view model in a modal state.
/// </summary>
/// <param name="viewModel">The view model.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// Nullable boolean representing the dialog result.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception>
/// <exception cref="WindowNotRegisteredException">The <paramref name="viewModel"/> is not registered by the <see cref="Register(string,System.Type,bool)"/> method first.</exception>
public virtual bool? ShowDialog(IViewModel viewModel, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNull("viewModel", viewModel);
var viewModelType = viewModel.GetType();
var viewModelTypeName = viewModelType.FullName;
RegisterViewForViewModelIfRequired(viewModelType);
return ShowDialog(viewModelTypeName, viewModel, completedProc);
}
/// <summary>
/// Shows a window that is registered with the specified view model in a modal state.
/// </summary>
/// <param name="viewModel">The view model.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// Nullable boolean representing the dialog result.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception>
/// <exception cref="WindowNotRegisteredException">The <paramref name="viewModel"/> is not registered by the <see cref="Register(string,System.Type,bool)"/> method first.</exception>
public virtual async Task<bool?> ShowDialogAsync(IViewModel viewModel, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNull("viewModel", viewModel);
var viewModelType = viewModel.GetType();
var viewModelTypeName = viewModelType.FullName;
RegisterViewForViewModelIfRequired(viewModelType);
return await ShowDialogAsync(viewModelTypeName, viewModel, completedProc);
}
/// <summary>
/// Shows a window that is registered with the specified view model in a modal state.
/// </summary>
/// <param name="name">The name that the window is registered with.</param>
/// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>Nullable boolean representing the dialog result.</returns>
/// <exception cref="ArgumentException">The <paramref name="name" /> is <c>null</c> or whitespace.</exception>
/// <exception cref="WindowNotRegisteredException">The <paramref name="name" /> is not registered by the <see cref="Register(string,System.Type,bool)" /> method first.</exception>
public virtual bool? ShowDialog(string name, object data, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNullOrWhitespace("name", name);
EnsureViewIsRegistered(name);
var window = CreateWindow(name, data, completedProc, true);
if (window != null)
{
return ShowWindow(window, true);
}
return false;
}
/// <summary>
/// Shows a window that is registered with the specified view model in a modal state.
/// </summary>
/// <param name="name">The name that the window is registered with.</param>
/// <param name="data">The data to set as data context. If <c>null</c>, the data context will be untouched.</param>
/// <param name="completedProc">The callback procedure that will be invoked as soon as the window is closed. This value can be <c>null</c>.</param>
/// <returns>
/// Nullable boolean representing the dialog result.
/// </returns>
/// <exception cref="ArgumentException">The <paramref name="name"/> is <c>null</c> or whitespace.</exception>
/// <exception cref="WindowNotRegisteredException">The <paramref name="name"/> is not registered by the <see cref="Register(string,System.Type,bool)"/> method first.</exception>
public virtual async Task<bool?> ShowDialogAsync(string name, object data, EventHandler<UICompletedEventArgs> completedProc = null)
{
Argument.IsNotNullOrWhitespace("name", name);
EnsureViewIsRegistered(name);
var window = CreateWindow(name, data, completedProc, true);
if (window != null)
{
return await ShowWindowAsync(window, true);
}
return false;
}
#if NET
/// <summary>
/// Gets the active window to use as parent window of new windows.
/// <para />
/// The default implementation returns the active window of the application.
/// </summary>
/// <returns>The active window.</returns>
protected virtual FrameworkElement GetActiveWindow()
{
return Application.Current.GetActiveWindow();
}
#endif
/// <summary>
/// Ensures that the specified view is registered.
/// </summary>
/// <param name="name">The name.</param>
/// <exception cref="WindowNotRegisteredException"></exception>
protected virtual void EnsureViewIsRegistered(string name)
{
lock (RegisteredWindows)
{
if (!RegisteredWindows.ContainsKey(name))
{
throw new WindowNotRegisteredException(name);
}
}
}
/// <summary>
/// Registers the view for the specified view model if required.
/// </summary>
/// <param name="viewModelType">Type of the view model.</param>
protected virtual void RegisterViewForViewModelIfRequired(Type viewModelType)
{
lock (RegisteredWindows)
{
if (!RegisteredWindows.ContainsKey(viewModelType.FullName))
{
var viewType = _viewLocator.ResolveView(viewModelType);
if (viewType != null)
{
this.Register(viewModelType, viewType);
}
}
}
}
/// <summary>
/// This creates the window from a key.
/// </summary>
/// <param name="name">The name that the window is registered with.</param>
/// <param name="data">The data that will be set as data context.</param>
/// <param name="completedProc">The completed callback.</param>
/// <param name="isModal">True if this is a ShowDialog request.</param>
/// <returns>The created window.</returns>
protected virtual FrameworkElement CreateWindow(string name, object data, EventHandler<UICompletedEventArgs> completedProc, bool isModal)
{
Type windowType;
lock (RegisteredWindows)
{
if (!RegisteredWindows.TryGetValue(name, out windowType))
{
return null;
}
}
return CreateWindow(windowType, data, completedProc, isModal);
}
/// <summary>
/// This creates the window of the specified type.
/// </summary>
/// <param name="windowType">The type of the window.</param>
/// <param name="data">The data that will be set as data context.</param>
/// <param name="completedProc">The completed callback.</param>
/// <param name="isModal">True if this is a ShowDialog request.</param>
/// <returns>The created window.</returns>
protected virtual FrameworkElement CreateWindow(Type windowType, object data, EventHandler<UICompletedEventArgs> completedProc, bool isModal)
{
var window = ViewHelper.ConstructViewWithViewModel(windowType, data);
#if NET
var activeWindow = GetActiveWindow();
if (window != activeWindow)
{
PropertyHelper.TrySetPropertyValue(window, "Owner", activeWindow);
}
#endif
if ((window != null) && (completedProc != null))
{
HandleCloseSubscription(window, data, completedProc, isModal);
}
return window;
}
/// <summary>
/// Handles the close subscription.
/// <para />
/// The default implementation uses the <see cref="DynamicEventListener"/>.
/// </summary>
/// <param name="window">The window.</param>
/// <param name="data">The data that will be set as data context.</param>
/// <param name="completedProc">The completed callback.</param>
/// <param name="isModal">True if this is a ShowDialog request.</param>
protected virtual void HandleCloseSubscription(object window, object data, EventHandler<UICompletedEventArgs> completedProc, bool isModal)
{
var dynamicEventListener = new DynamicEventListener(window, "Closed");
EventHandler closed = null;
closed = (sender, e) =>
{
bool? dialogResult = null;
PropertyHelper.TryGetPropertyValue(window, "DialogResult", out dialogResult);
completedProc(this, new UICompletedEventArgs(data, isModal ? dialogResult : null));
#if SILVERLIGHT
if (window is ChildWindow)
{
// Due to a bug in the latest version of the Silverlight toolkit, set parent to enabled again
// TODO: After every toolkit release, check if this code can be removed
Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, true);
}
#endif
dynamicEventListener.EventOccurred -= closed;
dynamicEventListener.UnsubscribeFromEvent();
};
dynamicEventListener.EventOccurred += closed;
}
/// <summary>
/// Shows the window.
/// </summary>
/// <param name="window">The window.</param>
/// <param name="showModal">If <c>true</c>, the window should be shown as modal.</param>
/// <returns><c>true</c> if the window is closed with success; otherwise <c>false</c> or <c>null</c>.</returns>
protected virtual bool? ShowWindow(FrameworkElement window, bool showModal)
{
if (showModal)
{
var showDialogMethodInfo = window.GetType().GetMethodEx("ShowDialog");
if (showDialogMethodInfo != null)
{
// Child window does not have a ShowDialog, so not null is allowed
bool? result = null;
window.Dispatcher.Invoke(() =>
{
// Safety net to prevent crashes when this is the main window
try
{
result = showDialogMethodInfo.Invoke(window, null) as bool?;
}
catch (Exception ex)
{
Log.Warning(ex, "An error occurred, returning null since we don't know the result");
}
});
return result;
}
Log.Warning("Method 'ShowDialog' not found on '{0}', falling back to 'Show'", window.GetType().Name);
}
var showMethodInfo = window.GetType().GetMethodEx("Show");
if (showMethodInfo == null)
{
var error = string.Format("Method 'Show' not found on '{0}', cannot show the window", window.GetType().Name);
Log.Error(error);
throw new NotSupportedException(error);
}
window.Dispatcher.Invoke(() => showMethodInfo.Invoke(window, null));
return null;
}
/// <summary>
/// Shows the window.
/// </summary>
/// <param name="window">The window.</param>
/// <param name="showModal">If <c>true</c>, the window should be shown as modal.</param>
/// <returns><c>true</c> if the window is closed with success; otherwise <c>false</c> or <c>null</c>.</returns>
protected virtual async Task<bool?> ShowWindowAsync(FrameworkElement window, bool showModal)
{
return await Task<bool?>.Factory.StartNew(() => ShowWindow(window, showModal));
}
#endregion
}
}
#endif | 44.877778 | 193 | 0.59008 | [
"MIT"
] | nix63/Catel | src/Catel.MVVM/Catel.MVVM.Shared/Services/UIVisualizerService.cs | 24,236 | 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("TeamSpark.AzureDay.SocialCounter.Shared")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TeamSpark.AzureDay.SocialCounter.Shared")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5b24f38f-edef-4db1-a936-7838aef6499c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.216216 | 84 | 0.750517 | [
"MIT"
] | AzureDay/2016-SocialCounter | TeamSpark.AzureDay.SocialCounter.Shared/Properties/AssemblyInfo.cs | 1,454 | C# |
using System;
using Xamarin.Forms;
namespace Native2Forms
{
/// <summary>
/// This Xamarin.Forms page will be opened from within a 'native' app on iOS and Android
/// </summary>
public class MySecondPage : ContentPage
{
public MySecondPage ()
{
var label = new Label {
Text = "This is the Xamarin.Forms page",
Font = Font.SystemFontOfSize (36),
};
Content = new StackLayout {
Spacing = 30,
VerticalOptions = LayoutOptions.Start,
Children = {
label,
}
};
}
}
}
| 18.428571 | 89 | 0.637597 | [
"Apache-2.0"
] | Alshaikh-Abdalrahman/jedoo | Native2Forms/Native2Forms/MySecondPage.cs | 518 | C# |
#region License
// Copyright (c) 2011 Effort Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
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("Effort.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Effort.Test")]
[assembly: AssemblyCopyright("")]
[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("73598583-02bb-4d62-9d48-2257f1bb3e57")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.35 | 84 | 0.754131 | [
"MIT"
] | JonathanMagnan/effort | Main/Source/misc/Backup/Properties/AssemblyInfo.cs | 2,483 | C# |
// Copyright (c) 2015 - 2018 Doozy Entertainment / Marlink Trading SRL. All Rights Reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using QuickEditor;
using UnityEditor.AnimatedValues;
namespace DoozyUI
{
public partial class ControlPanelWindow : QWindow
{
AnimBool _UICanvasesAnimBool;
AnimBool UICanvasesAnimBool { get { if(_UICanvasesAnimBool == null) { _UICanvasesAnimBool = new AnimBool(true, Repaint); } return _UICanvasesAnimBool; } }
void InitPageUICanvases()
{
DUIData.Instance.ScanForUICanvases(true);
DUIData.Instance.ValidateUICanvases();
}
void DrawPageUICanvases()
{
DrawPageHeader("UICanvases", QColors.Blue, "Database", QUI.IsProSkin ? QColors.UnityLight : QColors.UnityMild, DUIResources.pageIconUICanvases);
QUI.Space(6);
DrawPageUICanvasesRefreshButton(WindowSettings.CurrentPageContentWidth);
QUI.Space(SPACE_16);
QUI.BeginHorizontal(WindowSettings.CurrentPageContentWidth);
{
QUI.BeginVertical(WindowSettings.CurrentPageContentWidth - SPACE_8);
{
DrawStringList(DUIData.Instance.DatabaseUICanvases, WindowSettings.CurrentPageContentWidth - SPACE_8, UICanvasesAnimBool);
}
QUI.EndVertical();
}
QUI.EndHorizontal();
QUI.Space(SPACE_16);
}
void DrawPageUICanvasesRefreshButton(float width)
{
QUI.BeginHorizontal(width);
{
QUI.Space(SPACE_8);
if(QUI.SlicedButton("Refresh the UICanvases Database", QColors.Color.Gray, width - 16, 18))
{
DUIData.Instance.ScanForUICanvases(true);
}
QUI.Space(SPACE_8);
}
QUI.EndHorizontal();
}
}
} | 35.637931 | 162 | 0.619739 | [
"Apache-2.0"
] | endovitsky/Arkanoid | Assets/Packages/DoozyUI/Scripts/Editor/Windows/ControlPanelWindowUICanvases.cs | 2,069 | C# |
using System.Data;
using System.Management.Automation;
using Sitecore;
using Sitecore.ContentSearch.Utilities;
using Sitecore.Install.Security;
using Sitecore.Security.Accounts;
using Spe.Commands.Security;
namespace Spe.Commands.Packages
{
[Cmdlet(VerbsCommon.New, "SecuritySource",DefaultParameterSetName = "Filter")]
[OutputType(typeof (SecuritySource))]
public class NewSecuritySourceCommand : BasePackageCommand
{
private SecuritySource source;
[Parameter(ParameterSetName = "Account", ValueFromPipeline = true, Mandatory = true, Position = 1)]
public Account Account { get; set; }
[Parameter(ParameterSetName = "Id", ValueFromPipeline = true, Mandatory = true, Position = 1)]
[ValidateNotNullOrEmpty]
public AccountIdentity Identity { get; set; }
[Parameter(ParameterSetName = "Filter", ValueFromPipeline = true, Mandatory = true, Position = 1)]
[ValidateNotNullOrEmpty]
public string[] Filter { get; set; }
[Parameter(ParameterSetName = "Filter", ValueFromPipeline = true, Position = 2)]
[Parameter(ParameterSetName = "Id", ValueFromPipeline = true, Position = 2)]
public AccountType AccountType { get; set; }
[Parameter(Position = 0, Mandatory = true)]
public string Name { get; set; }
protected override void BeginProcessing()
{
source = new SecuritySource { Name = Name }; //Create source – source should be based on BaseSource
}
protected override void ProcessRecord()
{
switch (ParameterSetName)
{
case "Account":
source.AddAccount(new AccountString(Account.Name, Account.AccountType));
break;
case "Id":
if (Role.Exists(Identity.Name) && (AccountType == AccountType.Role || AccountType == AccountType.Unknown))
{
source.AddAccount(new AccountString(Identity.Name, AccountType.Role));
}
else if (User.Exists(Identity.Name) && (AccountType == AccountType.User || AccountType == AccountType.Unknown))
{
source.AddAccount(new AccountString(Identity.Name, AccountType.User));
}
else
{
WriteError(typeof(ObjectNotFoundException), $"Cannot find any account of type {AccountType} with identity '{Identity.Name}'.",
ErrorIds.AccountNotFound, ErrorCategory.ObjectNotFound, Identity);
}
break;
case "Filter":
foreach (var filter in Filter)
{
if (AccountType == AccountType.User || AccountType == AccountType.Unknown)
{
WildcardFilter(filter, UserManager.GetUsers(), user => user.Name)
.ForEach(user => source.AddAccount(new AccountString(user.Name, AccountType.User)));
}
if (AccountType == AccountType.Role || AccountType == AccountType.Unknown)
{
WildcardFilter(filter, Context.User.Delegation.GetManagedRoles(true),
role => role.Name)
.ForEach(role => source.AddAccount(new AccountString(role.Name, AccountType.Role)));
}
}
break;
}
}
protected override void EndProcessing()
{
WriteObject(source, false);
}
}
} | 43.597701 | 151 | 0.550751 | [
"MIT"
] | PavloGlazunov/Console | src/Spe/Commands/Packages/NewSecuritySourceCommand.cs | 3,797 | 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(".NET Micro Framework Toolbox - POP3 Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NETMFToolbox.com")]
[assembly: AssemblyProduct(".NET Micro Framework Toolbox - POP3 Client")]
[assembly: AssemblyCopyright("Copyright © NETMFToolbox.com 2011-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("4.1.0.0")]
[assembly: AssemblyFileVersion("4.1.0.0")]
| 36.423077 | 77 | 0.75396 | [
"Apache-2.0"
] | JakeLardinois/NetMF.Toolbox | Framework/NET.POP3_Client/Properties/AssemblyInfo (4.1).cs | 948 | C# |
using System;
namespace Programatica.Framework.Core.Adapter
{
public class AuthUserAdapter : IAuthUserAdapter
{
public AuthUserAdapter() : base()
{ }
public string Name
{
get
{
return Environment.UserName;
}
}
public string Password
{ get; }
public string AuthenticationType
{
get
{
return "";
}
}
public DateTime LastLoginDateTime
{ get; }
}
}
| 18.030303 | 52 | 0.435294 | [
"MIT"
] | ruialexrib/Programatica.Framework | Programatica.Framework.Core/Adapter/AuthUserAdapter.cs | 597 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Patterns
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 24.52381 | 70 | 0.574757 | [
"MIT"
] | xiaomi7732/CodeSaar | DI/src/Patterns/Program.cs | 515 | C# |
using Amazon.JSII.Runtime.Deputy;
namespace Amazon.JSII.Tests.CalculatorNamespace
{
/// <remarks>
/// stability: Experimental
/// </remarks>
[JsiiClass(nativeType: typeof(Amazon.JSII.Tests.CalculatorNamespace.DoubleTrouble), fullyQualifiedName: "jsii-calc.DoubleTrouble")]
public class DoubleTrouble : DeputyBase, Amazon.JSII.Tests.CalculatorNamespace.IFriendlyRandomGenerator
{
public DoubleTrouble(): base(new DeputyProps(new object[]{}))
{
}
protected DoubleTrouble(ByRefValue reference): base(reference)
{
}
protected DoubleTrouble(DeputyProps props): base(props)
{
}
/// <summary>Say hello!</summary>
/// <remarks>
/// stability: Experimental
/// </remarks>
[JsiiMethod(name: "hello", returnsJson: "{\"type\":{\"primitive\":\"string\"}}", isOverride: true)]
public virtual string Hello()
{
return InvokeInstanceMethod<string>(new System.Type[]{}, new object[]{});
}
/// <summary>Returns another random number.</summary>
/// <remarks>
/// stability: Experimental
/// </remarks>
[JsiiMethod(name: "next", returnsJson: "{\"type\":{\"primitive\":\"number\"}}", isOverride: true)]
public virtual double Next()
{
return InvokeInstanceMethod<double>(new System.Type[]{}, new object[]{});
}
}
}
| 32.931818 | 135 | 0.599034 | [
"Apache-2.0"
] | NyanKiyoshi/jsii | packages/jsii-pacmak/test/expected.jsii-calc/dotnet/Amazon.JSII.Tests.CalculatorPackageId/Amazon/JSII/Tests/CalculatorNamespace/DoubleTrouble.cs | 1,449 | C# |
using System;
using System.Collections.Generic;
using CodeHatch.Build;
using CodeHatch.Engine.Networking;
using CodeHatch.Engine.Core.Networking;
using CodeHatch.Blocks;
using CodeHatch.Blocks.Networking.Events;
using CodeHatch.Networking.Events.Entities;
using CodeHatch.Networking.Events.Entities.Players;
using CodeHatch.Networking.Events.Players;
using CodeHatch.Networking.Events.Social;
namespace Oxide.Plugins
{
[Info("SimpleBlockProtection", "Jonty", "1.0.0")]
public class JontysBlockProtection : ReignOfKingsPlugin
{
void Loaded()
{
}
private void OnCubeTakeDamage(CubeDamageEvent Event)
{
Player BlockOwner = Event.Entity.Owner;
Player Me = Event.Damage.DamageSource.Owner;
if (Me != BlockOwner)
{
return;
}
}
}
} | 24.2 | 59 | 0.689492 | [
"MIT"
] | john-clark/rust-oxide-umod | oxide/plugins/other/JontysBlockProtection.cs | 847 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.ErrorReporting.V1Beta1
{
/// <summary>Settings for <see cref="ErrorStatsServiceClient"/> instances.</summary>
public sealed partial class ErrorStatsServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ErrorStatsServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ErrorStatsServiceSettings"/>.</returns>
public static ErrorStatsServiceSettings GetDefault() => new ErrorStatsServiceSettings();
/// <summary>Constructs a new <see cref="ErrorStatsServiceSettings"/> object with default settings.</summary>
public ErrorStatsServiceSettings()
{
}
private ErrorStatsServiceSettings(ErrorStatsServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListGroupStatsSettings = existing.ListGroupStatsSettings;
ListEventsSettings = existing.ListEventsSettings;
DeleteEventsSettings = existing.DeleteEventsSettings;
OnCopy(existing);
}
partial void OnCopy(ErrorStatsServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorStatsServiceClient.ListGroupStats</c> and <c>ErrorStatsServiceClient.ListGroupStatsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListGroupStatsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorStatsServiceClient.ListEvents</c> and <c>ErrorStatsServiceClient.ListEventsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListEventsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorStatsServiceClient.DeleteEvents</c> and <c>ErrorStatsServiceClient.DeleteEventsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteEventsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ErrorStatsServiceSettings"/> object.</returns>
public ErrorStatsServiceSettings Clone() => new ErrorStatsServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ErrorStatsServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class ErrorStatsServiceClientBuilder : gaxgrpc::ClientBuilderBase<ErrorStatsServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ErrorStatsServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ErrorStatsServiceClientBuilder()
{
UseJwtAccessWithScopes = ErrorStatsServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ErrorStatsServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ErrorStatsServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ErrorStatsServiceClient Build()
{
ErrorStatsServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ErrorStatsServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ErrorStatsServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ErrorStatsServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ErrorStatsServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ErrorStatsServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ErrorStatsServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ErrorStatsServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ErrorStatsServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ErrorStatsServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ErrorStatsService client wrapper, for convenient use.</summary>
/// <remarks>
/// An API for retrieving and managing error statistics as well as data for
/// individual events.
/// </remarks>
public abstract partial class ErrorStatsServiceClient
{
/// <summary>
/// The default endpoint for the ErrorStatsService service, which is a host of
/// "clouderrorreporting.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "clouderrorreporting.googleapis.com:443";
/// <summary>The default ErrorStatsService scopes.</summary>
/// <remarks>
/// The default ErrorStatsService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ErrorStatsServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ErrorStatsServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ErrorStatsServiceClient"/>.</returns>
public static stt::Task<ErrorStatsServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ErrorStatsServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ErrorStatsServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ErrorStatsServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns>
public static ErrorStatsServiceClient Create() => new ErrorStatsServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ErrorStatsServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns>
internal static ErrorStatsServiceClient Create(grpccore::CallInvoker callInvoker, ErrorStatsServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ErrorStatsService.ErrorStatsServiceClient grpcClient = new ErrorStatsService.ErrorStatsServiceClient(callInvoker);
return new ErrorStatsServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ErrorStatsService client</summary>
public virtual ErrorStatsService.ErrorStatsServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}`
/// and `{projectNumber}` can be found in the
/// [Google Cloud Console](https://support.google.com/cloud/answer/6158840).
///
/// Examples: `projects/my-project-123`, `projects/5551234`.
/// </param>
/// <param name="timeRange">
/// Optional. List data for the given time range.
/// If not set, a default time range is used. The field
/// &lt;code&gt;time_range_begin&lt;/code&gt; in the response will specify the beginning
/// of this time range.
/// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time
/// range are returned, unless the request contains an explicit
/// &lt;code&gt;group_id&lt;/code&gt; list. If a &lt;code&gt;group_id&lt;/code&gt; list is given, also
/// &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero occurrences are returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(string projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListGroupStats(new ListGroupStatsRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
TimeRange = timeRange,
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}`
/// and `{projectNumber}` can be found in the
/// [Google Cloud Console](https://support.google.com/cloud/answer/6158840).
///
/// Examples: `projects/my-project-123`, `projects/5551234`.
/// </param>
/// <param name="timeRange">
/// Optional. List data for the given time range.
/// If not set, a default time range is used. The field
/// &lt;code&gt;time_range_begin&lt;/code&gt; in the response will specify the beginning
/// of this time range.
/// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time
/// range are returned, unless the request contains an explicit
/// &lt;code&gt;group_id&lt;/code&gt; list. If a &lt;code&gt;group_id&lt;/code&gt; list is given, also
/// &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero occurrences are returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(string projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListGroupStatsAsync(new ListGroupStatsRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
TimeRange = timeRange,
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}`
/// and `{projectNumber}` can be found in the
/// [Google Cloud Console](https://support.google.com/cloud/answer/6158840).
///
/// Examples: `projects/my-project-123`, `projects/5551234`.
/// </param>
/// <param name="timeRange">
/// Optional. List data for the given time range.
/// If not set, a default time range is used. The field
/// &lt;code&gt;time_range_begin&lt;/code&gt; in the response will specify the beginning
/// of this time range.
/// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time
/// range are returned, unless the request contains an explicit
/// &lt;code&gt;group_id&lt;/code&gt; list. If a &lt;code&gt;group_id&lt;/code&gt; list is given, also
/// &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero occurrences are returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(gagr::ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListGroupStats(new ListGroupStatsRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
TimeRange = timeRange,
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}`
/// and `{projectNumber}` can be found in the
/// [Google Cloud Console](https://support.google.com/cloud/answer/6158840).
///
/// Examples: `projects/my-project-123`, `projects/5551234`.
/// </param>
/// <param name="timeRange">
/// Optional. List data for the given time range.
/// If not set, a default time range is used. The field
/// &lt;code&gt;time_range_begin&lt;/code&gt; in the response will specify the beginning
/// of this time range.
/// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time
/// range are returned, unless the request contains an explicit
/// &lt;code&gt;group_id&lt;/code&gt; list. If a &lt;code&gt;group_id&lt;/code&gt; list is given, also
/// &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero occurrences are returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(gagr::ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListGroupStatsAsync(new ListGroupStatsRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
TimeRange = timeRange,
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns>
public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="groupId">
/// Required. The group for which events shall be returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns>
public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(string projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEvents(new ListEventsRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="groupId">
/// Required. The group for which events shall be returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(string projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEventsAsync(new ListEventsRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="groupId">
/// Required. The group for which events shall be returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns>
public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(gagr::ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEvents(new ListEventsRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="groupId">
/// Required. The group for which events shall be returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(gagr::ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEventsAsync(new ListEventsRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DeleteEventsResponse DeleteEvents(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(DeleteEventsRequest request, st::CancellationToken cancellationToken) =>
DeleteEventsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DeleteEventsResponse DeleteEvents(string projectName, gaxgrpc::CallSettings callSettings = null) =>
DeleteEvents(new DeleteEventsRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
}, callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(string projectName, gaxgrpc::CallSettings callSettings = null) =>
DeleteEventsAsync(new DeleteEventsRequest
{
ProjectName = gax::GaxPreconditions.CheckNotNullOrEmpty(projectName, nameof(projectName)),
}, callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(string projectName, st::CancellationToken cancellationToken) =>
DeleteEventsAsync(projectName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DeleteEventsResponse DeleteEvents(gagr::ProjectName projectName, gaxgrpc::CallSettings callSettings = null) =>
DeleteEvents(new DeleteEventsRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
}, callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(gagr::ProjectName projectName, gaxgrpc::CallSettings callSettings = null) =>
DeleteEventsAsync(new DeleteEventsRequest
{
ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
}, callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// Required. The resource name of the Google Cloud Platform project. Written
/// as `projects/{projectID}`, where `{projectID}` is the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
///
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync(gagr::ProjectName projectName, st::CancellationToken cancellationToken) =>
DeleteEventsAsync(projectName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ErrorStatsService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// An API for retrieving and managing error statistics as well as data for
/// individual events.
/// </remarks>
public sealed partial class ErrorStatsServiceClientImpl : ErrorStatsServiceClient
{
private readonly gaxgrpc::ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> _callListGroupStats;
private readonly gaxgrpc::ApiCall<ListEventsRequest, ListEventsResponse> _callListEvents;
private readonly gaxgrpc::ApiCall<DeleteEventsRequest, DeleteEventsResponse> _callDeleteEvents;
/// <summary>
/// Constructs a client wrapper for the ErrorStatsService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ErrorStatsServiceSettings"/> used within this client.</param>
public ErrorStatsServiceClientImpl(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings settings)
{
GrpcClient = grpcClient;
ErrorStatsServiceSettings effectiveSettings = settings ?? ErrorStatsServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListGroupStats = clientHelper.BuildApiCall<ListGroupStatsRequest, ListGroupStatsResponse>(grpcClient.ListGroupStatsAsync, grpcClient.ListGroupStats, effectiveSettings.ListGroupStatsSettings).WithGoogleRequestParam("project_name", request => request.ProjectName);
Modify_ApiCall(ref _callListGroupStats);
Modify_ListGroupStatsApiCall(ref _callListGroupStats);
_callListEvents = clientHelper.BuildApiCall<ListEventsRequest, ListEventsResponse>(grpcClient.ListEventsAsync, grpcClient.ListEvents, effectiveSettings.ListEventsSettings).WithGoogleRequestParam("project_name", request => request.ProjectName);
Modify_ApiCall(ref _callListEvents);
Modify_ListEventsApiCall(ref _callListEvents);
_callDeleteEvents = clientHelper.BuildApiCall<DeleteEventsRequest, DeleteEventsResponse>(grpcClient.DeleteEventsAsync, grpcClient.DeleteEvents, effectiveSettings.DeleteEventsSettings).WithGoogleRequestParam("project_name", request => request.ProjectName);
Modify_ApiCall(ref _callDeleteEvents);
Modify_DeleteEventsApiCall(ref _callDeleteEvents);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListGroupStatsApiCall(ref gaxgrpc::ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> call);
partial void Modify_ListEventsApiCall(ref gaxgrpc::ApiCall<ListEventsRequest, ListEventsResponse> call);
partial void Modify_DeleteEventsApiCall(ref gaxgrpc::ApiCall<DeleteEventsRequest, DeleteEventsResponse> call);
partial void OnConstruction(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ErrorStatsService client</summary>
public override ErrorStatsService.ErrorStatsServiceClient GrpcClient { get; }
partial void Modify_ListGroupStatsRequest(ref ListGroupStatsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListEventsRequest(ref ListEventsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteEventsRequest(ref DeleteEventsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public override gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListGroupStatsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings);
}
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListGroupStatsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings);
}
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="ErrorEvent"/> resources.</returns>
public override gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListEventsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings);
}
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(ListEventsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListEventsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings);
}
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override DeleteEventsResponse DeleteEvents(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteEventsRequest(ref request, ref callSettings);
return _callDeleteEvents.Sync(request, callSettings);
}
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<DeleteEventsResponse> DeleteEventsAsync(DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteEventsRequest(ref request, ref callSettings);
return _callDeleteEvents.Async(request, callSettings);
}
}
public partial class ListGroupStatsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListEventsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListGroupStatsResponse : gaxgrpc::IPageResponse<ErrorGroupStats>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<ErrorGroupStats> GetEnumerator() => ErrorGroupStats.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class ListEventsResponse : gaxgrpc::IPageResponse<ErrorEvent>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<ErrorEvent> GetEnumerator() => ErrorEvents.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| 58.152902 | 556 | 0.659342 | [
"Apache-2.0"
] | Mattlk13/google-cloud-dotnet | apis/Google.Cloud.ErrorReporting.V1Beta1/Google.Cloud.ErrorReporting.V1Beta1/ErrorStatsServiceClient.g.cs | 52,105 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using FluentAssertions;
using NUnit.Framework;
namespace Azure.IoT.TimeSeriesInsights.Tests
{
public class TimeSeriesIdTests : E2eTestBase
{
private static readonly TimeSpan s_retryDelay = TimeSpan.FromSeconds(20);
// This is the GUID that TSI uses to represent the default type for a Time Series Instance.
// TODO: replace hardcoding the Type GUID when the Types resource has been implemented.
private const string DefaultType = "1be09af9-f089-4d6b-9f0b-48018b5f7393";
private const int MaxNumberOfRetries = 10;
public TimeSeriesIdTests(bool isAsync)
: base(isAsync)
{
}
[Test]
public async Task TimeSeriesId_CreateInstanceWith3Keys()
{
// Arrange
TimeSeriesInsightsClient client = GetClient();
// Create a Time Series Id with 3 keys. Middle key is a null
var idWithNull = new TimeSeriesId(
Recording.GenerateAlphaNumericId(string.Empty, 5),
null,
Recording.GenerateAlphaNumericId(string.Empty, 5));
var timeSeriesInstances = new List<TimeSeriesInstance>
{
new TimeSeriesInstance(idWithNull, DefaultType),
};
// Act and assert
try
{
// Create TSI instances
Response<TimeSeriesOperationError[]> createInstancesResult = await client
.Instances
.CreateOrReplaceAsync(timeSeriesInstances)
.ConfigureAwait(false);
// Assert that the result error array does not contain any object that is set
createInstancesResult.Value.Should().OnlyContain((errorResult) => errorResult == null);
// This retry logic was added as the TSI instance are not immediately available after creation
await TestRetryHelper.RetryAsync<Response<InstancesOperationResult[]>>(async () =>
{
// Get the instance with a null item in its Id
Response<InstancesOperationResult[]> getInstanceWithNullInId = await client
.Instances
.GetAsync(new List<TimeSeriesId> { idWithNull })
.ConfigureAwait(false);
getInstanceWithNullInId.Value.Length.Should().Be(1);
InstancesOperationResult resultItem = getInstanceWithNullInId.Value.First();
resultItem.Error.Should().BeNull();
resultItem.Instance.Should().NotBeNull();
resultItem.Instance.TimeSeriesId.ToArray().Length.Should().Be(3);
resultItem.Instance.TimeSeriesId.ToArray()[1].Should().BeNull();
return null;
}, MaxNumberOfRetries, s_retryDelay);
}
finally
{
// clean up
try
{
Response<TimeSeriesOperationError[]> deleteInstancesResponse = await client
.Instances
.DeleteAsync(timeSeriesInstances.Select((instance) => instance.TimeSeriesId))
.ConfigureAwait(false);
// Assert that the response array does not have any error object set
deleteInstancesResponse.Value.Should().OnlyContain((errorResult) => errorResult == null);
}
catch (Exception ex)
{
Console.WriteLine($"Test clean up failed: {ex.Message}");
throw;
}
}
}
[Test]
public void TimeSeriesId_GetIdForStringKeys()
{
// Arrange
var key1 = "B17";
var key2 = "F1";
var key3 = "R400";
var tsiId = new TimeSeriesId(key1, key2, key3);
// Act
var idAsString = tsiId.ToString();
// Assert
idAsString.Should().Be($"[\"{key1}\",\"{key2}\",\"{key3}\"]");
}
[Test]
public void TimeSeriesId_ToArrayWith1StringKey()
{
// Arrange
var key1 = "B17";
var tsiId = new TimeSeriesId(key1);
// Act
var idAsArray = tsiId.ToArray();
// Assert
idAsArray.Should().Equal(new string[] { key1 });
}
[Test]
public void TimeSeriesId_ToArrayWith2StringKeys()
{
// Arrange
var key1 = "B17";
var key2 = "F1";
var tsiId = new TimeSeriesId(key1, key2);
// Act
var idAsArray = tsiId.ToArray();
// Assert
idAsArray.Should().Equal(new string[] { key1, key2 });
}
[Test]
public void TimeSeriesId_ToArrayWith3StringKeys()
{
// Arrange
var key1 = "B17";
var key2 = "F1";
var key3 = "R1";
var tsiId = new TimeSeriesId(key1, key2, key3);
// Act
var idAsArray = tsiId.ToArray();
// Assert
idAsArray.Should().Equal(new string[] { key1, key2, key3 });
}
}
}
| 34.55625 | 110 | 0.539338 | [
"MIT"
] | AzureAppServiceCLI/azure-sdk-for-net | sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/tests/TimeSeriesIdTests.cs | 5,531 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 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 HOLDER 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.
*/
using System;
using System.IO;
class MainClass
{
public static void Main(string[] args)
{
Export.verbose_debugging = true;
if ((args.Length != 1) && (args.Length != 2))
{
Console.WriteLine("Usage: ");
Console.WriteLine(" verify <archive> [optional copy]");
Environment.Exit(1);
}
try
{
string filename = args[0];
Stream g = null;
if (args.Length == 2)
{
g = new FileStream(args[1], FileMode.Create);
}
Stream f = new FileStream(filename, FileMode.Open);
bool cancelling = false;
new Export().verify(f, g, (Export.cancellingCallback)delegate() { return cancelling; });
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Permission denied, check access rights to file");
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found, verify filename is correct");
}
catch (IOException)
{
Console.WriteLine("IO Exception, file may be truncated.");
}
catch (BlockChecksumFailed)
{
Console.WriteLine("Verification failed, file appears to be corrupt");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
| 36.185185 | 101 | 0.613101 | [
"BSD-2-Clause"
] | ChrisH4rding/xenadmin | xva_verify/verify_main.cs | 2,933 | C# |
using System;
namespace OpenCvSharp.ML
{
#if LANG_JP
/// <summary>
/// MLPモデルクラス
/// </summary>
#else
/// <summary>
/// Artificial Neural Networks - Multi-Layer Perceptrons.
/// </summary>
#endif
public class ANN_MLP : StatModel
{
/// <summary>
/// Track whether Dispose has been called
/// </summary>
private bool disposed;
private Ptr<ANN_MLP> ptrObj;
#region Init and Disposal
/// <summary>
/// Creates instance by raw pointer cv::ml::ANN_MLP*
/// </summary>
protected ANN_MLP(IntPtr p)
: base()
{
ptrObj = new Ptr<ANN_MLP>(p);
ptr = ptrObj.Get();
}
/// <summary>
/// Creates the empty model.
/// </summary>
/// <returns></returns>
public static ANN_MLP Create()
{
IntPtr ptr = NativeMethods.ml_ANN_MLP_create();
return new ANN_MLP(ptr);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">
/// If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and unmanaged resources can be disposed.
/// If false, the method has been called by the runtime from inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed.
/// </param>
protected override void Dispose(bool disposing)
{
if (!disposed)
{
try
{
if (disposing)
{
if (ptrObj != null)
{
ptrObj.Dispose();
ptrObj = null;
}
}
ptr = IntPtr.Zero;
disposed = true;
}
finally
{
base.Dispose(disposing);
}
}
}
#endregion
#region Properties
/// <summary>
/// Termination criteria of the training algorithm.
/// </summary>
public TermCriteria TermCriteria
{
get { return NativeMethods.ml_ANN_MLP_getTermCriteria(ptr); }
set { NativeMethods.ml_ANN_MLP_setTermCriteria(ptr, value); }
}
/// <summary>
/// Strength of the weight gradient term.
/// The recommended value is about 0.1. Default value is 0.1.
/// </summary>
public double BackpropWeightScale
{
get { return NativeMethods.ml_ANN_MLP_getBackpropWeightScale(ptr); }
set { NativeMethods.ml_ANN_MLP_setBackpropWeightScale(ptr, value); }
}
/// <summary>
/// Strength of the momentum term (the difference between weights on the 2 previous iterations).
/// This parameter provides some inertia to smooth the random fluctuations of the weights.
/// It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or
/// so is good enough. Default value is 0.1.
/// </summary>
public double BackpropMomentumScale
{
get { return NativeMethods.ml_ANN_MLP_getBackpropMomentumScale(ptr); }
set { NativeMethods.ml_ANN_MLP_setBackpropMomentumScale(ptr, value); }
}
/// <summary>
/// Initial value Delta_0 of update-values Delta_{ij}. Default value is 0.1.
/// </summary>
// ReSharper disable once InconsistentNaming
public double RpropDW0
{
get { return NativeMethods.ml_ANN_MLP_getRpropDW0(ptr); }
set { NativeMethods.ml_ANN_MLP_setRpropDW0(ptr, value); }
}
/// <summary>
/// Increase factor eta^+.
/// It must be >1. Default value is 1.2.
/// </summary>
// ReSharper disable once InconsistentNaming
public double RpropDWPlus
{
get { return NativeMethods.ml_ANN_MLP_getRpropDWPlus(ptr); }
set { NativeMethods.ml_ANN_MLP_setRpropDWPlus(ptr, value); }
}
/// <summary>
/// Decrease factor eta^-.
/// It must be \>1. Default value is 0.5.
/// </summary>
// ReSharper disable once InconsistentNaming
public double RpropDWMinus
{
get { return NativeMethods.ml_ANN_MLP_getRpropDWPlus(ptr); }
set { NativeMethods.ml_ANN_MLP_setRpropDWPlus(ptr, value); }
}
/// <summary>
/// Update-values lower limit Delta_{min}.
/// It must be positive. Default value is FLT_EPSILON.
/// </summary>
// ReSharper disable once InconsistentNaming
public double RpropDWMin
{
get { return NativeMethods.ml_ANN_MLP_getRpropDWMin(ptr); }
set { NativeMethods.ml_ANN_MLP_setRpropDWMin(ptr, value); }
}
/// <summary>
/// Update-values upper limit Delta_{max}.
/// It must be >1. Default value is 50.
/// </summary>
// ReSharper disable once InconsistentNaming
public double RpropDWMax
{
get { return NativeMethods.ml_ANN_MLP_getRpropDWMax(ptr); }
set { NativeMethods.ml_ANN_MLP_setRpropDWMax(ptr, value); }
}
#endregion
#region Methods
/// <summary>
/// Integer vector specifying the number of neurons in each layer including the input and output layers.
/// The very first element specifies the number of elements in the input layer.
/// The last element - number of elements in the output layer.Default value is empty Mat.
/// </summary>
/// <param name="layerSizes"></param>
public virtual void SetLayerSizes(InputArray layerSizes)
{
if (disposed)
throw new ObjectDisposedException(GetType().Name);
if (layerSizes == null)
throw new ArgumentNullException("nameof(layerSizes)");
NativeMethods.ml_ANN_MLP_setLayerSizes(ptr, layerSizes.CvPtr);
}
/// <summary>
/// Integer vector specifying the number of neurons in each layer including the input and output layers.
/// The very first element specifies the number of elements in the input layer.
/// The last element - number of elements in the output layer.
/// </summary>
/// <returns></returns>
public virtual Mat GetLayerSizes()
{
if (disposed)
throw new ObjectDisposedException(GetType().Name);
IntPtr p = NativeMethods.ml_ANN_MLP_getLayerSizes(ptr);
return new Mat(p);
}
#endregion
#region Types
/// <summary>
/// possible activation functions
/// </summary>
public enum ActivationFunctions
{
/// <summary>
/// Identity function: $f(x)=x
/// </summary>
Identity = 0,
/// <summary>
/// Symmetrical sigmoid: f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x}
/// </summary>
SigmoidSym = 1,
/// <summary>
/// Gaussian function: f(x)=\beta e^{-\alpha x*x}
/// </summary>
Gaussian = 2
}
/// <summary>
/// Train options
/// </summary>
[Flags]
public enum TrainFlags
{
/// <summary>
/// Update the network weights, rather than compute them from scratch.
/// In the latter case the weights are initialized using the Nguyen-Widrow algorithm.
/// </summary>
UpdateWeights = 1,
/* */
/// <summary>
/// Do not normalize the input vectors.
/// If this flag is not set, the training algorithm normalizes each input feature
/// independently, shifting its mean value to 0 and making the standard deviation
/// equal to 1. If the network is assumed to be updated frequently, the new
/// training data could be much different from original one. In this case,
/// you should take care of proper normalization.
/// </summary>
NoInputScale = 2,
/// <summary>
/// Do not normalize the output vectors. If the flag is not set,
/// the training algorithm normalizes each output feature independently,
/// by transforming it to the certain range depending on the used activation function.
/// </summary>
NoOutputScale = 4
}
/// <summary>
/// Available training methods
/// </summary>
public enum TrainingMethods
{
/// <summary>
/// The back-propagation algorithm.
/// </summary>
BackProp = 0,
/// <summary>
/// The RPROP algorithm. See @cite RPROP93 for details.
/// </summary>
RProp = 1
}
#endregion
}
} | 34.052045 | 175 | 0.544323 | [
"MIT"
] | Atharvap14/SecondaryVision | DepthMap/Assets/OpenCV+Unity/Assets/Scripts/OpenCvSharp/modules/ml/ANN_MLP.cs | 9,174 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace XeroApi.Model.Reporting
{
public class BankSummaryReport : DynamicReportBase
{
private readonly DateTime? _fromDate;
private readonly DateTime? _toDate;
/// <summary>
/// Initializes a new instance of the <see cref="BankSummaryReport"/> class.
/// </summary>
/// <param name="fromDate">From date.</param>
/// <param name="toDate">To date.</param>
public BankSummaryReport(DateTime? fromDate = null, DateTime? toDate = null)
{
_fromDate = fromDate;
_toDate = toDate;
}
/// <summary>
/// Generates the querystring params.
/// </summary>
/// <param name="queryStringParams">The query string params.</param>
internal override void GenerateQuerystringParams(NameValueCollection queryStringParams)
{
if (_fromDate.HasValue)
queryStringParams.Add("fromDate", _fromDate.Value.ToString(ReportDateFormatString));
if (_toDate.HasValue)
queryStringParams.Add("toDate", _toDate.Value.ToString(ReportDateFormatString));
}
}
}
| 32.794872 | 100 | 0.632525 | [
"MIT"
] | MatthewSteeples/XeroAPI.Net | source/XeroApi/Model/Reporting/BankSummaryReport.cs | 1,281 | C# |
namespace Elsa.Attributes;
[AttributeUsage(AttributeTargets.Property)]
public class InboundAttribute : Attribute
{
} | 19.5 | 43 | 0.82906 | [
"MIT"
] | elsa-workflows/experimental | src/core/Elsa.Core/Attributes/InboundAttribute.cs | 117 | C# |
using Business.Abstract;
using DataAccess.Abstract;
using Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business.Concrete
{
public class LastKmManager : ILastKmService
{
ILastKmDal lastKmDal;
public LastKmManager(ILastKmDal lastKmDal)
{
this.lastKmDal = lastKmDal;
}
public void Add(LastKm lastKm)
{
lastKmDal.Add(lastKm);
}
public List<LastKm> GetAll()
{
return lastKmDal.GetList();
}
public List<LastKm> GetVehicleKms(int vehicleId)
{
return lastKmDal.GetList(x => x.vehicleId == vehicleId);
}
}
}
| 20.540541 | 68 | 0.610526 | [
"MIT"
] | jova/Rent-a-Car | RentACar/Business/Concrete/LastKmManager.cs | 762 | C# |
using Avalonia;
using Avalonia.Controls;
using ReactiveUI;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia.Xaml.Interactivity;
namespace WalletWasabi.Fluent.Behaviors;
public class CheckMarkVisibilityBehavior : Behavior<PathIcon>
{
private CompositeDisposable? _disposables;
public static readonly StyledProperty<TextBox> OwnerTextBoxProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, TextBox>(nameof(OwnerTextBox));
[ResolveByName]
public TextBox OwnerTextBox
{
get => GetValue(OwnerTextBoxProperty);
set => SetValue(OwnerTextBoxProperty, value);
}
protected override void OnAttached()
{
this.WhenAnyValue(x => x.OwnerTextBox)
.Subscribe(
x =>
{
_disposables?.Dispose();
if (x is not null)
{
_disposables = new CompositeDisposable();
var hasErrors = OwnerTextBox.GetObservable(DataValidationErrors.HasErrorsProperty);
var text = OwnerTextBox.GetObservable(TextBox.TextProperty);
hasErrors.Select(_ => Unit.Default)
.Merge(text.Select(_ => Unit.Default))
.Throttle(TimeSpan.FromMilliseconds(100))
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(
_ =>
{
if (AssociatedObject is { })
{
AssociatedObject.Opacity =
!DataValidationErrors.GetHasErrors(OwnerTextBox) &&
!string.IsNullOrEmpty(OwnerTextBox.Text)
? 1
: 0;
}
})
.DisposeWith(_disposables);
}
});
}
}
| 25.42623 | 89 | 0.684075 | [
"MIT"
] | CAnorbo/WalletWasabi | WalletWasabi.Fluent/Behaviors/CheckMarkVisibilityBehavior.cs | 1,551 | C# |
using SwedbankPay.Sdk.PaymentInstruments;
using System;
using System.Collections.Generic;
namespace SwedbankPay.Sdk
{
internal class TransactionListResponse : Identifiable, ITransactionListResponse
{
public TransactionListResponse(Uri id, List<ITransaction> transactionList)
: base(id)
{
TransactionList = transactionList;
}
public IList<ITransaction> TransactionList { get; }
}
} | 26.055556 | 84 | 0.66951 | [
"Apache-2.0"
] | Nacorpio/swedbank-pay-sdk-dotnet | src/SwedbankPay.Sdk.Infrastructure/TransactionListResponse.cs | 471 | C# |
using UnityEngine;
namespace TopDownEngineExtensions
{
[CreateAssetMenu(menuName = "ScriptableCookbook/Damage Type")]
public class DamageType : ScriptableObject {}
}
| 22 | 66 | 0.772727 | [
"MIT"
] | AlexanderGheorghe/TopDownEngineExtensions | TypedDamage/DamageType.cs | 178 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.Diagnostics;
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace QuickBuild
{
public class QBProcess
{
#if UNITY_EDITOR_WIN
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool SetWindowPos(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, int flags);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetForegroundWindow();
#endif
public event Action<QBProcess> OnProcessCompleted;
private Thread _thread;
private Process _process;
private ProcessStartInfo _processStartInfo;
private int _instanceID;
protected QBProfile _profile;
private const string QBMessageFormatPrefix = "<b>[QB:{0}]</b> {1}";
public QBProcess(string buildPath, QBProfile editorProfile, QBPlayerSettings playerSettings, int instanceID)
{
_instanceID = instanceID;
_profile = editorProfile;
_processStartInfo = new ProcessStartInfo();
//_processStartInfo.UseShellExecute = false;
_processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
// processStartInfo.RedirectStandardOutput = EditorSettings.RedirectOutputLog;
_processStartInfo.FileName = buildPath;
_processStartInfo.Arguments = BuildCommandLineArguments(editorProfile, playerSettings, instanceID);
UnityEngine.Debug.Log("Command line arguments : " + _processStartInfo.Arguments);
}
public void Start()
{
Kill();
_thread = new Thread(ProcessWorker);
_thread.Start();
}
void ProcessWorker(object param)
{
Process.Start(_processStartInfo);
// process.EnableRaisingEvents = true;
// process.OutputDataReceived += HandleOutputDataReceived;
// process.Exited += HandleProcessExited;
// process.BeginOutputReadLine();
// Does not work for now... _process.MainWindowTitle is always invalid
//_process.WaitForInputIdle();
//_process.Refresh();
//MoveProcessWindowIfRequired(_process);
}
void HandleOutputDataReceived (object sender, DataReceivedEventArgs e)
{
// Should be dispatched on Unity thread !
string condition;
string stackTrace;
LogType logType;
if (QBMessagePacker.UnpackMessage(e.Data, out condition, out stackTrace, out logType))
{
string messageContent = string.Format("{0}{1}<i>{2}</i>", condition, System.Environment.NewLine, stackTrace);
string message = string.Format(QBMessageFormatPrefix, _instanceID, messageContent);
switch (logType)
{
case LogType.Log:
UnityEngine.Debug.Log(message);
break;
case LogType.Warning:
UnityEngine.Debug.LogWarning(message);
break;
default:
UnityEngine.Debug.LogError(message);
break;
}
}
else
{
UnityEngine.Debug.Log(string.Format(QBMessageFormatPrefix, _instanceID, e.Data));
}
}
void HandleProcessExited (object sender, EventArgs e)
{
_process = null;
}
public void Kill()
{
if (_thread != null && _thread.IsAlive)
{
_thread.Abort();
_thread = null;
}
if (_process != null)
{
_process.Kill();
}
}
private string BuildCommandLineArguments(QBProfile editorProfile, QBPlayerSettings playerSettings, int instanceID)
{
StringBuilder sb = new StringBuilder();
AddCommandLineArgument(sb, QBCommandLineParameters.EnableQuickBuild);
AddCommandLineArgument(sb, QBCommandLineParameters.InstanceID, instanceID);
AddCommandLineArgument(sb, QBCommandLineParameters.Screen_FullscreenMode, editorProfile.advancedSettings.screenSettings.isFullScreen ? 1 : 0);
int width, height;
editorProfile.GetScreenSizeForInstance(instanceID, out width, out height);
AddCommandLineArgument(sb, QBCommandLineParameters.Screen_Width, width);
AddCommandLineArgument(sb, QBCommandLineParameters.Screen_Height, height);
string outputLogFileName = string.Empty;
if (!editorProfile.advancedSettings.redirectOutputLog)
{
outputLogFileName = editorProfile.BuildDirectoryPath + "/" + string.Format(QBCommandLineParameters.LogFileFormat, instanceID);
AddCommandLineArgument(sb, QBCommandLineParameters.LogFile, outputLogFileName);
}
else
{
AddCommandLineArgument(sb, QBCommandLineParameters.RedirectOutput);
}
if (editorProfile.expertSettings.launchInBatchMode)
{
AddCommandLineArgument(sb, QBCommandLineParameters.Batchmode);
AddCommandLineArgument(sb, QBCommandLineParameters.NoGraphics);
}
if (editorProfile.advancedSettings.displayInstanceID)
{
AddCommandLineArgument(sb, QBCommandLineParameters.DisplayInstanceID);
}
if (playerSettings.AdditiveScenes.Length > 0)
{
AddCommandLineArgument(sb, QBCommandLineParameters.AdditiveScenes, QBCommandLineHelper.PackStringArray(playerSettings.AdditiveScenes));
}
if (instanceID < editorProfile.expertSettings.customInstanceDatas.Length)
{
QBInstanceData qbInstanceData = editorProfile.expertSettings.customInstanceDatas[instanceID];
if (qbInstanceData)
{
AddCommandLineArgument(sb, qbInstanceData.commandLineArguments);
if (!string.IsNullOrEmpty(qbInstanceData.customName))
{
AddCommandLineArgument(sb, QBCommandLineParameters.CustomName, qbInstanceData.customName);
}
}
}
AddCommandLineArgument(sb, editorProfile.advancedSettings.commandLineArguments);
return (sb.ToString());
}
private void AddCommandLineArgument(StringBuilder sb, string argument)
{
sb.AppendFormat("{0} ", argument);
}
private void AddCommandLineArgument(StringBuilder sb, string key, object value)
{
AddCommandLineArgument(sb, string.Format("{0} {1}", key, value));
}
private void MoveProcessWindowIfRequired(Process process)
{
if (process.MainWindowHandle.ToInt32() == 0)
{
return;
}
QBInstanceData instanceData = _profile.GetInstanceData(_instanceID);
if (instanceData != null && instanceData.screenPosition.Override)
{
#if UNITY_EDITOR_WIN
int width, height;
_profile.GetScreenSizeForInstance(_instanceID, out width, out height);
IntPtr id = GetForegroundWindow();
UnityEngine.Debug.LogFormat("Move window [{0}, {1}, {2}, {3}]", instanceData.screenPosition.X, instanceData.screenPosition.Y, width, height);
// bool repaint = true;
// QBProcess.MoveWindow(
// id,
// instanceData.screenPosition.X, instanceData.screenPosition.Y,
// width, height,
// repaint
// );
bool result = QBProcess.SetWindowPos(
id,
instanceData.screenPosition.X, instanceData.screenPosition.Y,
width, height,
0x0010 | 0x0200 | 0x0001 | 0x0004
);
UnityEngine.Debug.LogFormat("Move success : {0}", result);
if (!result)
{
int errorCode = Marshal.GetLastWin32Error();
UnityEngine.Debug.LogFormat("Error code : {0}", errorCode);
}
#endif
}
}
}
} | 36.217949 | 154 | 0.610619 | [
"MIT"
] | Begounet/QuickBuild | Editor/QBProcess.cs | 8,477 | 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 quicksight-2018-04-01.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.QuickSight.Model
{
/// <summary>
/// The structure of a data source.
/// </summary>
public partial class DataSource
{
private List<DataSourceParameters> _alternateDataSourceParameters = new List<DataSourceParameters>();
private string _arn;
private DateTime? _createdTime;
private string _dataSourceId;
private DataSourceParameters _dataSourceParameters;
private DataSourceErrorInfo _errorInfo;
private DateTime? _lastUpdatedTime;
private string _name;
private SslProperties _sslProperties;
private ResourceStatus _status;
private DataSourceType _type;
private VpcConnectionProperties _vpcConnectionProperties;
/// <summary>
/// Gets and sets the property AlternateDataSourceParameters.
/// <para>
/// A set of alternate data source parameters that you want to share for the credentials
/// stored with this data source. The credentials are applied in tandem with the data
/// source parameters when you copy a data source by using a create or update request.
/// The API operation compares the <code>DataSourceParameters</code> structure that's
/// in the request with the structures in the <code>AlternateDataSourceParameters</code>
/// allow list. If the structures are an exact match, the request is allowed to use the
/// credentials from this existing data source. If the <code>AlternateDataSourceParameters</code>
/// list is null, the <code>Credentials</code> originally used with this <code>DataSourceParameters</code>
/// are automatically allowed.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=50)]
public List<DataSourceParameters> AlternateDataSourceParameters
{
get { return this._alternateDataSourceParameters; }
set { this._alternateDataSourceParameters = value; }
}
// Check to see if AlternateDataSourceParameters property is set
internal bool IsSetAlternateDataSourceParameters()
{
return this._alternateDataSourceParameters != null && this._alternateDataSourceParameters.Count > 0;
}
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// The Amazon Resource Name (ARN) of the data source.
/// </para>
/// </summary>
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property CreatedTime.
/// <para>
/// The time that this data source was created.
/// </para>
/// </summary>
public DateTime CreatedTime
{
get { return this._createdTime.GetValueOrDefault(); }
set { this._createdTime = value; }
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this._createdTime.HasValue;
}
/// <summary>
/// Gets and sets the property DataSourceId.
/// <para>
/// The ID of the data source. This ID is unique per Region; for each Amazon Web Services
/// account;.
/// </para>
/// </summary>
public string DataSourceId
{
get { return this._dataSourceId; }
set { this._dataSourceId = value; }
}
// Check to see if DataSourceId property is set
internal bool IsSetDataSourceId()
{
return this._dataSourceId != null;
}
/// <summary>
/// Gets and sets the property DataSourceParameters.
/// <para>
/// The parameters that Amazon QuickSight uses to connect to your underlying source. This
/// is a variant type structure. For this structure to be valid, only one of the attributes
/// can be non-null.
/// </para>
/// </summary>
public DataSourceParameters DataSourceParameters
{
get { return this._dataSourceParameters; }
set { this._dataSourceParameters = value; }
}
// Check to see if DataSourceParameters property is set
internal bool IsSetDataSourceParameters()
{
return this._dataSourceParameters != null;
}
/// <summary>
/// Gets and sets the property ErrorInfo.
/// <para>
/// Error information from the last update or the creation of the data source.
/// </para>
/// </summary>
public DataSourceErrorInfo ErrorInfo
{
get { return this._errorInfo; }
set { this._errorInfo = value; }
}
// Check to see if ErrorInfo property is set
internal bool IsSetErrorInfo()
{
return this._errorInfo != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedTime.
/// <para>
/// The last time that this data source was updated.
/// </para>
/// </summary>
public DateTime LastUpdatedTime
{
get { return this._lastUpdatedTime.GetValueOrDefault(); }
set { this._lastUpdatedTime = value; }
}
// Check to see if LastUpdatedTime property is set
internal bool IsSetLastUpdatedTime()
{
return this._lastUpdatedTime.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// A display name for the data source.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property SslProperties.
/// <para>
/// Secure Socket Layer (SSL) properties that apply when QuickSight connects to your underlying
/// source.
/// </para>
/// </summary>
public SslProperties SslProperties
{
get { return this._sslProperties; }
set { this._sslProperties = value; }
}
// Check to see if SslProperties property is set
internal bool IsSetSslProperties()
{
return this._sslProperties != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The HTTP status of the request.
/// </para>
/// </summary>
public ResourceStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The type of the data source. This type indicates which database engine the data source
/// connects to.
/// </para>
/// </summary>
public DataSourceType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property VpcConnectionProperties.
/// <para>
/// The VPC connection information. You need to use this parameter only when you want
/// QuickSight to use a VPC connection when connecting to your underlying source.
/// </para>
/// </summary>
public VpcConnectionProperties VpcConnectionProperties
{
get { return this._vpcConnectionProperties; }
set { this._vpcConnectionProperties = value; }
}
// Check to see if VpcConnectionProperties property is set
internal bool IsSetVpcConnectionProperties()
{
return this._vpcConnectionProperties != null;
}
}
} | 33.198582 | 114 | 0.584063 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/QuickSight/Generated/Model/DataSource.cs | 9,362 | C# |
namespace LINGYUN.Abp.UI.Navigation
{
public interface INavigationDefinitionContext
{
void Add(params NavigationDefinition[] definitions);
}
}
| 21.375 | 61 | 0.690058 | [
"MIT"
] | ZhaoYis/abp-next-admin | aspnet-core/modules/navigation/LINGYUN.Abp.UI.Navigation/LINGYUN/Abp/UI/Navigation/INavigationDefinitionContext.cs | 173 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.Update7
{
public partial class Update7YamlTests
{
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class ExternalVersion1Tests : YamlTestsBase
{
[Test]
public void ExternalVersion1Test()
{
//do update
_body = new {
doc= new {
foo= "baz"
},
upsert= new {
foo= "bar"
}
};
this.Do(()=> _client.Update("test_1", "test", "1", _body, nv=>nv
.AddQueryString("version", 2)
.AddQueryString("version_type", @"external")
));
//match _response._version:
this.IsMatch(_response._version, 2);
//do update
_body = new {
doc= new {
foo= "baz"
},
upsert= new {
foo= "bar"
}
};
this.Do(()=> _client.Update("test_1", "test", "1", _body, nv=>nv
.AddQueryString("version", 2)
.AddQueryString("version_type", @"external")
), shouldCatch: @"conflict");
//do update
_body = new {
doc= new {
foo= "baz"
},
upsert= new {
foo= "bar"
}
};
this.Do(()=> _client.Update("test_1", "test", "1", _body, nv=>nv
.AddQueryString("version", 3)
.AddQueryString("version_type", @"external")
));
//match _response._version:
this.IsMatch(_response._version, 3);
}
}
}
}
| 19.534247 | 68 | 0.576438 | [
"Apache-2.0"
] | Bloomerang/elasticsearch-net | src/Tests/Elasticsearch.Net.Integration.Yaml/update/35_external_version.yaml.cs | 1,426 | C# |
namespace GitVersion
{
using System;
using System.Collections.Generic;
public static class BuildServerList
{
static List<IBuildServer> BuildServers;
public static Func<Arguments, IEnumerable<IBuildServer>> Selector = arguments => DefaultSelector(arguments);
public static void ResetSelector()
{
Selector = DefaultSelector;
}
public static IEnumerable<IBuildServer> GetApplicableBuildServers(Arguments arguments)
{
return Selector(arguments);
}
static IEnumerable<IBuildServer> DefaultSelector(Arguments arguments)
{
if (BuildServers == null)
{
BuildServers = new List<IBuildServer>
{
new ContinuaCi(arguments),
new TeamCity(arguments)
};
}
var buildServices = new List<IBuildServer>();
foreach (var buildServer in BuildServers)
{
try
{
if (buildServer.CanApplyToCurrentContext())
{
Logger.WriteInfo(string.Format("Applicable build agent found: '{0}'.", buildServer.GetType().Name));
buildServices.Add(buildServer);
}
}
catch (Exception ex)
{
Logger.WriteWarning(string.Format("Failed to check build server '{0}': {1}", buildServer.GetType().Name, ex.Message));
}
}
return buildServices;
}
}
}
| 30.836364 | 139 | 0.503538 | [
"MIT"
] | VSoftTechnologies/GitVersion | GitVersion/BuildServers/BuildServerList.cs | 1,644 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using Messerli.LinqToRest.Test.Stub;
using NSubstitute;
using Xunit;
namespace Messerli.LinqToRest.Test
{
public class ResourceRetrieverTest
{
[Fact]
public async void ReturnsRestObject()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(EntityWithQueryableMemberResult.Query, UriKind.Absolute);
var actual = await resourceRetriever.RetrieveResource<IEnumerable<EntityWithQueryableMember>>(uri);
Assert.Equal(EntityWithQueryableMemberResult.Object, actual);
}
[Fact]
public async void ReturnsRestObjectWithSelect()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(NameResult.Query, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { Name = default(string) }.GetType());
var actual = await resourceRetriever.RetrieveResource(type, uri);
Assert.Equal(NameResult.Object, actual);
}
[Fact]
public async void ReturnsFullRestObjectWithSelect()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(NameNumberResult.Query, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { Name = default(string), Number = default(int) }.GetType());
var actual = await resourceRetriever.RetrieveResource(type, uri);
Assert.Equal(NameNumberResult.Object, actual);
}
[Fact]
public async void ReturnsRestObjectWithSelectedQueryable()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(NameQueryableMemberResult.Query, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { Name = default(string), QueryableMember = default(IQueryable<EntityWithSimpleMembers>) }.GetType());
var actual = await resourceRetriever.RetrieveResource(type, uri);
Assert.Equal(NameQueryableMemberResult.Object, actual);
}
[Fact]
public async void ReturnsRestObjectWithSelectedUniqueIdentifier()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(UniqueIdentifierNameResult.Query, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { UniqueIdentifier = default(string), Name = default(string) }.GetType());
var actual = await resourceRetriever.RetrieveResource(type, uri);
var expected = UniqueIdentifierNameResult.Object;
Assert.Equal(expected, actual);
}
[Fact]
public async void ReturnsRestObjectWithEnum()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(EnumResult.Query, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { Enum = default(TestEnum) }.GetType());
var actual = await resourceRetriever.RetrieveResource(type, uri);
var expected = EnumResult.Object;
Assert.Equal(expected, actual);
}
[Fact]
public async void ReturnsRestObjectWithDateString()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(DateStringResult.Query, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { Date = default(StringNewType) }.GetType());
var actual = await resourceRetriever.RetrieveResource(type, uri);
var expected = DateStringResult.Object;
Assert.Equal(expected[0], ((IEnumerable<object>)actual).First());
}
[Fact]
public async System.Threading.Tasks.Task ThrowOnInvalidEnumValue()
{
var resourceRetriever = CreateResourceRetriever();
var uri = new Uri(InvalidEnumRequestUri, UriKind.Absolute);
var type = typeof(IEnumerable<>).MakeGenericType(new { Enum = TestEnum.One }.GetType());
await Assert.ThrowsAsync<InvalidEnumArgumentException>(() => resourceRetriever.RetrieveResource(type, uri));
}
private static ResourceRetriever CreateResourceRetriever()
{
return new ResourceRetriever(MockHttpClient())
{
QueryableFactory = (type, uri) =>
{
var queryProvider = new QueryProvider(
Substitute.For<IResourceRetriever>(),
() => new QueryBinder(new EntityValidator()),
uri,
NamingPolicy.LowerCasePlural);
return Activator.CreateInstance(typeof(Query<>).MakeGenericType(type), queryProvider) as IQueryable<object>;
},
};
}
#region Mock
private static HttpClient MockHttpClient()
{
return new HttpClientMockBuilder()
.JsonResponse(UniqueIdentifierNameNumberRequestUri, UniqueIdentifierNameNumberJson)
.JsonResponse(EntityWithQueryableMemberRequestUri, EntityWithQueryableMemberJson)
.JsonResponse(EnumRequestUri, EntityWithEnumMemberJson)
.JsonResponse(DateRequestUri, EntityWithDateStringJson)
.JsonResponse(InvalidEnumRequestUri, InvalidEnumJson)
.Build();
}
#endregion
#region Data
private static Uri RootUri => new Uri("http://www.example.com/api/v1/", UriKind.Absolute);
private static string EntityWithQueryableMemberRequestUri =>
$"{RootUri}entitywithqueryablemembers";
private static string EntityWithQueryableMemberJson => @"
[
{
""uniqueIdentifier"": ""Test1"",
""name"": ""Test1""
},
{
""uniqueIdentifier"": ""Test2"",
""name"": ""Test2""
}
]
";
private static string UniqueIdentifierNameNumberJson => @"
[
{
""uniqueIdentifier"": ""Test1"",
""name"": ""Test1"",
""number"": ""1""
},
{
""uniqueIdentifier"": ""Test2"",
""name"": ""Test2"",
""number"": ""2""
}
]
";
private static QueryResult<object> EntityWithQueryableMemberResult => new QueryResult<object>(
new Uri(EntityWithQueryableMemberRequestUri),
new object[]
{
new EntityWithQueryableMember("Test1", CreateQuery<EntityWithSimpleMembers>("entitywithqueryablemembers/Test1/")),
new EntityWithQueryableMember("Test2", CreateQuery<EntityWithSimpleMembers>("entitywithqueryablemembers/Test2/"))
});
private static QueryProvider CreateQueryProvider(Uri root)
{
return new QueryProvider(CreateResourceRetriever(), () => new QueryBinder(new EntityValidator()), root, NamingPolicy.LowerCasePlural);
}
private static IQueryable<T> CreateQuery<T>(string subPath)
{
return new Query<T>(CreateQueryProvider(new Uri(RootUri, subPath)));
}
private static string UniqueIdentifierNameRequestUri =>
$"{RootUri}entitywithqueryablemembers?fields=uniqueIdentifier,name";
private static QueryResult<object> NameResult => new QueryResult<object>(
new Uri(UniqueIdentifierNameRequestUri),
new object[]
{
new
{
Name = "Test1"
},
new
{
Name = "Test2"
}
});
private static string UniqueIdentifierNameNumberRequestUri =>
$"{RootUri}entitywithqueryablemembers?fields=uniqueIdentifier,name,number";
private static QueryResult<object> NameNumberResult => new(
new Uri(UniqueIdentifierNameNumberRequestUri),
new object[]
{
new
{
Name = "Test1",
Number = 1
},
new
{
Name = "Test2",
Number = 2
}
});
private static QueryResult<object> UniqueIdentifierNameResult => new QueryResult<object>(
new Uri(UniqueIdentifierNameRequestUri),
new object[]
{
new
{
UniqueIdentifier = "Test1",
Name = "Test1"
},
new
{
UniqueIdentifier = "Test2",
Name = "Test2"
}
});
private static string NameQueryableMemberRequestUri =>
$"{RootUri}entitywithqueryablemembers?fields=uniqueIdentifier,name,queryableMember";
private static QueryResult<object> NameQueryableMemberResult => new QueryResult<object>(
new Uri(NameQueryableMemberRequestUri),
new object[]
{
new
{
Name = "Test1",
QueryableMember = CreateQuery<EntityWithSimpleMembers>("entitywithqueryablemembers/Test1/")
},
new
{
Name = "Test2",
QueryableMember = CreateQuery<EntityWithSimpleMembers>("entitywithqueryablemembers/Test2/")
}
});
private static string EnumRequestUri => $"{RootUri}entitywithenummembers";
private static string EntityWithEnumMemberJson => @"
[
{
""uniqueIdentifier"": ""One"",
""enum"": ""One""
},
{
""uniqueIdentifier"": ""Two"",
""enum"": ""Two""
},
{
""uniqueIdentifier"": ""Three"",
""enum"": ""Three""
},
]
";
private static QueryResult<object> EnumResult => new QueryResult<object>(
new Uri(EnumRequestUri),
new object[]
{
new { Enum = TestEnum.One },
new { Enum = TestEnum.Two },
new { Enum = TestEnum.Three }
});
private static string DateRequestUri => $"{RootUri}entitywithdatemembers";
private static string EntityWithDateStringJson => @"
[
{
""uniqueIdentifier"": ""One"",
""date"": ""2021-01-03T09:45:12""
},
]
";
private static QueryResult<object> DateStringResult => new(
new Uri(DateRequestUri),
new object[]
{
new { Date = new StringNewType("2021-01-03T09:45:12") },
});
private static string InvalidEnumRequestUri => $"{RootUri}invaludenummembers";
private static string InvalidEnumJson => @"
[
{
""uniqueIdentifier"": ""One"",
""enum"": ""NoEnumValue""
}
]
";
#endregion
private sealed record StringNewType
{
public StringNewType(string value)
{
Value = value;
}
public string Value { get; }
public override string ToString() => $"{nameof(StringNewType)}({Value})";
}
}
}
| 32.915942 | 167 | 0.573353 | [
"Apache-2.0",
"MIT"
] | messerli-informatik-ag/LinqToRest | LinqToRest.Test/ResourceRetrieverTest.cs | 11,356 | C# |
using CleanArchitectureTemplate.Application.Interfaces.Repositories;
using CleanArchitectureTemplate.Domain.Entities;
using CleanArchitectureTemplate.Infrastructure.Persistence.Contexts;
using CleanArchitectureTemplate.Infrastructure.Persistence.Repository;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace CleanArchitectureTemplate.Infrastructure.Persistence.Repositories
{
public class ProductRepositoryAsync : GenericRepositoryAsync<Product>, IProductRepositoryAsync
{
private readonly DbSet<Product> products;
public ProductRepositoryAsync(ApplicationDbContext dbContext) : base(dbContext)
{
products = dbContext.Set<Product>();
}
public Task<bool> IsUniqueBarcodeAsync(string barcode)
{
return products
.AllAsync(p => p.Barcode != barcode);
}
}
}
| 34.307692 | 98 | 0.746637 | [
"MIT"
] | GheorgheVolosenco/CleanArchitectureSolutionTemplate | src/Infrastructure.Persistence/Repositories/ProductRepositoryAsync.cs | 894 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System.Linq.Expressions;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace Microsoft.Scripting.Interpreter {
/// <summary>
/// Visits a LambdaExpression, replacing the constants with direct accesses
/// to their StrongBox fields. This is very similar to what
/// ExpressionQuoter does for LambdaCompiler.
///
/// Also inserts debug information tracking similar to what the interpreter
/// would do.
/// </summary>
internal sealed class LightLambdaClosureVisitor : ExpressionVisitor {
/// <summary>
/// Local variable mapping.
/// </summary>
private readonly Dictionary<ParameterExpression, LocalVariable> _closureVars;
/// <summary>
/// The variable that holds onto the StrongBox{object}[] closure from
/// the interpreter
/// </summary>
private readonly ParameterExpression _closureArray;
/// <summary>
/// A stack of variables that are defined in nested scopes. We search
/// this first when resolving a variable in case a nested scope shadows
/// one of our variable instances.
/// </summary>
private readonly Stack<HashSet<ParameterExpression>> _shadowedVars = new Stack<HashSet<ParameterExpression>>();
private LightLambdaClosureVisitor(Dictionary<ParameterExpression, LocalVariable> closureVariables, ParameterExpression closureArray) {
Assert.NotNull(closureVariables, closureArray);
_closureArray = closureArray;
_closureVars = closureVariables;
}
/// <summary>
/// Walks the lambda and produces a higher order function, which can be
/// used to bind the lambda to a closure array from the interpreter.
/// </summary>
/// <param name="lambda">The lambda to bind.</param>
/// <param name="closureVariables">Variables which are being accessed defined in the outer scope.</param>
/// <returns>A delegate that can be called to produce a delegate bound to the passed in closure array.</returns>
internal static Func<StrongBox<object>[], Delegate> BindLambda(LambdaExpression lambda, Dictionary<ParameterExpression, LocalVariable> closureVariables) {
// 1. Create rewriter
var closure = Expression.Parameter(typeof(StrongBox<object>[]), "closure");
var visitor = new LightLambdaClosureVisitor(closureVariables, closure);
// 2. Visit the lambda
lambda = (LambdaExpression)visitor.Visit(lambda);
// 3. Create a higher-order function which fills in the parameters
var result = Expression.Lambda<Func<StrongBox<object>[], Delegate>>(lambda, closure);
// 4. Compile it
return result.Compile();
}
#region closures
protected override Expression VisitLambda<T>(Expression<T> node) {
_shadowedVars.Push(new HashSet<ParameterExpression>(node.Parameters));
Expression b = Visit(node.Body);
_shadowedVars.Pop();
if (b == node.Body) {
return node;
}
return Expression.Lambda<T>(b, node.Name, node.TailCall, node.Parameters);
}
protected override Expression VisitBlock(BlockExpression node) {
if (node.Variables.Count > 0) {
_shadowedVars.Push(new HashSet<ParameterExpression>(node.Variables));
}
var b = Visit(node.Expressions);
if (node.Variables.Count > 0) {
_shadowedVars.Pop();
}
if (b == node.Expressions) {
return node;
}
return Expression.Block(node.Variables, b);
}
protected override CatchBlock VisitCatchBlock(CatchBlock node) {
if (node.Variable != null) {
_shadowedVars.Push(new HashSet<ParameterExpression>(new[] { node.Variable }));
}
Expression b = Visit(node.Body);
Expression f = Visit(node.Filter);
if (node.Variable != null) {
_shadowedVars.Pop();
}
if (b == node.Body && f == node.Filter) {
return node;
}
return Expression.MakeCatchBlock(node.Test, node.Variable, b, f);
}
protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
int count = node.Variables.Count;
var boxes = new List<Expression>();
var vars = new List<ParameterExpression>();
var indexes = new int[count];
for (int i = 0; i < count; i++) {
Expression box = GetClosureItem(node.Variables[i], false);
if (box == null) {
indexes[i] = vars.Count;
vars.Add(node.Variables[i]);
} else {
indexes[i] = -1 - boxes.Count;
boxes.Add(box);
}
}
// No variables were rewritten. Just return the original node.
if (boxes.Count == 0) {
return node;
}
var boxesArray = Expression.NewArrayInit(typeof(IStrongBox), boxes);
// All of them were rewritten. Just return the array, wrapped in a
// read-only collection.
if (vars.Count == 0) {
return Expression.Invoke(
Expression.Constant((Func<IStrongBox[], IRuntimeVariables>)RuntimeVariables.Create),
boxesArray
);
}
// Otherwise, we need to return an object that merges them
Func<IRuntimeVariables, IRuntimeVariables, int[], IRuntimeVariables> helper = MergedRuntimeVariables.Create;
return Expression.Invoke(AstUtils.Constant(helper), Expression.RuntimeVariables(vars), boxesArray, AstUtils.Constant(indexes));
}
protected override Expression VisitParameter(ParameterExpression node) {
Expression closureItem = GetClosureItem(node, true);
if (closureItem == null) {
return node;
}
// Convert can go away if we switch to strongly typed StrongBox
return Ast.Utils.Convert(closureItem, node.Type);
}
protected override Expression VisitBinary(BinaryExpression node) {
if (node.NodeType == ExpressionType.Assign &&
node.Left.NodeType == ExpressionType.Parameter) {
var variable = (ParameterExpression)node.Left;
Expression closureItem = GetClosureItem(variable, true);
if (closureItem != null) {
// We need to convert to object to store the value in the box.
return Expression.Block(
new[] { variable },
Expression.Assign(variable, Visit(node.Right)),
Expression.Assign(closureItem, Ast.Utils.Convert(variable, typeof(object))),
variable
);
}
}
return base.VisitBinary(node);
}
private Expression GetClosureItem(ParameterExpression variable, bool unbox) {
// Skip variables that are shadowed by a nested scope/lambda
foreach (HashSet<ParameterExpression> hidden in _shadowedVars) {
if (hidden.Contains(variable)) {
return null;
}
}
LocalVariable loc;
if (!_closureVars.TryGetValue(variable, out loc)) {
throw new InvalidOperationException("unbound variable: " + variable.Name);
}
var result = loc.LoadFromArray(null, _closureArray);
return (unbox) ? LightCompiler.Unbox(result) : result;
}
protected override Expression VisitExtension(Expression node) {
// Reduce extensions now so we can find embedded variables
return Visit(node.ReduceExtensions());
}
#region MergedRuntimeVariables
/// <summary>
/// Provides a list of variables, supporing read/write of the values
/// </summary>
private sealed class MergedRuntimeVariables : IRuntimeVariables {
private readonly IRuntimeVariables _first;
private readonly IRuntimeVariables _second;
// For reach item, the index into the first or second list
// Positive values mean the first array, negative means the second
private readonly int[] _indexes;
private MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) {
_first = first;
_second = second;
_indexes = indexes;
}
internal static IRuntimeVariables Create(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) {
return new MergedRuntimeVariables(first, second, indexes);
}
int IRuntimeVariables.Count {
get { return _indexes.Length; }
}
object IRuntimeVariables.this[int index] {
get {
index = _indexes[index];
return (index >= 0) ? _first[index] : _second[-1 - index];
}
set {
index = _indexes[index];
if (index >= 0) {
_first[index] = value;
} else {
_second[-1 - index] = value;
}
}
}
}
#endregion
#endregion
}
}
| 41.217899 | 162 | 0.575569 | [
"MIT"
] | IMaeland/IronSmalltalk | DLR/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs | 10,595 | C# |
#region Copyright (c) 2003-2005, Luke T. Maxon
/********************************************************************************************************************
'
' Copyright (c) 2003-2005, Luke T. Maxon
' All rights reserved.
'
' Redistribution and use in source and binary forms, with or without modification, are permitted provided
' that the following conditions are met:
'
' * Redistributions of source code must retain the above copyright notice, this list of conditions and the
' following disclaimer.
'
' * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
' the following disclaimer in the documentation and/or other materials provided with the distribution.
'
' * Neither the name of the author 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.
'
'*******************************************************************************************************************/
#endregion
using System;
using System.Data;
using System.Windows.Forms;
namespace Xunit.Extensions.Forms.TestApplications
{
public partial class RichTextBoxDataSetBindingTestForm : Form
{
public RichTextBoxDataSetBindingTestForm()
{
InitializeComponent();
}
private void btnView_Click(object sender, EventArgs e)
{
MessageBox.Show(myDataSet.Tables[0].Rows[0].ItemArray[0].ToString(), myRichTextBox.Text);
}
private void RichTextBoxtDataSetBindingTestForm_Load(object sender, EventArgs e)
{
myDataSet.Tables.Add("TableName");
myDataSet.Tables[0].Columns.Add("ColumnName");
DataRow row = myDataSet.Tables[0].NewRow();
myDataSet.Tables[0].Rows.Add(row);
myDataSet.Tables[0].Rows[0]["ColumnName"] = "Old";
myRichTextBox.DataBindings.Add(new Binding("Text", myDataSet, "TableName.ColumnName"));
}
}
} | 46.048387 | 118 | 0.65324 | [
"BSD-3-Clause"
] | ChrisPelatari/XunitForms | source/XunitForms.Test/TestForms/RichTextBoxDataSetBindingTestForm.cs | 2,855 | C# |
// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using JetBrains.Annotations;
namespace Nuke.Common.IO
{
public static partial class SerializationTasks
{
public static void XmlSerializeToFile(object obj, string path)
{
File.WriteAllText(path, XmlSerialize(obj));
}
[Pure]
public static T XmlDeserializeFromFile<T>(string path)
{
return XmlDeserialize<T>(File.ReadAllText(path));
}
[Pure]
public static string XmlSerialize<T>(T obj)
{
var xmlSerializer = new XmlSerializer(typeof(T));
using var streamWriter = new StringWriter();
xmlSerializer.Serialize(streamWriter, obj);
return streamWriter.ToString();
}
[Pure]
public static T XmlDeserialize<T>(string content)
{
var xmlSerializer = new XmlSerializer(typeof(T));
using var memoryStream = new StringReader(content);
return (T) xmlSerializer.Deserialize(memoryStream);
}
}
}
| 26.978261 | 70 | 0.628525 | [
"MIT"
] | Ceaphyrel/nuke | source/Nuke.Common/IO/SerializationTasks.Xml.cs | 1,241 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// leadcompetitors
/// </summary>
public partial class MicrosoftDynamicsCRMleadcompetitors
{
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMleadcompetitors class.
/// </summary>
public MicrosoftDynamicsCRMleadcompetitors()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMleadcompetitors class.
/// </summary>
public MicrosoftDynamicsCRMleadcompetitors(long? versionnumber = default(long?), string leadid = default(string), string competitorid = default(string), string leadcompetitorid = default(string))
{
Versionnumber = versionnumber;
Leadid = leadid;
Competitorid = competitorid;
Leadcompetitorid = leadcompetitorid;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public long? Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "leadid")]
public string Leadid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "competitorid")]
public string Competitorid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "leadcompetitorid")]
public string Leadcompetitorid { get; set; }
}
}
| 30.166667 | 203 | 0.59769 | [
"Apache-2.0"
] | danieltruong/ag-lclb-cllc-public | cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMleadcompetitors.cs | 1,991 | C# |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2008 Novell, Inc.
//
// Authors:
// Andreia Gaita (avidigal@novell.com)
//
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace Mono.Mozilla
{
internal delegate void nsITimerCallbackDelegate (
[MarshalAs (UnmanagedType.Interface)] nsITimer timer,
IntPtr closure
);
}
| 38.648649 | 73 | 0.758042 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/Mono.WebBrowser/Mono.Mozilla/interfaces/extras/nsITimerCallbackDelegate.cs | 1,430 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461)
// Version 5.461.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
namespace ComponentFactory.Krypton.Toolkit
{
internal class KryptonListBoxDesigner : ControlDesigner
{
#region Public Overrides
/// <summary>
/// Initializes the designer with the specified component.
/// </summary>
/// <param name="component">The IComponent to associate the designer with.</param>
public override void Initialize(IComponent component)
{
// Let base class do standard stuff
base.Initialize(component);
// The resizing handles around the control need to change depending on the
// value of the AutoSize and AutoSizeMode properties. When in AutoSize you
// do not get the resizing handles, otherwise you do.
AutoResizeHandles = true;
}
/// <summary>
/// Gets the design-time action lists supported by the component associated with the designer.
/// </summary>
public override DesignerActionListCollection ActionLists
{
get
{
// Create a collection of action lists
DesignerActionListCollection actionLists = new DesignerActionListCollection
{
// Add the label specific list
new KryptonListBoxActionList(this)
};
return actionLists;
}
}
#endregion
}
}
| 40.210526 | 157 | 0.599913 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.461 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Designers/KryptonListBoxDesigner.cs | 2,295 | 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Model
{
using System.Globalization;
public class RoleInstanceStatusInfo
{
public string InstanceStatus { get; set; }
public string InstanceName { get; set; }
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Instance Name: {0} - Instance Status: {1}", this.InstanceName, this.InstanceStatus);
}
}
}
| 39.580645 | 148 | 0.620212 | [
"Apache-2.0"
] | OctopusDeploy/azure-sdk-tools | WindowsAzurePowershell/src/Management.ServiceManagement/Model/RoleInstanceStatusInfo.cs | 1,229 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Huawei.SCCMPlugin.Models;
using LogUtil;
namespace Huawei.SCCMPlugin.DAO
{
/// <summary>
/// eSight数据库管理类
/// </summary>
public class HWESightHostDal :BaseRepository<HWESightHost>, IHWESightHostDal
{
/// <summary>
/// 单例
/// </summary>
public static HWESightHostDal Instance
{
get { return SingletonProvider<HWESightHostDal>.Instance; }
}
/// <summary>
/// 根据IP查找ESight实体。
/// </summary>
/// <param name="eSightIp">IP地址</param>
/// <returns></returns>
public HWESightHost FindByIP(string eSightIp) {
return DBUtility.Context.Sql("select * from HWESightHosts where HOST_IP=@0", eSightIp).QuerySingle<HWESightHost>();
}
/// <summary>
/// 删除eSight
/// </summary>
/// <param name="eSightId">eSight Id</param>
public void DeleteESight(int eSightId) {
ExecuteSql("delete from HW_TASK_RESOURCE where HW_ESIGHT_TASK_ID in (select ID from HW_ESIGHT_TASK where HW_ESIGHT_HOST_ID=" + eSightId+")");
ExecuteSql("delete from HW_ESIGHT_TASK where HW_ESIGHT_HOST_ID="+eSightId);
ExecuteSql("delete from HWESightHosts where ID=" + eSightId);
}
}
}
| 33.477273 | 153 | 0.636796 | [
"MIT"
] | Huawei/Server_Management_Plugin_SCCM | src/Respository/Huawei.SCCMPlugin.DAO/HWESightHostDal.cs | 1,513 | C# |
using UnityEngine;
using System.Collections;
public class SelfRotate : MonoBehaviour {
public float rotateSpeed = 40.0f; //旋转速度
//每帧执行一次:物体自转
void Update () {
//物体以世界坐标系的向上方向(正Y轴)方向,以rotateSpeed的速度进行顺时针自转
//Time.deltaTime表示该帧的执行时间,Time.deltaTime * rotateSpeed表示该帧总共自转的角度,Space.World表示世界坐标系
transform.Rotate (Vector3.up, -Time.deltaTime * rotateSpeed, Space.World);
}
}
| 25.533333 | 86 | 0.767624 | [
"MIT"
] | AidenFeng/The-Infinite-War-I---Origin-Standalone- | Assets/Scripts/SelfRotate.cs | 535 | C# |
using System;
using System.Net;
using FluentFTP;
using System.Security.Authentication;
namespace Examples {
internal static class SetEncryptionProtocolsExample {
public static void ValidateCertificate() {
using (var conn = new FtpClient()) {
conn.Host = "localhost";
conn.Credentials = new NetworkCredential("ftptest", "ftptest");
conn.EncryptionMode = FtpEncryptionMode.Explicit;
// Override the default protocols. The example line sets the protocols
// to support TLS 1.1 and TLS 1.2. These are only available if the
// executable targets .NET 4.5 (or higher). The framework does not enable these
// protocols by default.
//conn.SslProtocols = SslProtocols.Default | SslProtocols.Tls11 | SslProtocols.Tls12;
// Alternate example: Only support the latest level.
//conn.SslProtocols = SslProtocols.Tls12;
conn.Connect();
}
}
}
} | 32.962963 | 89 | 0.721348 | [
"MIT"
] | Mortens4444/FluentFTP | FluentFTP.Examples/SetEncryptionProtocols.cs | 892 | C# |
// Copyright 2017 Quintonn Rothmann
// 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 BasicAuthentication.Core.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace BasicAuthentication.ControllerHelpers
{
public static class Methods
{
public static async Task<ICoreIdentityUser> GetLoggedInUserAsync(ICoreUserContext userContext)
{
IIdentity userIdentity = null;
if (HttpContext.Current != null && HttpContext.Current.User != null)
{
userIdentity = HttpContext.Current.User.Identity;
}
if (userIdentity == null)
{
return null;
}
var user = await userContext.FindUserByNameAsync(userIdentity.Name);
return user;
}
public static ICoreIdentityUser GetLoggedInUser(ICoreUserContext userContext)
{
IIdentity userIdentity = null;
if (HttpContext.Current != null && HttpContext.Current.User != null)
{
userIdentity = HttpContext.Current.User.Identity;
}
if (userIdentity == null)
{
return null;
}
var result = userContext.FindUserByNameAsync(userIdentity.Name);
result.Wait();
if (result.Status != TaskStatus.RanToCompletion)
{
throw new Exception("Enable to complete async task in non-async mode:\n" + result.Status);
}
return result.Result;
}
public static async Task<ICoreIdentityUser> GetLoggedInUserAsync(HttpRequestContext requestContext, ICoreUserContext userContext)
{
var user = requestContext.Principal.Identity;
var result = await userContext.FindUserByNameAsync(user.Name);
return result;
}
public static ICoreIdentityUser GetLoggedInUser(HttpRequestContext requestContext, ICoreUserContext userContext)
{
var user = requestContext.Principal.Identity;
//var result = CoreAuthenticationEngine.UserManager.FindByNameAsync(user.Name);
var result = userContext.FindUserByNameAsync(user.Name);
result.Wait();
if (result.Status != TaskStatus.RanToCompletion)
{
throw new Exception("Enable to complete async task in non-async mode:\n" + result.Status);
}
return result.Result;
}
public static async Task<ICoreIdentityUser> GetLoggedInUserAsync(this ApiController controller, ICoreUserContext userContext)
{
return await GetLoggedInUserAsync(controller.RequestContext, userContext);
}
public static ICoreIdentityUser GetLoggedInUser(this ApiController controller, ICoreUserContext userContext)
{
return GetLoggedInUser(controller.RequestContext, userContext);
}
public static IDictionary<string, string> ParseFormData(string data)
{
var items = data.Split("&".ToCharArray());
var result = new Dictionary<string, string>();
foreach (var item in items)
{
var parts = item.Split("=".ToCharArray());
var key = HttpUtility.UrlDecode(parts.First());
var value = HttpUtility.UrlDecode(parts.Last());
result.Add(key, value);
}
return result;
}
public static IDictionary<string, string> ParseFormData(this ApiController controller, string data)
{
var items = data.Split("&".ToCharArray());
var result = new Dictionary<string, string>();
foreach (var item in items)
{
var parts = item.Split("=".ToCharArray());
var key = HttpUtility.UrlDecode(parts.First());
var value = HttpUtility.UrlDecode(parts.Last());
result.Add(key, value);
}
return result;
}
}
}
| 45.862069 | 465 | 0.628195 | [
"MIT"
] | quintonn/QBic | BasicAuthentication/ControllerHelpers/Methods.cs | 5,322 | C# |
using BanallyMe.UnException.ActionFilters.ExceptionHandling;
using BanallyMe.UnException.DependencyInjection;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using Xunit;
namespace BanallyMe.UnException.UnitTests.DependencyInjection
{
public class UnExceptionLoaderTests
{
[Fact]
public void AddUnException_AddsReplyOnActionWithFilterToMvcConfiguration()
{
var fakeServiceCollection = new ServiceCollection();
fakeServiceCollection.AddUnException();
var mvcConfig = GetMvcConfigurationFromServices(fakeServiceCollection);
mvcConfig.Should().NotBeNull();
var configurationAction = GetConfigurationActionFromService(mvcConfig);
AssertConfigurationActionAddsReplyOnExceptionWithFilter(configurationAction);
}
private ServiceDescriptor GetMvcConfigurationFromServices(IServiceCollection services)
=> services.FirstOrDefault(service => service.ServiceType == typeof(IConfigureOptions<MvcOptions>));
private Action<MvcOptions> GetConfigurationActionFromService(ServiceDescriptor service)
=> ((ConfigureNamedOptions<MvcOptions>)service.ImplementationInstance).Action;
private void AssertConfigurationActionAddsReplyOnExceptionWithFilter(Action<MvcOptions> configurationAction)
{
var fakeOptions = new MvcOptions();
configurationAction.Invoke(fakeOptions);
AssertMvcOptionsContainReplyOnExceptionWithFilter(fakeOptions);
}
private void AssertMvcOptionsContainReplyOnExceptionWithFilter(MvcOptions mvcOptions)
{
var x = mvcOptions.Filters.Select(filter => filter.GetType());
mvcOptions.Filters.OfType<TypeFilterAttribute>()
.Where(attr => attr.ImplementationType == typeof(ReplyOnExceptionWithFilter))
.Should().HaveCount(1);
}
}
}
| 38.773585 | 116 | 0.731873 | [
"MIT"
] | BanallyMe/UnException | UnException/UnException.UnitTests/DependencyInjection/UnExceptionLoaderTests.cs | 2,057 | C# |
using System;
using System.Collections.Generic;
// ReSharper disable once CheckNamespace
class EyeDiabeticExam : BaseExam
{
public override DateTime NeedleRemovingMoment { get; set; }
public override string Name => "Препроліферативна діабетична ретинопатія";
public override string LoadName => "EyeDiabeticExam";
public override string HelpString => "";
public override TupleList<string, string> CorrectSteps => new TupleList<string, string>();
public override TupleList<string, string> ToolActions(ToolItem tool)
{
return new TupleList<string, string>();
}
public override Dictionary<string, string> InventoryTool => new Dictionary<string, string>();
public override bool CheckMove(string colliderTag, out string errorMessage, out string tipMessage)
{
errorMessage = "";
tipMessage = "";
return true;
}
public override int? CheckAction(string actionCode, out string errorMessage, ref string tipMessage, out bool showAnimation, string locatedColliderTag = "")
{
errorMessage = "";
showAnimation = true;
return 1;
}
}
| 30.864865 | 159 | 0.698774 | [
"MIT"
] | levabd/dolls | Assets/Resources/Scripts/Exams/EyeDiabeticExam.cs | 1,182 | C# |
namespace Draw_a_Filled_Square
{
using System;
public class DrawAFilledSquare
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
PrintDashes(n);
PrintJaggedPart(n);
PrintDashes(n);
}
private static void PrintJaggedPart(int n)
{
for (int i = 1; i <= n - 2; i++)
{
Console.Write("-");
for (int k = 1; k <= n - 1; k++)
{
Console.Write("\\/");
}
Console.WriteLine("-");
}
}
private static void PrintDashes(int n)
{
Console.WriteLine(new string('-', 2 * n));
}
}
}
| 21.714286 | 54 | 0.405263 | [
"MIT"
] | MihailDobrev/SoftUni | Tech Module/Programming Fundamentals/09. Methods. Debugging and Troubleshooting Code - Lab/04. Draw a Filled Square/DrawAFilledSquare.cs | 762 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Templates.Core;
using Microsoft.Templates.Core.Gen;
using Microsoft.Templates.UI.Controls;
using Microsoft.Templates.UI.Extensions;
using Microsoft.Templates.UI.Mvvm;
using Microsoft.Templates.UI.Resources;
using Microsoft.Templates.UI.Services;
using Microsoft.Templates.UI.ViewModels.Common;
namespace Microsoft.Templates.UI.ViewModels.NewItem
{
public class TemplateSelectionViewModel : Observable
{
private readonly string _emptyBackendFramework = string.Empty;
private string _name;
private bool _nameEditable;
private bool _hasErrors;
private bool _isFocused;
private bool _isTextSelected;
private ICommand _setFocusCommand;
private ICommand _lostKeyboardFocusCommand;
public string Name
{
get => _name;
set => SetName(value);
}
public bool NameEditable
{
get => _nameEditable;
set => SetProperty(ref _nameEditable, value);
}
public bool HasErrors
{
get => _hasErrors;
set => SetProperty(ref _hasErrors, value);
}
public bool IsFocused
{
get => _isFocused;
set
{
if (_isFocused == value)
{
SetProperty(ref _isFocused, false);
}
SetProperty(ref _isFocused, value);
}
}
public bool IsTextSelected
{
get => _isTextSelected;
set
{
if (_isTextSelected == value)
{
SetProperty(ref _isTextSelected, false);
}
SetProperty(ref _isTextSelected, value);
}
}
public TemplateInfo Template { get; private set; }
public ObservableCollection<TemplateGroupViewModel> Groups { get; } = new ObservableCollection<TemplateGroupViewModel>();
public ObservableCollection<LicenseViewModel> Licenses { get; } = new ObservableCollection<LicenseViewModel>();
public ObservableCollection<BasicInfoViewModel> Dependencies { get; } = new ObservableCollection<BasicInfoViewModel>();
public ObservableCollection<string> RequiredSdks { get; protected set; } = new ObservableCollection<string>();
public ICommand SetFocusCommand => _setFocusCommand ?? (_setFocusCommand = new RelayCommand(() => IsFocused = true));
public ICommand LostKeyboardFocusCommand => _lostKeyboardFocusCommand ?? (_lostKeyboardFocusCommand = new RelayCommand<KeyboardFocusChangedEventArgs>(OnLostKeyboardFocus));
public TemplateSelectionViewModel()
{
}
public void Focus()
{
IsTextSelected = true;
}
public void LoadData(TemplateType templateType, string platform, string projectTypeName, string frameworkName)
{
DataService.LoadTemplatesGroups(Groups, templateType, platform, projectTypeName, frameworkName, true);
var group = Groups.FirstOrDefault();
if (group != null)
{
SelectTemplate(group.Items.FirstOrDefault());
}
}
public void SelectTemplate(TemplateInfoViewModel template)
{
if (template != null)
{
foreach (var group in Groups)
{
group.ClearIsSelected();
}
template.IsSelected = true;
NameEditable = template.ItemNameEditable;
if (template.ItemNameEditable)
{
Name = ValidationService.InferTemplateName(template.Name);
}
else
{
Name = template.Template.DefaultName;
}
HasErrors = false;
Template = template.Template;
var licenses = GenContext.ToolBox.Repo.GetAllLicences(template.Template.TemplateId, MainViewModel.Instance.ConfigPlatform, MainViewModel.Instance.ConfigProjectType, MainViewModel.Instance.ConfigFramework, _emptyBackendFramework);
LicensesService.SyncLicenses(licenses, Licenses);
Dependencies.Clear();
foreach (var dependency in template.Dependencies)
{
Dependencies.Add(dependency);
}
RequiredSdks.Clear();
foreach (var requiredSdk in template.RequiredSdks)
{
RequiredSdks.Add(requiredSdk);
}
OnPropertyChanged("Licenses");
OnPropertyChanged("Dependencies");
OnPropertyChanged("RequiredSdks");
CheckForMissingSdks();
NotificationsControl.CleanErrorNotificationsAsync(ErrorCategory.NamingValidation).FireAndForget();
WizardStatus.Current.HasValidationErrors = false;
if (NameEditable)
{
Focus();
}
}
}
private void CheckForMissingSdks()
{
var missingVersions = new List<RequiredVersionInfo>();
foreach (var requiredVersion in Template.RequiredVersions)
{
var requirementInfo = RequiredVersionService.GetVersionInfo(requiredVersion);
var isInstalled = RequiredVersionService.Instance.IsVersionInstalled(requirementInfo);
if (!isInstalled)
{
missingVersions.Add(requirementInfo);
}
}
if (missingVersions.Any())
{
var missingSdkVersions = missingVersions.Select(v => RequiredVersionService.GetRequirementDisplayName(v));
var notification = Notification.Warning(string.Format(StringRes.NotificationMissingVersions, missingSdkVersions.Aggregate((i, j) => $"{i}, {j}")), Category.MissingVersion, TimerType.None);
NotificationsControl.AddNotificationAsync(notification).FireAndForget();
}
else
{
NotificationsControl.CleanCategoryNotificationsAsync(Category.MissingVersion).FireAndForget();
}
}
private void SetName(string newName)
{
if (NameEditable)
{
var validationResult = ValidationService.ValidateTemplateName(newName);
HasErrors = !validationResult.IsValid;
MainViewModel.Instance.WizardStatus.HasValidationErrors = !validationResult.IsValid;
if (validationResult.IsValid)
{
NotificationsControl.CleanErrorNotificationsAsync(ErrorCategory.NamingValidation).FireAndForget();
}
else
{
NotificationsControl.AddNotificationAsync(validationResult.Errors.FirstOrDefault()?.GetNotification()).FireAndForget();
}
}
SetProperty(ref _name, newName, nameof(Name));
}
private void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs args)
{
if (HasErrors)
{
var textBox = args.Source as TextBox;
textBox.Focus();
}
}
}
}
| 36.355856 | 246 | 0.575517 | [
"MIT"
] | Sergio0694/WindowsTemplateStudio | code/src/UI/ViewModels/NewItem/TemplateSelectionViewModel.cs | 7,852 | C# |
using Model.Neg;
using PagedList;
using PlatinDashboard.Presentation.MVC.ApiServices;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace PlatinDashboard.Presentation.MVC.Controllers
{
public class AbcFarmaController : Controller
{
private readonly ServicosApi _servicosApi;
public AbcFarmaController()
{
_servicosApi = new ServicosApi();
}
// GET: AbcFarma
public ActionResult Index(string busca = "", int pagina = 1, int tamanhoPagina = 10)
{
return View();
}
}
} | 24 | 92 | 0.63141 | [
"Apache-2.0"
] | TcavalcantiDesenv/RepasseApcd | src/APCD/src/PlatinDashboard.Presentation.MVC/Controllers/AbcFarmaController.cs | 626 | 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 DotNetNuke.Build.Tasks
{
using System;
using System.IO;
using System.Linq;
using Cake.Common.Diagnostics;
using Cake.Common.IO;
using Cake.Frosting;
using Dnn.CakeUtils;
/// <summary>A cake task to create the Upgrade package.</summary>
[Dependency(typeof(PreparePackaging))]
[Dependency(typeof(OtherPackages))]
[Dependency(typeof(CreateInstall))] // This is to ensure CreateUpgrade runs last and not in parallel, can be removed when we get to v10 where the telerik workaround is no longer needed
[Dependency(typeof(CreateSymbols))] // This is to ensure CreateUpgrade runs last and not in parallel, can be removed when we get to v10 where the telerik workaround is no longer needed
[Dependency(typeof(CreateDeploy))] // This is to ensure CreateUpgrade runs last and not in parallel, can be removed when we get to v10 where the telerik workaround is no longer needed
public sealed class CreateUpgrade : FrostingTask<Context>
{
/// <inheritdoc/>
public override void Run(Context context)
{
this.RenameResourcesFor98xUpgrades(context);
context.CreateDirectory(context.ArtifactsFolder);
var excludes = new string[context.PackagingPatterns.InstallExclude.Length + context.PackagingPatterns.UpgradeExclude.Length];
context.PackagingPatterns.InstallExclude.CopyTo(excludes, 0);
context.PackagingPatterns.UpgradeExclude.CopyTo(excludes, context.PackagingPatterns.InstallExclude.Length);
var files = context.GetFilesByPatterns(context.WebsiteFolder, new[] { "**/*" }, excludes);
files.Add(context.GetFiles("./Website/Install/Module/DNNCE_Website.Deprecated_*_Install.zip"));
context.Information("Zipping {0} files for Upgrade zip", files.Count);
var packageZip = $"{context.ArtifactsFolder}DNN_Platform_{context.GetBuildNumber()}_Upgrade.zip";
context.Zip(context.WebsiteFolder, packageZip, files);
}
[Obsolete(
"Workaround to support upgrades from 9.8.0 which may or may not still have Telerik installed."
+ "This method is to be removed in v10.0.0 and we should also implement a solution to remove these .resources files"
+ "from the available extensions to make sure people don't install them by mistake.")]
private void RenameResourcesFor98xUpgrades(Context context)
{
var telerikPackages = new[]
{
$"{context.WebsiteFolder}Install/Module/DNNCE_DigitalAssetsManagement*.zip",
$"{context.WebsiteFolder}Install/Module/Telerik*.zip",
$"{context.WebsiteFolder}Install/Library/DNNCE_Web.Deprecated*.zip",
$"{context.WebsiteFolder}Install/Library/DNNCE_Website.Deprecated*.zip",
};
var filesToRename = context.GetFilesByPatterns(telerikPackages);
foreach (var fileToRename in filesToRename)
{
File.Move(
fileToRename.ToString(),
fileToRename.ChangeExtension("resources").ToString());
}
}
}
}
| 54.984375 | 188 | 0.656152 | [
"MIT"
] | Mariusz11711/DNN | Build/Tasks/CreateUpgrade.cs | 3,521 | 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.Compute.V20180601.Outputs
{
[OutputType]
public sealed class VirtualHardDiskResponse
{
/// <summary>
/// Specifies the virtual hard disk's uri.
/// </summary>
public readonly string? Uri;
[OutputConstructor]
private VirtualHardDiskResponse(string? uri)
{
Uri = uri;
}
}
}
| 24.821429 | 81 | 0.654676 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20180601/Outputs/VirtualHardDiskResponse.cs | 695 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Middleware.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
} | 25.761905 | 80 | 0.676525 | [
"MIT"
] | ViniciusTavares/.Net-DDD-Sample | Middleware/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs | 541 | C# |
using System;
using System.Collections.Generic;
using AliCloudOpenSearch.com.API;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace AliCloudAPITest
{
/// <summary>
/// UnitTest1 的摘要说明
/// </summary>
[TestFixture]
public class CloudSearchApiTest : CloudSearchApiAliyunBase
{
private int rep;
/// <summary>
/// 获取或设置测试上下文,该上下文提供
/// 有关当前测试运行及其功能的信息。
/// </summary>
public TestContext TestContext { get; set; }
[Test]
public void TestAPI()
{
var customD2 = new Dictionary<string, object>
{
{"param1", new Dictionary<string, object> {{"a", 1}, {"b", 2}}},
{"param2", new object[] {"c", "d", new Dictionary<string, object> {{"e", 1}}}}
};
var res = HttpBuildQueryHelper.FormatDictionary(customD2);
Console.WriteLine(res);
}
[Test]
public void TestCreateIndex()
{
var appName = DateTime.UtcNow.Ticks.ToString();
var target = new CloudsearchApplication(api);
var template = "template1";
string actual;
actual = target.CreateByTemplate(appName, template);
Console.WriteLine(actual);
var jo = JObject.Parse(actual);
//Console.WriteLine(result);
Assert.AreEqual("OK", (string)jo["status"]);
actual = target.Delete(appName);
Console.WriteLine(actual);
//"result":{"index_name":"4N0F6H","description":""},"status":"OK"}
jo = JObject.Parse(actual);
Assert.AreEqual("OK", (string)jo["status"]);
}
[Test]
public void TestGetErrorMessage()
{
var target = new CloudsearchApplication(api);
var result = target.GetErrorMessage("hotel");
var jo = JObject.Parse(result);
Assert.AreEqual("OK", (string)jo["status"]);
}
[Test]
public void TestListIndex()
{
var target = new CloudsearchApplication(mockApi);
var result = target.ListApplications();
AssertPath("/index", result);
AssertEqualFromQueryString("page", "1", result);
result = target.ListApplications(2, 2);
AssertEqualFromQueryString("page", "2", result);
}
[Test]
public void TestStatusIndex()
{
var target = new CloudsearchApplication(api);
var result = target.Status("hotel");
Console.WriteLine(result);
//Assert.AreEqual(expected, actual);
//Assert.Inconclusive("验证此测试方法的正确性。");
var jo = JObject.Parse(result);
Assert.AreEqual("OK", (string)jo["status"]);
}
[Test]
public void TestTopQuery()
{
var css = new CloudsearchAnalysis("hotel", api);
var result = css.GetTopQuery(100, 100);
var jo = JObject.Parse(result);
Console.WriteLine(result);
Assert.AreEqual("OK", (string)jo["status"]);
}
[Test]
public void TestUnixTimeStamp()
{
var stamp = Utilities.getUnixTimeStamp();
Console.WriteLine(stamp);
}
}
} | 28.29661 | 94 | 0.537287 | [
"Apache-2.0"
] | aliyun-beta/aliyun-opensearch-.net-sdk | AliCouldOpenSearchAPI_vs2015_2.1.3/AliCloudOpenSearchAPITest/CloudSearchApiTest.cs | 3,441 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace AgendaDemo
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
}
| 22.909091 | 81 | 0.698413 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | srdelsalto/XamarinProject | Xamarin Curse/AgendaDemo/AgendaDemo/AgendaDemo/MainPage.xaml.cs | 506 | C# |
using System;
using System.Numerics;
namespace TrentTobler.Algorithms.FourierTransform
{
public static class DiscreteFourierTransform
{
public static Complex[] Dft( this Complex[] x )
{
var len = x.Length;
var y = new Complex[len];
for( var k = 0; k < len; ++k )
{
var dw = 2 * Math.PI * k / len;
var sum = x[0];
for( var n = 1; n < len; ++n )
{
var w = dw * n;
sum += x[n] * new Complex( Math.Cos( w ), -Math.Sin( w ) );
}
y[k] = sum;
}
return y;
}
public static Complex[] InverseDft( this Complex[] x )
{
var len = x.Length;
var y = new Complex[len];
for( var k = 0; k < len; ++k )
{
var dw = 2 * Math.PI * k / len;
var sum = x[0];
for( var n = 1; n < len; ++n )
{
var w = dw * n;
sum += x[n] * new Complex( Math.Cos( w ), Math.Sin( w ) );
}
y[k] = sum / len;
}
return y;
}
public static Complex[,] Dft2D( this Complex[,] x )
{
var len0 = x.GetLength( 0 );
var len1 = x.GetLength( 1 );
var y = new Complex[len0, len1];
for( var k0 = 0; k0 < len0; ++k0 )
{
var dw0 = 2 * Math.PI * k0 / len0;
for( var k1 = 0; k1 < len1; ++k1 )
{
var dw1 = 2 * Math.PI * k1 / len1;
var sum = Complex.Zero;
for( var n0 = 0; n0 < len0; ++n0 )
{
var w0 = dw0 * n0;
for( var n1 = 0; n1 < len1; ++n1 )
{
var w1 = dw1 * n1;
var wct = new Complex( Math.Cos( w0 + w1 ), -Math.Sin( w0 + w1 ) );
sum += x[n0, n1] * wct;
}
}
y[k0, k1] = sum;
}
}
return y;
}
public static Complex[,] InverseDft2D( this Complex[,] x )
{
var len0 = x.GetLength( 0 );
var len1 = x.GetLength( 1 );
var lenT = len0 * len1;
var y = new Complex[len0, len1];
for( var k0 = 0; k0 < len0; ++k0 )
{
var dw0 = 2 * Math.PI * k0 / len0;
for( var k1 = 0; k1 < len1; ++k1 )
{
var sum = Complex.Zero;
var dw1 = 2 * Math.PI * k1 / len1;
for( var n0 = 0; n0 < len0; ++n0 )
{
var w0 = dw0 * n0;
for( var n1 = 0; n1 < len1; ++n1 )
{
var w1 = dw1 * n1;
var wct = new Complex( Math.Cos( w0 + w1 ), Math.Sin( w0 + w1 ) );
sum += x[n0, n1] * wct;
}
}
y[k0, k1] = sum / lenT;
}
}
return y;
}
public static Complex[,,] Dft3D( this Complex[,,] x )
{
var len0 = x.GetLength( 0 );
var len1 = x.GetLength( 1 );
var len2 = x.GetLength( 2 );
var y = new Complex[len0, len1, len2];
for( var k0 = 0; k0 < len0; ++k0 )
{
var dw0 = 2 * Math.PI * k0 / len0;
for( var k1 = 0; k1 < len1; ++k1 )
{
var dw1 = 2 * Math.PI * k1 / len1;
for( var k2 = 0; k2 < len2; ++k2 )
{
var dw2 = 2 * Math.PI * k2 / len2;
var sum = Complex.Zero;
for( var n0 = 0; n0 < len0; ++n0 )
{
var w0 = dw0 * n0;
for( var n1 = 0; n1 < len1; ++n1 )
{
var w1 = dw1 * n1;
for( var n2 = 0; n2 < len2; ++n2 )
{
var w2 = dw2 * n2;
var wct = new Complex( Math.Cos( w0 + w1 + w2 ), -Math.Sin( w0 + w1 + w2 ) );
sum += x[n0, n1, n2] * wct;
}
}
}
y[k0, k1, k2] = sum;
}
}
}
return y;
}
public static Complex[,,] InverseDft3D( this Complex[,,] x )
{
var len0 = x.GetLength( 0 );
var len1 = x.GetLength( 1 );
var len2 = x.GetLength( 2 );
var lenT = len0 * len1 * len2;
var y = new Complex[len0, len1, len2];
for( var k0 = 0; k0 < len0; ++k0 )
{
var dw0 = 2 * Math.PI * k0 / len0;
for( var k1 = 0; k1 < len1; ++k1 )
{
var dw1 = 2 * Math.PI * k1 / len1;
for( var k2 = 0; k2 < len2; ++k2 )
{
var dw2 = 2 * Math.PI * k2 / len2;
var sum = Complex.Zero;
for( var n0 = 0; n0 < len0; ++n0 )
{
var w0 = dw0 * n0;
for( var n1 = 0; n1 < len1; ++n1 )
{
var w1 = dw1 * n1;
for( var n2 = 0; n2 < len2; ++n2 )
{
var w2 = dw2 * n2;
var wct = new Complex( Math.Cos( w0 + w1 + w2 ), Math.Sin( w0 + w1 + w2 ) );
sum += x[n0, n1, n2] * wct;
}
}
}
y[k0, k1, k2] = sum / lenT;
}
}
}
return y;
}
}
}
| 19.941964 | 87 | 0.425565 | [
"MIT"
] | trenttobler/FourierTransform | TrentTobler.Algorithms.FourierTransform/DiscreteFourierTransform.cs | 4,469 | C# |
using Core.Entities.Abstract;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Core.DataAccess.EntityFramework
{
public class EfEntityRepositoryBase<TEntity, TContext> : IEntityRepository<TEntity>
where TEntity: class, IEntity, new()
where TContext: DbContext, new()
{
public void Add(TEntity entity)
{
using (TContext context = new TContext())
{
var addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
context.SaveChanges();
}
}
public void Delete(TEntity entity)
{
using (TContext context = new TContext())
{
var deletedEntity = context.Entry(entity);
deletedEntity.State = EntityState.Deleted;
context.SaveChanges();
}
}
public TEntity Get(Expression<Func<TEntity, bool>> filter)
{
using (TContext context = new TContext())
{
return context.Set<TEntity>().SingleOrDefault(filter);
}
}
public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null)
{
using (TContext context = new TContext())
{
return filter == null ? context.Set<TEntity>().ToList()
: context.Set<TEntity>().Where(filter).ToList();
}
}
public void Update(TEntity entity)
{
using (TContext context = new TContext())
{
var updatedEntity = context.Entry(entity);
updatedEntity.State = EntityState.Modified;
context.SaveChanges();
}
}
}
} | 30.693548 | 87 | 0.544404 | [
"MIT"
] | mcaliskan7/CSharpCampReCapProject | Core/DataAccess/EntityFramework/EfEntityRepositoryBase.cs | 1,905 | C# |
using System;
using Common.Structure.Base;
namespace Common.Structure
{
public class Status:BaseStatus
{
public override long Id { get; set; }
public override DateTime LogTime { get; set; }
public override long ItemCount { get; set; }
public override long UserCount { get; set; }
public override long QueryCount { get; set; }
}
}
| 24.8 | 53 | 0.663978 | [
"MIT"
] | ifdog/Queries | Queries/Common/Structure/Status.cs | 374 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using JetBrains.Space.Client;
namespace JetBrains.Space.AspNetCore.Experimental.WebHooks;
/// <inheritdoc/>
public abstract class SpaceWebHookHandler
: ISpaceWebHookHandler
{
/// <inheritdoc/>
public virtual Task<Commands> HandleListCommandsAsync(ListCommandsPayload payload)
=> Task.FromResult(new Commands(new List<CommandDetail>()));
/// <inheritdoc/>
public virtual Task<MenuExtensions> HandleListMenuExtensionsAsync(ListMenuExtensionsPayload payload)
=> Task.FromResult(new MenuExtensions(new List<MenuExtensionDetail>()));
/// <inheritdoc/>
public virtual Task HandleMessageAsync(MessagePayload payload)
=> Task.CompletedTask;
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleMessageActionAsync(MessageActionPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleMenuActionAsync(MenuActionPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleWebhookRequestAsync(WebhookRequestPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleNewUnfurlQueueItemsAsync(NewUnfurlQueueItemsPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleInitAsync(InitPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleChangeClientSecretRequestAsync(ChangeClientSecretPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleChangeServerUrlAsync(ChangeServerUrlPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
/// <inheritdoc/>
public virtual Task<ApplicationExecutionResult> HandleAppPublicationCheckAsync(AppPublicationCheckPayload payload)
=> Task.FromResult(new ApplicationExecutionResult());
} | 43.611111 | 123 | 0.751592 | [
"Apache-2.0"
] | JetBrains/space-dotnet-sdk | src/JetBrains.Space.AspNetCore/Experimental/WebHooks/SpaceWebHookHandler.cs | 2,355 | C# |
using System.Collections.Generic;
using System.IO;
using System.Text;
using Netch.Controllers;
using Netch.Models;
namespace Netch.Servers.Shadowsocks
{
public class SSController : Guard, IServerController
{
public override string MainFile { get; protected set; } = "Shadowsocks.exe";
protected override IEnumerable<string> StartedKeywords { get; } = new[] {"listening at"};
protected override IEnumerable<string> StoppedKeywords { get; } = new[] {"Invalid config path", "usage", "plugin service exit unexpectedly"};
public override string Name { get; } = "Shadowsocks";
public ushort? Socks5LocalPort { get; set; }
public string? LocalAddress { get; set; }
public void Start(in Server s, in Mode mode)
{
var server = (Shadowsocks) s;
var command = new SSParameter
{
s = server.AutoResolveHostname(),
p = server.Port,
b = this.LocalAddress(),
l = this.Socks5LocalPort(),
m = server.EncryptMethod,
k = server.Password,
u = true,
plugin = server.Plugin,
plugin_opts = server.PluginOption
};
if (mode.BypassChina)
command.acl = $"{Path.GetFullPath(File.Exists(Constants.UserACL) ? Constants.UserACL : Constants.BuiltinACL)}";
StartInstanceAuto(command.ToString());
}
[Verb]
private class SSParameter : ParameterBase
{
public string? s { get; set; }
public ushort? p { get; set; }
public string? b { get; set; }
public ushort? l { get; set; }
public string? m { get; set; }
public string? k { get; set; }
public bool u { get; set; }
[Full]
[Optional]
public string? plugin { get; set; }
[Full]
[Optional]
[RealName("plugin-opts")]
public string? plugin_opts { get; set; }
[Full]
[Quote]
[Optional]
public string? acl { get; set; }
}
public override void Stop()
{
StopInstance();
}
}
} | 27.722892 | 149 | 0.527597 | [
"MIT"
] | 1pipi2/Netch | Netch/Servers/Shadowsocks/SSController.cs | 2,301 | C# |
using Prism.Mvvm;
using System.ComponentModel.Composition;
namespace Tida.Canvas.Shell.Splash.ViewModels {
[Export]
public class SplashViewModel:BindableBase {
private string _loadingText;
public string LoadingText {
get { return _loadingText; }
set { SetProperty(ref _loadingText, value); }
}
}
}
| 23.125 | 57 | 0.640541 | [
"MIT"
] | JanusTida/Tida.CAD | Tida.Canvas.Shell/Splash/ViewModels/SplashViewModel.cs | 372 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.