content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Furion; using Furion.DependencyInjection; using Furion.UnifyResult; using System; using System.Linq; using System.Reflection; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// 应用服务集合拓展类(由框架内部调用) /// </summary> [SkipScan] public static class AppServiceCollectionExtensions { /// <summary> /// MiniProfiler 插件路径 /// </summary> private const string MiniProfilerRouteBasePath = "/index-mini-profiler"; /// <summary> /// Mvc 注入基础配置(带Swagger) /// </summary> /// <param name="mvcBuilder">Mvc构建器</param> /// <returns>IMvcBuilder</returns> public static IMvcBuilder AddInject(this IMvcBuilder mvcBuilder) { mvcBuilder.AddSpecificationDocuments() .AddDynamicApiControllers() .AddDataValidation() .AddFriendlyException(); return mvcBuilder; } /// <summary> /// 服务注入基础配置(带Swagger) /// </summary> /// <param name="services">服务集合</param> /// <returns>IMvcBuilder</returns> public static IServiceCollection AddInject(this IServiceCollection services) { services.AddSpecificationDocuments() .AddDynamicApiControllers() .AddDataValidation() .AddFriendlyException(); return services; } /// <summary> /// Mvc 注入基础配置 /// </summary> /// <param name="mvcBuilder">Mvc构建器</param> /// <param name="includeDynamicApiController"></param> /// <returns>IMvcBuilder</returns> public static IMvcBuilder AddInjectBase(this IMvcBuilder mvcBuilder, bool includeDynamicApiController = true) { if (includeDynamicApiController) mvcBuilder.AddDynamicApiControllers(); mvcBuilder.AddDataValidation() .AddFriendlyException(); return mvcBuilder; } /// <summary> /// Mvc 注入基础配置 /// </summary> /// <param name="services">服务集合</param> /// <param name="includeDynamicApiController"></param> /// <returns>IMvcBuilder</returns> public static IServiceCollection AddInjectBase(this IServiceCollection services, bool includeDynamicApiController = true) { if (includeDynamicApiController) services.AddDynamicApiControllers(); services.AddDataValidation() .AddFriendlyException(); return services; } /// <summary> /// Mvc 注入基础配置和规范化结果 /// </summary> /// <param name="mvcBuilder"></param> /// <returns></returns> public static IMvcBuilder AddInjectWithUnifyResult(this IMvcBuilder mvcBuilder) { mvcBuilder.AddInject() .AddUnifyResult(); return mvcBuilder; } /// <summary> /// 注入基础配置和规范化结果 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddInjectWithUnifyResult(this IServiceCollection services) { services.AddInject() .AddUnifyResult(); return services; } /// <summary> /// Mvc 注入基础配置和规范化结果 /// </summary> /// <typeparam name="TUnifyResultProvider"></typeparam> /// <param name="mvcBuilder"></param> /// <returns></returns> public static IMvcBuilder AddInjectWithUnifyResult<TUnifyResultProvider>(this IMvcBuilder mvcBuilder) where TUnifyResultProvider : class, IUnifyResultProvider { mvcBuilder.AddInject() .AddUnifyResult<TUnifyResultProvider>(); return mvcBuilder; } /// <summary> /// Mvc 注入基础配置和规范化结果 /// </summary> /// <typeparam name="TUnifyResultProvider"></typeparam> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddInjectWithUnifyResult<TUnifyResultProvider>(this IServiceCollection services) where TUnifyResultProvider : class, IUnifyResultProvider { services.AddInject() .AddUnifyResult<TUnifyResultProvider>(); return services; } /// <summary> /// 添加应用配置 /// </summary> /// <param name="services">服务集合</param> /// <param name="configure">服务配置</param> /// <returns>服务集合</returns> internal static IServiceCollection AddApp(this IServiceCollection services, Action<IServiceCollection> configure = null) { // 注册全局配置选项 services.AddConfigurableOptions<AppSettingsOptions>(); // 添加 HttContext 访问器 services.AddHttpContextAccessor(); // 注册分布式内存缓存 services.AddDistributedMemoryCache(); // 注册全局 Startup 扫描 services.AddStartup(); // 注册MiniProfiler 组件 if (App.Settings.InjectMiniProfiler == true) { services.AddMiniProfiler(options => { options.RouteBasePath = MiniProfilerRouteBasePath; }).AddEntityFramework(); } // 注册全局依赖注入 services.AddDependencyInjection(); // 添加对象映射 services.AddObjectMapper(); // 自定义服务 configure?.Invoke(services); return services; } /// <summary> /// 添加 Startup 自动扫描 /// </summary> /// <param name="services">服务集合</param> /// <returns>服务集合</returns> internal static IServiceCollection AddStartup(this IServiceCollection services) { // 扫描所有继承 AppStartup 的类 var startups = App.EffectiveTypes .Where(u => typeof(AppStartup).IsAssignableFrom(u) && u.IsClass && !u.IsAbstract && !u.IsGenericType) .OrderByDescending(u => GetOrder(u)); // 注册自定义 starup foreach (var type in startups) { var startup = Activator.CreateInstance(type) as AppStartup; App.AppStartups.Add(startup); // 获取所有符合依赖注入格式的方法,如返回值void,且第一个参数是 IServiceCollection 类型 var serviceMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(u => u.ReturnType == typeof(void) && u.GetParameters().Length > 0 && u.GetParameters().First().ParameterType == typeof(IServiceCollection)); if (!serviceMethods.Any()) continue; // 自动安装属性调用 foreach (var method in serviceMethods) { method.Invoke(startup, new[] { services }); } } return services; } /// <summary> /// 获取 Startup 排序 /// </summary> /// <param name="type">排序类型</param> /// <returns>int</returns> private static int GetOrder(Type type) { return !type.IsDefined(typeof(AppStartupAttribute), true) ? 0 : type.GetCustomAttribute<AppStartupAttribute>(true).Order; } } }
32.535088
129
0.552979
[ "Apache-2.0" ]
dotNetTreasury/Furion
framework/Furion/App/Extensions/AppServiceCollectionExtensions.cs
7,936
C#
using System; using System.Diagnostics; using System.IO; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Appium; using OpenQA.Selenium.Appium.Windows; using OpenQA.Selenium.Interactions; namespace PowerToysTests { public class PowerToysSession { protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723"; protected static WindowsDriver<WindowsElement> session; protected static bool isPowerToysLaunched = false; protected static WindowsElement trayButton; protected static string _settingsFolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\\PowerToys\\FancyZones"); protected static string _settingsPath = _settingsFolderPath + "\\settings.json"; protected static string _zoneSettingsPath = _settingsFolderPath + "\\zones-settings.json"; protected static string _initialSettings = ""; protected static string _initialZoneSettings = ""; protected const string _defaultSettings = "{\"version\":\"1.0\",\"name\":\"FancyZones\",\"properties\":{\"fancyzones_shiftDrag\":{\"value\":true},\"fancyzones_overrideSnapHotkeys\":{\"value\":false},\"fancyzones_zoneSetChange_flashZones\":{\"value\":false},\"fancyzones_displayChange_moveWindows\":{\"value\":false},\"fancyzones_zoneSetChange_moveWindows\":{\"value\":false},\"fancyzones_virtualDesktopChange_moveWindows\":{\"value\":false},\"fancyzones_appLastZone_moveWindows\":{\"value\":false},\"use_cursorpos_editor_startupscreen\":{\"value\":true},\"fancyzones_zoneHighlightColor\":{\"value\":\"#0078D7\"},\"fancyzones_highlight_opacity\":{\"value\":90},\"fancyzones_editor_hotkey\":{\"value\":{\"win\":true,\"ctrl\":false,\"alt\":false,\"shift\":false,\"code\":192,\"key\":\"`\"}},\"fancyzones_excluded_apps\":{\"value\":\"\"}}}"; protected const string _defaultZoneSettings = "{\"app-zone-history\":[],\"devices\":[],\"custom-zone-sets\":[]}"; public static void Setup(TestContext context, bool isLaunchRequired = true) { ReadUserSettings(); //read settings before running tests to restore them after if (session == null) { // Create a new Desktop session to use PowerToys. AppiumOptions appiumOptions = new AppiumOptions(); appiumOptions.PlatformName = "Windows"; appiumOptions.AddAdditionalCapability("app", "Root"); session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appiumOptions); Assert.IsNotNull(session); trayButton = session.FindElementByAccessibilityId("1502"); isPowerToysLaunched = CheckPowerToysLaunched(); if (!isPowerToysLaunched && isLaunchRequired) { LaunchPowerToys(); } } } public static void TearDown() { RestoreUserSettings(); //restore initial settings files if (session != null) { session.Quit(); session = null; } } public static void WaitSeconds(double seconds) { Thread.Sleep(TimeSpan.FromSeconds(seconds)); } public static void ShortWait() { Thread.Sleep(TimeSpan.FromSeconds(0.5)); } //Trying to find element by XPath protected WindowsElement WaitElementByXPath(string xPath, double maxTime = 10) { WindowsElement result = null; Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.Elapsed < TimeSpan.FromSeconds(maxTime)) { try { result = session.FindElementByXPath(xPath); } catch { } if (result != null) { return result; } } Assert.IsNotNull(result); return null; } //Trying to find element by AccessibilityId protected WindowsElement WaitElementByAccessibilityId(string accessibilityId, double maxTime = 10) { WindowsElement result = null; Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.Elapsed < TimeSpan.FromSeconds(maxTime)) { try { result = session.FindElementByAccessibilityId(accessibilityId); } catch { } if (result != null) { return result; } } Assert.IsNotNull(result); return null; } public static void OpenSettings() { trayButton.Click(); session.FindElementByXPath("//Button[@Name=\"PowerToys\"]").Click(); trayButton.Click(); } public static void OpenFancyZonesSettings() { WindowsElement fzNavigationButton = session.FindElementByXPath("//Button[@Name=\"FancyZones\"]"); Assert.IsNotNull(fzNavigationButton); fzNavigationButton.Click(); fzNavigationButton.Click(); ShortWait(); } public static void CloseSettings() { try { WindowsElement settings = session.FindElementByName("PowerToys Settings"); if (settings != null) { settings.SendKeys(Keys.Alt + Keys.F4); } } catch(Exception) { } } private static bool CheckPowerToysLaunched() { trayButton.Click(); bool isLaunched = false; try { WindowsElement pt = session.FindElementByXPath("//Button[@Name=\"PowerToys\"]"); isLaunched = (pt != null); } catch(OpenQA.Selenium.WebDriverException) { //PowerToys not found } trayButton.Click(); //close return isLaunched; } public static void LaunchPowerToys() { try { AppiumOptions opts = new AppiumOptions(); opts.PlatformName = "Windows"; opts.AddAdditionalCapability("platformVersion", "10"); opts.AddAdditionalCapability("deviceName", "WindowsPC"); opts.AddAdditionalCapability("app", "C:/Program Files/PowerToys/PowerToys.exe"); WindowsDriver<WindowsElement> driver = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), opts); Assert.IsNotNull(driver); driver.LaunchApp(); } catch (OpenQA.Selenium.WebDriverException ex) { Console.WriteLine("Exception on PowerToys launch:" + ex.Message); //exception could be thrown even if app launched successfully } isPowerToysLaunched = true; } public static void ExitPowerToys() { trayButton.Click(); ShortWait(); WindowsElement pt = session.FindElementByXPath("//Button[@Name=\"PowerToys\"]"); new Actions(session).MoveToElement(pt).ContextClick().Perform(); ShortWait(); session.FindElementByXPath("//MenuItem[@Name=\"Exit\"]").Click(); trayButton.Click(); //close tray isPowerToysLaunched = false; } public static void ResetDefaultFancyZonesSettings(bool relaunch) { ResetSettings(_settingsFolderPath, _settingsPath, _defaultSettings, relaunch); } public static void ResetDefautZoneSettings(bool relaunch) { ResetSettings(_settingsFolderPath, _zoneSettingsPath, _defaultZoneSettings, relaunch); } private static void ResetSettings(string folder, string filePath, string data, bool relaunch) { if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } File.WriteAllText(filePath, data); if (isPowerToysLaunched) { ExitPowerToys(); } if (relaunch) { LaunchPowerToys(); } } private static void ReadUserSettings() { try { _initialSettings = File.ReadAllText(_settingsPath); } catch (Exception) { //failed to read settings } try { _initialZoneSettings = File.ReadAllText(_zoneSettingsPath); } catch (Exception) { //failed to read settings } } private static void RestoreUserSettings() { if (_initialSettings.Length > 0) { File.WriteAllText(_settingsPath, _initialSettings); } else { File.Delete(_settingsPath); } if (_initialZoneSettings.Length > 0) { File.WriteAllText(_zoneSettingsPath, _initialZoneSettings); } else { File.Delete(_zoneSettingsPath); } } } }
35.124555
846
0.542047
[ "MIT" ]
S3curityPlu5/PowerToys
src/tests/win-app-driver/PowerToysSession.cs
9,870
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Devices.Bluetooth.GenericAttributeProfile { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class GattLocalDescriptor { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Devices.Bluetooth.GenericAttributeProfile.GattProtectionLevel ReadProtectionLevel { get { throw new global::System.NotImplementedException("The member GattProtectionLevel GattLocalDescriptor.ReadProtectionLevel is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Storage.Streams.IBuffer StaticValue { get { throw new global::System.NotImplementedException("The member IBuffer GattLocalDescriptor.StaticValue is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::System.Guid Uuid { get { throw new global::System.NotImplementedException("The member Guid GattLocalDescriptor.Uuid is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Devices.Bluetooth.GenericAttributeProfile.GattProtectionLevel WriteProtectionLevel { get { throw new global::System.NotImplementedException("The member GattProtectionLevel GattLocalDescriptor.WriteProtectionLevel is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.Uuid.get // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.StaticValue.get // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.ReadProtectionLevel.get // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.WriteProtectionLevel.get // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.ReadRequested.add // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.ReadRequested.remove // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.WriteRequested.add // Forced skipping of method Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor.WriteRequested.remove #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public event global::Windows.Foundation.TypedEventHandler<global::Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor, global::Windows.Devices.Bluetooth.GenericAttributeProfile.GattReadRequestedEventArgs> ReadRequested { [global::Uno.NotImplemented] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor", "event TypedEventHandler<GattLocalDescriptor, GattReadRequestedEventArgs> GattLocalDescriptor.ReadRequested"); } [global::Uno.NotImplemented] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor", "event TypedEventHandler<GattLocalDescriptor, GattReadRequestedEventArgs> GattLocalDescriptor.ReadRequested"); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public event global::Windows.Foundation.TypedEventHandler<global::Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor, global::Windows.Devices.Bluetooth.GenericAttributeProfile.GattWriteRequestedEventArgs> WriteRequested { [global::Uno.NotImplemented] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor", "event TypedEventHandler<GattLocalDescriptor, GattWriteRequestedEventArgs> GattLocalDescriptor.WriteRequested"); } [global::Uno.NotImplemented] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Devices.Bluetooth.GenericAttributeProfile.GattLocalDescriptor", "event TypedEventHandler<GattLocalDescriptor, GattWriteRequestedEventArgs> GattLocalDescriptor.WriteRequested"); } } #endif } }
50.336957
263
0.801771
[ "Apache-2.0" ]
AlexTrepanier/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Bluetooth.GenericAttributeProfile/GattLocalDescriptor.cs
4,631
C#
using System; using System.Buffers; using System.Linq; namespace Parquet.Data { abstract class BasicPrimitiveDataTypeHandler<TSystemType> : BasicDataTypeHandler<TSystemType> where TSystemType : struct { private static readonly ArrayPool<int> IntPool = ArrayPool<int>.Shared; public BasicPrimitiveDataTypeHandler(DataType dataType, Thrift.Type thriftType, Thrift.ConvertedType? convertedType = null) : base(dataType, thriftType, convertedType) { } public override Array GetArray(int minCount, bool rent, bool isNullable) { if(rent) { return isNullable ? ArrayPool<TSystemType?>.Shared.Rent(minCount) : ArrayPool<TSystemType?>.Shared.Rent(minCount); } if (isNullable) { return new TSystemType?[minCount]; } return new TSystemType[minCount]; } public override Array PackDefinitions(Array data, int maxDefinitionLevel, out int[] definitions, out int definitionsLength, out int nullCount) { return PackDefinitions((TSystemType?[])data, maxDefinitionLevel, out definitions, out definitionsLength, out nullCount); } public override Array UnpackDefinitions(Array untypedSource, int[] definitionLevels, int maxDefinitionLevel, out bool[] hasValueFlags) { return UnpackDefinitions((TSystemType[])untypedSource, definitionLevels, maxDefinitionLevel, out hasValueFlags); } private TSystemType?[] UnpackDefinitions(TSystemType[] src, int[] definitionLevels, int maxDefinitionLevel, out bool[] hasValueFlags) { TSystemType?[] result = (TSystemType?[])GetArray(definitionLevels.Length, false, true); hasValueFlags = new bool[definitionLevels.Length]; int isrc = 0; for (int i = 0; i < definitionLevels.Length; i++) { int level = definitionLevels[i]; if (level == maxDefinitionLevel) { result[i] = src[isrc++]; hasValueFlags[i] = true; } else if(level == 0) { hasValueFlags[i] = true; } } return result; } private TSystemType[] PackDefinitions(TSystemType?[] data, int maxDefinitionLevel, out int[] definitionLevels, out int definitionsLength, out int nullCount) { definitionLevels = IntPool.Rent(data.Length); definitionsLength = data.Length; nullCount = data.Count(i => !i.HasValue); TSystemType[] result = new TSystemType[data.Length - nullCount]; int ir = 0; for(int i = 0; i < data.Length; i++) { TSystemType? value = data[i]; if(value == null) { definitionLevels[i] = 0; } else { definitionLevels[i] = maxDefinitionLevel; result[ir++] = value.Value; } } return result; } } }
31.525773
162
0.596468
[ "MIT" ]
Rokannon/parquet-dotnet
src/Parquet/Data/BasicPrimitiveDataTypeHandler.cs
3,060
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ModeleVueVueModele { public class VueArticle : IVue { // Affiche le titre de l'article private string titre; public string TitreArticle { get => titre; set { titre = value; OnModifierPropVue?.Invoke("TitreArticle"); } } // Modification d'une propriété public event Action<string> OnModifierPropVue; // Initialise les valeurs affichées dans la vue public void Initialiser(string titre) { this.titre = titre; // En passant par l'attribut, on évite une màj inutile } public void Afficher() { if (TitreArticle != null) { Console.WriteLine("Le titre de l'article est " + TitreArticle); } Console.WriteLine("Quel est le titre de l'article ?"); TitreArticle = Console.ReadLine(); } } }
25.837209
90
0.549055
[ "Unlicense" ]
thecakeisreal/Exemples-Architectures
Modele-Vue-Vue modele/VueArticle.cs
1,118
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CoreQuiz.Services { // This class is used by the application to send Email and SMS // when you turn on two-factor authentication in ASP.NET Identity. // For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713 public class AuthMessageSender : IEmailSender, ISmsSender { public Task SendEmailAsync(string email, string subject, string message) { // Plug in your email service here to send an email. return Task.FromResult(0); } public Task SendSmsAsync(string number, string message) { // Plug in your SMS service here to send a text message. return Task.FromResult(0); } } }
31.730769
83
0.66303
[ "MIT" ]
witoldlitwin/CoreQuiz
src/CoreQuiz/Services/MessageServices.cs
827
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using MoreLinq; using NewRelic.Agent.Configuration; using NewRelic.Agent.Core.Attributes; using NewRelic.Agent.Core.Errors; using NewRelic.Agent.Core.Segments; using NewRelic.Agent.Core.Transactions; using NewRelic.Testing.Assertions; using NUnit.Framework; using Telerik.JustMock; namespace NewRelic.Agent.Core.Transformers.TransactionTransformer.UnitTest { [TestFixture] public class ErrorTraceMakerTests { private IConfigurationService _configurationService; private ErrorTraceMaker _errorTraceMaker; private ErrorService _errorService; private AttributeDefinitionService _attribDefSvc; private IAttributeDefinitions _attribDefs => _attribDefSvc.AttributeDefs; private const string StripExceptionMessagesMessage = "Message removed by New Relic based on your currently enabled security settings."; [SetUp] public void SetUp() { _configurationService = Mock.Create<IConfigurationService>(); _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f)); _errorTraceMaker = new ErrorTraceMaker(_configurationService); _errorService = new ErrorService(_configurationService); } [Test] public void GetErrorTrace_ReturnsErrorTrace_IfStatusCodeIs404() { var transaction = BuildTestTransaction(statusCode: 404, uri: "http://www.newrelic.com/test?param=value"); var attributes = new AttributeValueCollection(AttributeDestinations.ErrorTrace); var transactionMetricName = new TransactionMetricName("WebTransaction", "Name"); var errorTrace = _errorTraceMaker.GetErrorTrace(transaction, attributes, transactionMetricName); Assert.NotNull(errorTrace); NrAssert.Multiple( () => Assert.AreEqual("WebTransaction/Name", errorTrace.Path), () => Assert.AreEqual("Not Found", errorTrace.Message), () => Assert.AreEqual("404", errorTrace.ExceptionClassName), () => Assert.AreEqual(transaction.Guid, errorTrace.Guid), () => Assert.AreEqual(null, errorTrace.Attributes.StackTrace) ); } [Test] public void GetErrorTrace_ReturnsErrorTrace_IfExceptionIsNoticed() { var errorDataIn = _errorService.FromMessage("My message", (Dictionary<string, object>)null, false); var transaction = BuildTestTransaction(uri: "http://www.newrelic.com/test?param=value", transactionExceptionDatas: new[] { errorDataIn }); var attributes = new AttributeValueCollection(AttributeDestinations.ErrorTrace); var transactionMetricName = new TransactionMetricName("WebTransaction", "Name"); var errorTrace = _errorTraceMaker.GetErrorTrace(transaction, attributes, transactionMetricName); Assert.NotNull(errorTrace); NrAssert.Multiple( () => Assert.AreEqual("WebTransaction/Name", errorTrace.Path), () => Assert.AreEqual("My message", errorTrace.Message), () => Assert.AreEqual("Custom Error", errorTrace.ExceptionClassName), () => Assert.AreEqual(transaction.Guid, errorTrace.Guid) ); } [Test] public void GetErrorTrace_ReturnsFirstException_IfMultipleExceptionsNoticed() { var errorData1 = _errorService.FromMessage("My message", (Dictionary<string, object>)null, false); var errorData2 = _errorService.FromMessage("My message2", (Dictionary<string, object>)null, false); var transaction = BuildTestTransaction(uri: "http://www.newrelic.com/test?param=value", transactionExceptionDatas: new[] { errorData1, errorData2 }); var attributes = new AttributeValueCollection(AttributeDestinations.ErrorTrace); var transactionMetricName = new TransactionMetricName("WebTransaction", "Name"); var errorTrace = _errorTraceMaker.GetErrorTrace(transaction, attributes, transactionMetricName); Assert.NotNull(errorTrace); NrAssert.Multiple( () => Assert.AreEqual("WebTransaction/Name", errorTrace.Path), () => Assert.AreEqual("My message", errorTrace.Message), () => Assert.AreEqual("Custom Error", errorTrace.ExceptionClassName), () => Assert.AreEqual(transaction.Guid, errorTrace.Guid) ); } [Test] public void GetErrorTrace_ReturnsExceptionsBeforeStatusCodes() { var errorDataIn = _errorService.FromMessage("My message", (Dictionary<string, object>)null, false); var transaction = BuildTestTransaction(statusCode: 404, uri: "http://www.newrelic.com/test?param=value", transactionExceptionDatas: new[] { errorDataIn }); var attributes = new AttributeValueCollection(AttributeDestinations.ErrorTrace); var transactionMetricName = new TransactionMetricName("WebTransaction", "Name"); var errorTrace = _errorTraceMaker.GetErrorTrace(transaction, attributes, transactionMetricName); Assert.NotNull(errorTrace); NrAssert.Multiple( () => Assert.AreEqual("WebTransaction/Name", errorTrace.Path), () => Assert.AreEqual("My message", errorTrace.Message), () => Assert.AreEqual("Custom Error", errorTrace.ExceptionClassName), () => Assert.AreEqual(transaction.Guid, errorTrace.Guid) ); } [Test] public void GetErrorTrace_ReturnsExceptionWithoutMessage_IfStripExceptionMessageEnabled() { Mock.Arrange(() => _configurationService.Configuration.StripExceptionMessages).Returns(true); var errorData = _errorService.FromMessage("This message should be stripped.", (Dictionary<string, object>)null, false); var transaction = BuildTestTransaction(uri: "http://www.newrelic.com/test?param=value", transactionExceptionDatas: new[] { errorData }); var attributes = new AttributeValueCollection(AttributeDestinations.ErrorTrace); var transactionMetricName = new TransactionMetricName("WebTransaction", "Name"); var errorTrace = _errorTraceMaker.GetErrorTrace(transaction, attributes, transactionMetricName); Assert.NotNull(errorTrace); NrAssert.Multiple( () => Assert.AreEqual("WebTransaction/Name", errorTrace.Path), () => Assert.AreEqual(StripExceptionMessagesMessage, errorTrace.Message), () => Assert.AreEqual("Custom Error", errorTrace.ExceptionClassName), () => Assert.AreEqual(transaction.Guid, errorTrace.Guid) ); } private ImmutableTransaction BuildTestTransaction(string uri = null, string guid = null, int? statusCode = null, int? subStatusCode = null, IEnumerable<ErrorData> transactionExceptionDatas = null) { var transactionMetadata = new TransactionMetadata(); if (uri != null) transactionMetadata.SetUri(uri); if (statusCode != null) transactionMetadata.SetHttpResponseStatusCode(statusCode.Value, subStatusCode, _errorService); if (transactionExceptionDatas != null) transactionExceptionDatas.ForEach(data => transactionMetadata.TransactionErrorState.AddExceptionData(data)); var name = TransactionName.ForWebTransaction("foo", "bar"); var segments = Enumerable.Empty<Segment>(); var metadata = transactionMetadata.ConvertToImmutableMetadata(); guid = guid ?? Guid.NewGuid().ToString(); var attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f)); return new ImmutableTransaction(name, segments, metadata, DateTime.UtcNow, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), guid, false, false, false, 0.5f, false, string.Empty, null, attribDefSvc.AttributeDefs); } } }
51.675
225
0.673803
[ "Apache-2.0" ]
JoshuaColeman/newrelic-dotnet-agent
tests/Agent/UnitTests/Core.UnitTest/Transformers/TransactionTransformer/ErrorTraceMakerTests.cs
8,268
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.MixedReality.WebRTC.Interop; namespace Microsoft.MixedReality.WebRTC { /// <summary> /// Configuration to initialize capture on a local audio device (microphone). /// </summary> public class LocalAudioDeviceInitConfig { /// <summary> /// Enable automated gain control (AGC) on the audio device capture pipeline. /// </summary> public bool? AutoGainControl = null; } /// <summary> /// Implementation of an audio track source producing frames captured from an audio capture device (microphone). /// </summary> /// <seealso cref="LocalAudioTrack"/> public class DeviceAudioTrackSource : AudioTrackSource { /// <summary> /// Create an audio track source using a local audio capture device (microphone). /// </summary> /// <param name="initConfig">Optional configuration to initialize the audio capture on the device.</param> /// <returns>The newly create audio track source.</returns> /// <seealso cref="LocalAudioTrack.CreateFromSource(AudioTrackSource, LocalAudioTrackInitConfig)"/> public static Task<DeviceAudioTrackSource> CreateAsync(LocalAudioDeviceInitConfig initConfig = null) { return Task.Run(() => { // On UWP this cannot be called from the main UI thread, so always call it from // a background worker thread. var config = new DeviceAudioTrackSourceInterop.LocalAudioDeviceMarshalInitConfig(initConfig); uint ret = DeviceAudioTrackSourceInterop.DeviceAudioTrackSource_Create(in config, out DeviceAudioTrackSourceHandle handle); Utils.ThrowOnErrorCode(ret); return new DeviceAudioTrackSource(handle); }); } internal DeviceAudioTrackSource(AudioTrackSourceHandle nativeHandle) : base(nativeHandle) { } /// <inheritdoc/> public override string ToString() { return $"(DeviceAudioTrackSource)\"{Name}\""; } } }
37.866667
139
0.65581
[ "MIT" ]
Bhaskers-Blu-Org2/MixedReality-WebRTC
libs/Microsoft.MixedReality.WebRTC/DeviceAudioTrackSource.cs
2,272
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace AspNetCore.EventLog.PostgreSQL.Migrations { public partial class AddCorrelationIdPublished : Migration { private readonly string _schema; public AddCorrelationIdPublished(string schema) { _schema = schema; } protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( schema: _schema, name: "Content", table: "EventLog_Published", type: "jsonb", nullable: false, oldClrType: typeof(string), oldType: "json"); migrationBuilder.AddColumn<Guid>( schema: _schema, name: "CorrelationId", table: "EventLog_Published", nullable: true); ; } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( schema: _schema, name: "CorrelationId", table: "EventLog_Published"); migrationBuilder.AlterColumn<string>( schema: _schema, name: "Content", table: "EventLog_Published", type: "json", nullable: false, oldClrType: typeof(string), oldType: "jsonb"); } } }
29.254902
71
0.530831
[ "MIT" ]
dev-mich/AspNetCore.EventLog
src/AspNetCore.EventLog.PostgreSQL/Migrations/20191021201027_AddCorrelationIdPublished.cs
1,494
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Hub.Core.Test { using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Microsoft.Azure.Devices.Edge.Hub.CloudProxy; using Microsoft.Azure.Devices.Edge.Hub.Core; using Microsoft.Azure.Devices.Edge.Hub.Core.Device; using Microsoft.Azure.Devices.Edge.Hub.Core.Identity; using Microsoft.Azure.Devices.Edge.Hub.Core.Routing; using Microsoft.Azure.Devices.Edge.Storage; using Microsoft.Azure.Devices.Edge.Util; using Microsoft.Azure.Devices.Edge.Util.Test.Common; using Microsoft.Azure.Devices.Routing.Core; using Microsoft.Azure.Devices.Shared; using Moq; using Xunit; using Constants = Microsoft.Azure.Devices.Edge.Hub.Core.Constants; using IMessage = Microsoft.Azure.Devices.Edge.Hub.Core.IMessage; [Unit] public class EdgeHubConnectionTest { [Theory] [InlineData("1.0", null)] [InlineData("1.1", null)] [InlineData("1.2", null)] [InlineData("1.3", null)] [InlineData("1", typeof(ArgumentException))] [InlineData("", typeof(ArgumentException))] [InlineData(null, typeof(ArgumentException))] [InlineData("0.1", typeof(InvalidOperationException))] [InlineData("2.0", typeof(InvalidOperationException))] [InlineData("2.1", typeof(InvalidOperationException))] public void SchemaVersionCheckTest(string schemaVersion, Type expectedException) { if (expectedException != null) { Assert.Throws(expectedException, () => EdgeHubConnection.ValidateSchemaVersion(schemaVersion)); } else { EdgeHubConnection.ValidateSchemaVersion(schemaVersion); } } [Fact] public async Task HandleMethodInvocationTest() { // Arrange var edgeHubIdentity = Mock.Of<IModuleIdentity>(); var twinManager = Mock.Of<ITwinManager>(); var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>()); var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>(); var twinMessageConverter = Mock.Of<Core.IMessageConverter<Twin>>(); var versionInfo = new VersionInfo("1.0", "1", "123"); var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>(); deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).Returns(Task.CompletedTask); var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object); string correlationId = Guid.NewGuid().ToString(); var requestPayload = new { deviceIds = new[] { "d1", "d2" } }; byte[] requestBytes = requestPayload.ToBytes(); var directMethodRequest = new DirectMethodRequest(correlationId, Constants.ServiceIdentityRefreshMethodName, requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); // Act DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest); // Assert Assert.NotNull(directMethodResponse); Assert.Equal(HttpStatusCode.OK, directMethodResponse.HttpStatusCode); } [Fact] public async Task HandleMethodInvocationBadInputTest() { // Arrange var edgeHubIdentity = Mock.Of<IModuleIdentity>(); var twinManager = Mock.Of<ITwinManager>(); var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>()); var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>(); var twinMessageConverter = Mock.Of<Core.IMessageConverter<Twin>>(); var versionInfo = new VersionInfo("1.0", "1", "123"); var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>(); deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).Returns(Task.CompletedTask); var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object); string correlationId = Guid.NewGuid().ToString(); var requestPayload = new [] { "d1", "d2" }; byte[] requestBytes = requestPayload.ToBytes(); var directMethodRequest = new DirectMethodRequest(correlationId, Constants.ServiceIdentityRefreshMethodName, requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); // Act DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest); // Assert Assert.NotNull(directMethodResponse); Assert.Equal(HttpStatusCode.BadRequest, directMethodResponse.HttpStatusCode); } [Fact] public async Task HandleMethodInvocationServerErrorTest() { // Arrange var edgeHubIdentity = Mock.Of<IModuleIdentity>(); var twinManager = Mock.Of<ITwinManager>(); var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>()); var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>(); var twinMessageConverter = Mock.Of<Core.IMessageConverter<Twin>>(); var versionInfo = new VersionInfo("1.0", "1", "123"); var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>(); deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).ThrowsAsync(new Exception("Foo")); var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object); string correlationId = Guid.NewGuid().ToString(); var requestPayload = new { deviceIds = new[] { "d1", "d2" } }; byte[] requestBytes = requestPayload.ToBytes(); var directMethodRequest = new DirectMethodRequest(correlationId, Constants.ServiceIdentityRefreshMethodName, requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); // Act DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest); // Assert Assert.NotNull(directMethodResponse); Assert.Equal(HttpStatusCode.InternalServerError, directMethodResponse.HttpStatusCode); } [Fact] public async Task HandleMethodInvocationInvalidMethodNameTest() { // Arrange var edgeHubIdentity = Mock.Of<IModuleIdentity>(); var twinManager = Mock.Of<ITwinManager>(); var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>()); var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>(); var twinMessageConverter = Mock.Of<Core.IMessageConverter<Twin>>(); var versionInfo = new VersionInfo("1.0", "1", "123"); var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>(); deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).Returns(Task.CompletedTask); var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object); string correlationId = Guid.NewGuid().ToString(); var requestPayload = new { deviceIds = new[] { "d1", "d2" } }; byte[] requestBytes = requestPayload.ToBytes(); var directMethodRequest = new DirectMethodRequest(correlationId, "ping", requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); // Act DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest); // Assert Assert.NotNull(directMethodResponse); Assert.Equal(HttpStatusCode.NotFound, directMethodResponse.HttpStatusCode); } [Fact] public async Task HandleDeviceConnectedDisconnectedEvents() { // Arrange var edgeHubIdentity = Mock.Of<IModuleIdentity>(i => i.Id == "edgeD1/$edgeHub"); var twinManager = Mock.Of<ITwinManager>(); var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>()); var twinCollectionMessageConverter = new TwinCollectionMessageConverter(); var twinMessageConverter = new TwinMessageConverter(); var versionInfo = new VersionInfo("1.0", "1", "123"); var deviceScopeIdentitiesCache = Mock.Of<IDeviceScopeIdentitiesCache>(); var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache); Mock.Get(twinManager).Setup(t => t.UpdateReportedPropertiesAsync(It.IsAny<string>(), It.IsAny<IMessage>())).Returns(Task.CompletedTask); // Act edgeHubConnection.DeviceConnected(this, Mock.Of<IIdentity>(i => i.Id == "d1")); edgeHubConnection.DeviceConnected(this, Mock.Of<IIdentity>(i => i.Id == "edgeD1/$edgeHub")); // Assert await Task.Delay(TimeSpan.FromSeconds(2)); Mock.Get(twinManager).Verify(t => t.UpdateReportedPropertiesAsync(It.IsAny<string>(), It.IsAny<IMessage>()), Times.Once); // Act edgeHubConnection.DeviceDisconnected(this, Mock.Of<IIdentity>(i => i.Id == "d1")); edgeHubConnection.DeviceDisconnected(this, Mock.Of<IIdentity>(i => i.Id == "edgeD1/$edgeHub")); // Assert await Task.Delay(TimeSpan.FromSeconds(2)); Mock.Get(twinManager).Verify(t => t.UpdateReportedPropertiesAsync(It.IsAny<string>(), It.IsAny<IMessage>()), Times.Exactly(2)); } } }
50.525581
204
0.651477
[ "MIT" ]
DaveEM/iotedge
edge-hub/test/Microsoft.Azure.Devices.Edge.Hub.Core.Test/EdgeHubConnectionTest.cs
10,863
C#
using System; using System.Linq.Expressions; using System.Threading.Tasks; using Foundatio.Parsers.ElasticQueries; using Foundatio.Repositories.Elasticsearch.Queries.Builders; using Nest; namespace Foundatio.Repositories.Elasticsearch.Configuration { public interface IIndex : IDisposable { string Name { get; } bool HasMultipleIndexes { get; } IElasticQueryBuilder QueryBuilder { get; } ElasticMappingResolver MappingResolver { get; } ElasticQueryParser QueryParser { get; } IElasticConfiguration Configuration { get; } void ConfigureSettings(ConnectionSettings settings); Task ConfigureAsync(); Task EnsureIndexAsync(object target); Task MaintainAsync(bool includeOptionalTasks = true); Task DeleteAsync(); Task ReindexAsync(Func<int, string, Task> progressCallbackAsync = null); string CreateDocumentId(object document); string[] GetIndexesByQuery(IRepositoryQuery query); string GetIndex(object target); } public interface IIndex<T> : IIndex where T : class { TypeMappingDescriptor<T> ConfigureIndexMapping(TypeMappingDescriptor<T> map); Inferrer Infer { get; } string InferField(Expression<Func<T, object>> objectPath); string InferPropertyName(Expression<Func<T, object>> objectPath); } }
40.205882
85
0.713241
[ "Apache-2.0" ]
FoundatioFx/Foundatio.Repositories
src/Foundatio.Repositories.Elasticsearch/Configuration/IIndex.cs
1,369
C#
namespace Recarro { public class WebConstants { public const string AdministratorRoleName = "Administrator"; public const string AdminEmail = "admin@recarro.com"; public const string AdminUsername = "admin@recarro.com"; public const string AdminPassword = "Password"; } }
28.818182
68
0.678233
[ "MIT" ]
n1claren/ASP.NET-Project-SoftUni
Recarro/WebConstants.cs
319
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MenuButtons : MonoBehaviour { void Start() { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } public void PlayGame() { SceneManager.LoadScene("scene_1"); } public void QuitGame() { Application.Quit(); } }
19.47619
47
0.662592
[ "MIT" ]
Croixwin/low-poly-skyrim
Project Files/Assets/Scripts/UI/MenuButtons.cs
411
C#
using MyStacks.Classes; using System; namespace MultiBracketValidation { public class BracketValidation { public MyStack<char> brackets = new MyStack<char>(); /// <summary> /// Method that returns a boolean if all brackets has an opening and closing match /// </summary> /// <param name="str">string</param> /// <returns>boolean</returns> public bool ValidateBrackets(string str) { foreach (char character in str) { if (character == '(' || character == '{' || character == '[') { brackets.Push(character); } else if (character == ']' || character == '}' || character == ')') { if (character == '}' && brackets.Peek() != '{' || character == ')' && brackets.Peek() != '(' || character == ']' && brackets.Peek() != '[') { return false; } brackets.Pop(); } } return brackets.IsEmpty(); } } }
31.315789
90
0.422689
[ "MIT" ]
JCode1986/data-structure-and-algorithms-dotnet
challenges/MultiBracketValidation/MultiBracketValidation/Classes/MultiBracketValidation.cs
1,190
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.Buffers; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.Json.Tests; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; using Xunit.Sdk; namespace System.Text.Json { internal static class JsonTestHelper { public static string NewtonsoftReturnStringHelper(TextReader reader) { var sb = new StringBuilder(); var json = new JsonTextReader(reader); while (json.Read()) { if (json.Value != null) { // Use InvariantCulture to make sure numbers retain the decimal point '.' sb.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", json.Value); } } return sb.ToString(); } public static string WriteDepthObject(int depth, bool writeComment = false) { var sb = new StringBuilder(); var textWriter = new StringWriter(); var json = new JsonTextWriter(textWriter); json.WriteStartObject(); for (int i = 0; i < depth; i++) { json.WritePropertyName("message" + i); json.WriteStartObject(); } if (writeComment) json.WriteComment("Random comment string"); json.WritePropertyName("message" + depth); json.WriteValue("Hello, World!"); for (int i = 0; i < depth; i++) { json.WriteEndObject(); } json.WriteEndObject(); json.Flush(); return textWriter.ToString(); } public static string WriteDepthArray(int depth, bool writeComment = false) { var sb = new StringBuilder(); var textWriter = new StringWriter(); var json = new JsonTextWriter(textWriter); json.WriteStartArray(); for (int i = 0; i < depth; i++) { json.WriteStartArray(); } if (writeComment) json.WriteComment("Random comment string"); json.WriteValue("Hello, World!"); for (int i = 0; i < depth; i++) { json.WriteEndArray(); } json.WriteEndArray(); json.Flush(); return textWriter.ToString(); } public static string WriteDepthObjectWithArray(int depth, bool writeComment = false) { var sb = new StringBuilder(); var textWriter = new StringWriter(); var json = new JsonTextWriter(textWriter); json.WriteStartObject(); for (int i = 0; i < depth; i++) { json.WritePropertyName("message" + i); json.WriteStartObject(); } if (writeComment) json.WriteComment("Random comment string"); json.WritePropertyName("message" + depth); json.WriteStartArray(); json.WriteValue("string1"); json.WriteValue("string2"); json.WriteEndArray(); json.WritePropertyName("address"); json.WriteStartObject(); json.WritePropertyName("street"); json.WriteValue("1 Microsoft Way"); json.WritePropertyName("city"); json.WriteValue("Redmond"); json.WritePropertyName("zip"); json.WriteValue(98052); json.WriteEndObject(); for (int i = 0; i < depth; i++) { json.WriteEndObject(); } json.WriteEndObject(); json.Flush(); return textWriter.ToString(); } public static byte[] ReturnBytesHelper(byte[] data, out int length, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow, int maxDepth = 64) { var state = new JsonReaderState(new JsonReaderOptions { CommentHandling = commentHandling, MaxDepth = maxDepth }); var reader = new Utf8JsonReader(data, true, state); return ReaderLoop(data.Length, out length, ref reader); } public static byte[] SequenceReturnBytesHelper(byte[] data, out int length, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow, int maxDepth = 64) { ReadOnlySequence<byte> sequence = CreateSegments(data); var state = new JsonReaderState(new JsonReaderOptions { CommentHandling = commentHandling, MaxDepth = maxDepth }); var reader = new Utf8JsonReader(sequence, true, state); return ReaderLoop(data.Length, out length, ref reader); } public static ReadOnlySequence<byte> CreateSegments(byte[] data) { ReadOnlyMemory<byte> dataMemory = data; var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, data.Length / 2)); ReadOnlyMemory<byte> secondMem = dataMemory.Slice(data.Length / 2); BufferSegment<byte> secondSegment = firstSegment.Append(secondMem); return new ReadOnlySequence<byte>(firstSegment, 0, secondSegment, secondMem.Length); } public static ReadOnlySequence<byte> GetSequence(byte[] _dataUtf8, int segmentSize) { int numberOfSegments = _dataUtf8.Length / segmentSize + 1; byte[][] buffers = new byte[numberOfSegments][]; for (int j = 0; j < numberOfSegments - 1; j++) { buffers[j] = new byte[segmentSize]; Array.Copy(_dataUtf8, j * segmentSize, buffers[j], 0, segmentSize); } int remaining = _dataUtf8.Length % segmentSize; buffers[numberOfSegments - 1] = new byte[remaining]; Array.Copy(_dataUtf8, _dataUtf8.Length - remaining, buffers[numberOfSegments - 1], 0, remaining); return BufferFactory.Create(buffers); } public static List<ReadOnlySequence<byte>> GetSequences(ReadOnlyMemory<byte> dataMemory) { var sequences = new List<ReadOnlySequence<byte>> { new ReadOnlySequence<byte>(dataMemory) }; for (int i = 0; i < dataMemory.Length; i++) { var firstSegment = new BufferSegment<byte>(dataMemory.Slice(0, i)); ReadOnlyMemory<byte> secondMem = dataMemory.Slice(i); BufferSegment<byte> secondSegment = firstSegment.Append(secondMem); var sequence = new ReadOnlySequence<byte>(firstSegment, 0, secondSegment, secondMem.Length); sequences.Add(sequence); } return sequences; } internal static ReadOnlySequence<byte> SegmentInto(ReadOnlyMemory<byte> data, int segmentCount) { if (segmentCount < 2) throw new ArgumentOutOfRangeException(nameof(segmentCount)); int perSegment = data.Length / segmentCount; BufferSegment<byte> first; if (perSegment == 0 && data.Length > 0) { first = new BufferSegment<byte>(data.Slice(0, 1)); data = data.Slice(1); } else { first = new BufferSegment<byte>(data.Slice(0, perSegment)); data = data.Slice(perSegment); } BufferSegment<byte> last = first; segmentCount--; while (segmentCount > 1) { perSegment = data.Length / segmentCount; last = last.Append(data.Slice(0, perSegment)); data = data.Slice(perSegment); segmentCount--; } last = last.Append(data); return new ReadOnlySequence<byte>(first, 0, last, data.Length); } public static object ReturnObjectHelper(byte[] data, JsonCommentHandling commentHandling = JsonCommentHandling.Disallow) { var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = commentHandling }); var reader = new Utf8JsonReader(data, true, state); return ReaderLoop(ref reader); } public static string ObjectToString(object jsonValues) { string s = ""; if (jsonValues is List<object> jsonList) s = ListToString(jsonList); else if (jsonValues is Dictionary<string, object> jsonDictionary) s = DictionaryToString(jsonDictionary); return s; } public static string DictionaryToString(Dictionary<string, object> dictionary) { var builder = new StringBuilder(); foreach (KeyValuePair<string, object> entry in dictionary) { if (entry.Value is Dictionary<string, object> nestedDictionary) builder.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", entry.Key).Append(DictionaryToString(nestedDictionary)); else if (entry.Value is List<object> nestedList) builder.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", entry.Key).Append(ListToString(nestedList)); else builder.AppendFormat(CultureInfo.InvariantCulture, "{0}, {1}, ", entry.Key, entry.Value); } return builder.ToString(); } public static string ListToString(List<object> list) { var builder = new StringBuilder(); foreach (object entry in list) { if (entry is Dictionary<string, object> nestedDictionary) builder.Append(DictionaryToString(nestedDictionary)); else if (entry is List<object> nestedList) builder.Append(ListToString(nestedList)); else builder.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", entry); } return builder.ToString(); } private static JsonTokenType MapTokenType(JsonToken token) { switch (token) { case JsonToken.None: return JsonTokenType.None; case JsonToken.StartObject: return JsonTokenType.StartObject; case JsonToken.StartArray: return JsonTokenType.StartArray; case JsonToken.PropertyName: return JsonTokenType.PropertyName; case JsonToken.Comment: return JsonTokenType.Comment; case JsonToken.Integer: case JsonToken.Float: return JsonTokenType.Number; case JsonToken.String: return JsonTokenType.String; case JsonToken.Boolean: return JsonTokenType.True; case JsonToken.Null: return JsonTokenType.Null; case JsonToken.EndObject: return JsonTokenType.EndObject; case JsonToken.EndArray: return JsonTokenType.EndArray; case JsonToken.StartConstructor: case JsonToken.EndConstructor: case JsonToken.Date: case JsonToken.Bytes: case JsonToken.Undefined: case JsonToken.Raw: default: throw new InvalidOperationException(); } } public static string InsertCommentsEverywhere(string jsonString) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; var newtonsoft = new JsonTextReader(new StringReader(jsonString)); writer.WriteComment("comment"); while (newtonsoft.Read()) { writer.WriteToken(newtonsoft, writeChildren: false); writer.WriteComment("comment"); } writer.WriteComment("comment"); } return sb.ToString(); } public static List<JsonTokenType> GetTokenTypes(string jsonString) { var newtonsoft = new JsonTextReader(new StringReader(jsonString)); int totalReads = 0; while (newtonsoft.Read()) { totalReads++; } var expectedTokenTypes = new List<JsonTokenType>(); for (int i = 0; i < totalReads; i++) { newtonsoft = new JsonTextReader(new StringReader(jsonString)); for (int j = 0; j < i; j++) { Assert.True(newtonsoft.Read()); } newtonsoft.Skip(); expectedTokenTypes.Add(MapTokenType(newtonsoft.TokenType)); } return expectedTokenTypes; } public static byte[] ReaderLoop(int inpuDataLength, out int length, ref Utf8JsonReader json) { byte[] outputArray = new byte[inpuDataLength]; Span<byte> destination = outputArray; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan<byte> valueSpan = json.HasValueSequence ? json.ValueSequence.ToArray() : json.ValueSpan; if (json.HasValueSequence) { Assert.True(json.ValueSpan == default); if ((tokenType != JsonTokenType.String && tokenType != JsonTokenType.PropertyName) || json.GetString().Length != 0) { // Empty strings could still make this true, i.e. "" Assert.False(json.ValueSequence.IsEmpty); } } else { Assert.True(json.ValueSequence.IsEmpty); if ((tokenType != JsonTokenType.String && tokenType != JsonTokenType.PropertyName) || json.GetString().Length != 0) { // Empty strings could still make this true, i.e. "" Assert.False(json.ValueSpan == default); } } switch (tokenType) { case JsonTokenType.PropertyName: valueSpan.CopyTo(destination); destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.Number: case JsonTokenType.String: case JsonTokenType.Comment: valueSpan.CopyTo(destination); destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.True: // Special casing True/False so that the casing matches with Json.NET destination[0] = (byte)'T'; destination[1] = (byte)'r'; destination[2] = (byte)'u'; destination[3] = (byte)'e'; destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.False: destination[0] = (byte)'F'; destination[1] = (byte)'a'; destination[2] = (byte)'l'; destination[3] = (byte)'s'; destination[4] = (byte)'e'; destination[valueSpan.Length] = (byte)','; destination[valueSpan.Length + 1] = (byte)' '; destination = destination.Slice(valueSpan.Length + 2); break; case JsonTokenType.Null: // Special casing Null so that it matches what JSON.NET does break; case JsonTokenType.StartObject: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'{' })); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.EndObject: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'}' })); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.StartArray: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)'[' })); Assert.True(json.ValueSequence.IsEmpty); break; case JsonTokenType.EndArray: Assert.True(json.ValueSpan.SequenceEqual(new byte[] { (byte)']' })); Assert.True(json.ValueSequence.IsEmpty); break; default: break; } } length = outputArray.Length - destination.Length; return outputArray; } public static object ReaderLoop(ref Utf8JsonReader json) { object root = null; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan<byte> valueSpan = json.ValueSpan; switch (tokenType) { case JsonTokenType.True: case JsonTokenType.False: root = valueSpan[0] == 't'; break; case JsonTokenType.Number: json.TryGetDouble(out double valueDouble); root = valueDouble; break; case JsonTokenType.String: string valueString = json.GetString(); root = valueString; break; case JsonTokenType.Null: break; case JsonTokenType.StartObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); root = ReaderDictionaryLoop(ref json); break; case JsonTokenType.StartArray: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); root = ReaderListLoop(ref json); break; case JsonTokenType.EndObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'}' })); break; case JsonTokenType.EndArray: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)']' })); break; case JsonTokenType.None: case JsonTokenType.Comment: default: break; } } return root; } public static Dictionary<string, object> ReaderDictionaryLoop(ref Utf8JsonReader json) { Dictionary<string, object> dictionary = new Dictionary<string, object>(); string key = ""; object value = null; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan<byte> valueSpan = json.ValueSpan; switch (tokenType) { case JsonTokenType.PropertyName: key = json.GetString(); dictionary.Add(key, null); break; case JsonTokenType.True: case JsonTokenType.False: value = valueSpan[0] == 't'; if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.Number: json.TryGetDouble(out double valueDouble); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = valueDouble; } else { dictionary.Add(key, valueDouble); } break; case JsonTokenType.String: string valueString = json.GetString(); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = valueString; } else { dictionary.Add(key, valueString); } break; case JsonTokenType.Null: value = null; if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.StartObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); value = ReaderDictionaryLoop(ref json); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.StartArray: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); value = ReaderListLoop(ref json); if (dictionary.TryGetValue(key, out _)) { dictionary[key] = value; } else { dictionary.Add(key, value); } break; case JsonTokenType.EndObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'}' })); return dictionary; case JsonTokenType.None: case JsonTokenType.Comment: default: break; } } return dictionary; } public static List<object> ReaderListLoop(ref Utf8JsonReader json) { List<object> arrayList = new List<object>(); object value = null; while (json.Read()) { JsonTokenType tokenType = json.TokenType; ReadOnlySpan<byte> valueSpan = json.ValueSpan; switch (tokenType) { case JsonTokenType.True: case JsonTokenType.False: value = valueSpan[0] == 't'; arrayList.Add(value); break; case JsonTokenType.Number: json.TryGetDouble(out double doubleValue); arrayList.Add(doubleValue); break; case JsonTokenType.String: string valueString = json.GetString(); arrayList.Add(valueString); break; case JsonTokenType.Null: value = null; arrayList.Add(value); break; case JsonTokenType.StartObject: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'{' })); value = ReaderDictionaryLoop(ref json); arrayList.Add(value); break; case JsonTokenType.StartArray: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)'[' })); value = ReaderListLoop(ref json); arrayList.Add(value); break; case JsonTokenType.EndArray: Assert.True(valueSpan.SequenceEqual(new byte[] { (byte)']' })); return arrayList; case JsonTokenType.None: case JsonTokenType.Comment: default: break; } } return arrayList; } public static float NextFloat(Random random) { double mantissa = (random.NextDouble() * 2.0) - 1.0; double exponent = Math.Pow(2.0, random.Next(-126, 128)); float value = (float)(mantissa * exponent); return value; } public static double NextDouble(Random random, double minValue, double maxValue) { double value = random.NextDouble() * (maxValue - minValue) + minValue; return value; } public static decimal NextDecimal(Random random, double minValue, double maxValue) { double value = random.NextDouble() * (maxValue - minValue) + minValue; return (decimal)value; } public static string GetCompactString(string jsonString) { using (JsonTextReader jsonReader = new JsonTextReader(new StringReader(jsonString))) { jsonReader.FloatParseHandling = FloatParseHandling.Decimal; JToken jtoken = JToken.ReadFrom(jsonReader); var stringWriter = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(stringWriter)) { jtoken.WriteTo(jsonWriter); return stringWriter.ToString(); } } } public delegate void AssertThrowsActionUtf8JsonReader(Utf8JsonReader json); // Cannot use standard Assert.Throws() when testing Utf8JsonReader - ref structs and closures don't get along. public static void AssertThrows<E>(Utf8JsonReader json, AssertThrowsActionUtf8JsonReader action) where E : Exception { Exception ex; try { action(json); ex = null; } catch (Exception e) { ex = e; } if (ex == null) { throw new ThrowsException(typeof(E)); } if (!(ex is E)) { throw new ThrowsException(typeof(E), ex); } } public delegate void AssertThrowsActionUtf8JsonWriter(ref Utf8JsonWriter writer); public static void AssertThrows<E>( ref Utf8JsonWriter writer, AssertThrowsActionUtf8JsonWriter action) where E : Exception { Exception ex; try { action(ref writer); ex = null; } catch (Exception e) { ex = e; } if (ex == null) { throw new ThrowsException(typeof(E)); } if (ex.GetType() != typeof(E)) { throw new ThrowsException(typeof(E), ex); } } private static readonly Regex s_stripWhitespace = new Regex(@"\s+", RegexOptions.Compiled); public static string StripWhitespace(this string value) => s_stripWhitespace.Replace(value, string.Empty); } }
40.012295
170
0.487931
[ "MIT" ]
Castaneda1914/corefx
src/System.Text.Json/tests/JsonTestHelper.cs
29,291
C#
using DotVVM.Framework.ViewModel; namespace DotvvmWeb.Views.Docs.Controls.businesspack.Window.sample5 { public class ViewModel : DotvvmViewModelBase { public bool IsWindowDisplayed { get; set; } } }
24.333333
67
0.73516
[ "Apache-2.0" ]
Duzij/dotvvm-docs
Controls/businesspack/Window/sample5/ViewModel.cs
219
C#
namespace Cofoundry.Domain.Data { /// <summary> /// Lookup cache used for quickly finding the correct version for a /// specific publish status query e.g. 'Latest', 'Published', /// 'PreferPublished'. These records are generated when pages /// are published or unpublished. /// </summary> public class PagePublishStatusQuery { /// <summary> /// Id of the page this record represents. Forms a key /// with the PublishStatusQueryId. /// </summary> public int PageId { get; set; } /// <summary> /// Numeric representation of the domain PublishStatusQuery enum. /// </summary> public short PublishStatusQueryId { get; set; } /// <summary> /// The id of the version of the page that should be displayed /// for the corresponding PublishStatusQueryId. /// </summary> public int PageVersionId { get; set; } /// <summary> /// Page that this record represents. /// </summary> public virtual Page Page { get; set; } /// <summary> /// The version of the page that should be displayed /// for the corresponding PublishStatusQueryId. /// </summary> public virtual PageVersion PageVersion { get; set; } } }
32.95
73
0.593323
[ "MIT" ]
BearerPipelineTest/cofoundry
src/Cofoundry.Domain/Data/DbContext/Pages/PagePublishStatusQuery.cs
1,318
C#
using System; using System.Text; using System.Security.Cryptography; using Xunit; namespace SKIT.Utility.UnitTests { #if !NETFRAMEWORK public class RsaUtilUnitTests { const string STR_EN = "hello, world."; const string STR_CH = "��ã����硣"; const string RSA_PUBLIC_KEY_1024 = "-----BEGIN PUBLIC KEY-----" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCh5Nk2GLiyQFMIU+h3OEA4UeFb" + "u3dCH5sjd/sLTxxvwjXq7JLqJbt2rCIdzpAXOi4jL+FRGQnHaxUlHUBZsojnCcHv" + "hrz2knV6rXNogt0emL7f7ZMRo8IsQGV8mlKIC9xLnlOQQdRNUssmrROrCG99wpTR" + "RNZjOmLvkcoXdeuaCQIDAQAB" + "-----END PUBLIC KEY-----"; const string RSA_PRIVATE_KEY_1024 = "-----BEGIN RSA PRIVATE KEY-----" + "MIICWwIBAAKBgQCh5Nk2GLiyQFMIU+h3OEA4UeFbu3dCH5sjd/sLTxxvwjXq7JLq" + "Jbt2rCIdzpAXOi4jL+FRGQnHaxUlHUBZsojnCcHvhrz2knV6rXNogt0emL7f7ZMR" + "o8IsQGV8mlKIC9xLnlOQQdRNUssmrROrCG99wpTRRNZjOmLvkcoXdeuaCQIDAQAB" + "AoGAUTcJ1H6QYTOts9bMHsrERLymzir8R9qtLBzrfp/gRxxpigHGLdph8cWmk8dl" + "N5HDRXmmkdV6t2S7xdOnzZen31lcWe0bIzg0SrFiUEOtg3Lwxzw2Pz0dKwg4ZUoo" + "GKpcIU6kEpbC2UkjBV4+2E6P1DXuhdgTyHoUA3ycxOdjCAUCQQCyjTzGPXFoHq5T" + "miJyVd4VXNyCXGU0ZuQayt6nPN8Gd5CcEb2S4kggzPXQcd90FO0kHfZV6+PGTrc2" + "ZUuz5uwPAkEA6B3lmEmiZsJS/decLzWR0T1CXaFGwTjBQbHXJ0RziAfkuy+VwSmh" + "vrW/ipk5xbREr5rKx3jVI2PzVOvLw7NgZwJAbUsvDFnH9WfyZZJPy5TsID97awCL" + "oovozM2phM0p55eAmUfyttp0ND/BqBpMIY49qoH8q5N9FYJRe6Z9tF2B2QJAQBEo" + "cw039xcB4zCk2l713YQEEmXWarSomuJkWWFKZiyPlJ8Ava0pCMOPl8jNKmWkY7fc" + "6ovOgJMw8aqXtm+HVwJAerJeUEDez2djG5pIF6aCV0bP3fhQUq8OQCgGF5Qzo9Cn" + "qvYreGpYKPJGVixAsEPCiLzJRhy1XfFona6VRXIIxw==" + "-----END RSA PRIVATE KEY-----"; const string RSA_PUBLIC_KEY_2048 = "-----BEGIN PUBLIC KEY-----" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwd+PToipWA/p0eyjBJuL" + "es2QMBfB/Bpka02mchPLyQ1NOtDtgGsl3P3WRSDFfeW9vglfQtsgVZQmR5aT2iT4" + "NBST2KuwpO92OpmrDu0hDJb/pPIf7SiaSryq/JyTy6RBmXUG1mQGAAbLkZLRf1RK" + "aftLRdwquqs0fNBbvcWNZb/cMU8OkuPIpDBeMtsylwkt5LY5nQJsEb3kBVbuIVIq" + "gJhByjYRu2VKSc0xadQm3qmPLdU3UFx8A0y19lq6dYI4HYVnbVmkjZtU3n0d/S5R" + "ZEl4ctkg4wV/RrYZjS6nLB3PU0SuxbnNXBBz7DA3yxEYRMGVEBQy6gPFx2D3mzzb" + "kwIDAQAB" + "-----END PUBLIC KEY-----"; const string RSA_PRIVATE_KEY_2048 = "-----BEGIN RSA PRIVATE KEY-----" + "MIIEpQIBAAKCAQEAwd+PToipWA/p0eyjBJuLes2QMBfB/Bpka02mchPLyQ1NOtDt" + "gGsl3P3WRSDFfeW9vglfQtsgVZQmR5aT2iT4NBST2KuwpO92OpmrDu0hDJb/pPIf" + "7SiaSryq/JyTy6RBmXUG1mQGAAbLkZLRf1RKaftLRdwquqs0fNBbvcWNZb/cMU8O" + "kuPIpDBeMtsylwkt5LY5nQJsEb3kBVbuIVIqgJhByjYRu2VKSc0xadQm3qmPLdU3" + "UFx8A0y19lq6dYI4HYVnbVmkjZtU3n0d/S5RZEl4ctkg4wV/RrYZjS6nLB3PU0Su" + "xbnNXBBz7DA3yxEYRMGVEBQy6gPFx2D3mzzbkwIDAQABAoIBAQCYZuNCew+UGD5Y" + "NUsYziVhDcLw61wkj6Ks70eOmZ0ymPBC8gYhUxlalXggs1hMVZNIlhl6dsL+Qw2s" + "bOQhMbqjRiHKy3x6y3sHKdFcVHAMc47W3TbXuXlAkvtexL8x8BdZSLNtSQemcbEI" + "6H8jNuGgWlibvC0ivH7wNuJHVcqHVmLBgXi6dmm9bMRup8aMp+ROv4k2CULcLgsX" + "D1o5GWF4LoRKcVaHP9NMNSsK471w7P/5CN/X9JJFn4io5QRZDZlbNuUPGPLbkw7c" + "mbDUl5jEQC1VfuaakIg4sJFu33ZMxv9rN0jyybgcxkBzv5VNuSNg9urlI8u4ddZN" + "rVp1rrwxAoGBAN8iS86o/iL5ryUJQlHaMdWGGhnuA3lxD6AMt1Y2n8n4z/lUvxgh" + "QFdhlQWw8eVO+3fqc5gf5ROS6IM1/Vi4x8Hbij3OiIvSz+8vaPeXxKWnGR4YwdxE" + "WAPO9pewfYiOJA5RjYNltzvaujdCNlvlKVjRIkDhZbdBS/xjwlYa2S/NAoGBAN5t" + "7pjFqAx35YVkVNMUkGu++2mB2A4KSk9a3vkuMIfbuyRthqIF7FPqGG6B0mck/ZAS" + "nCnxgWKGWJQ5UK83NTo3cf4/8ivgzISfmiF0lh41dQnVaeyW2cDe36WkhCxC2uUF" + "niTgAv3CqMnB9PbQeeUHGtozHtxbcKoiu/9u1RjfAoGBAIbGb2WPO5mimMDVG+LW" + "2VzwmBlrY1vaB6cTpzWC3vceu3gNUTNg+j0Nava6DxIDp+6hhVqwgSxWguymErWh" + "Pr8APTrh4iYampANYeiTGis4h/pe19GU0ljSjK3I47o0qOChL8nbCVc04V95Nd5B" + "x7ym7Xqk6kxLO3tiQkLCCsdNAoGBALeB8Ohfog5vWJAdv5HKFICgNyHLuymSOc6Q" + "hQcFoYpksVgTeJDx3BE7QF7jgmgQb5XOlMJR+lIDzs6zHqsAHEzkc4q0zSKAO5tr" + "ZakWW8eeiOnNBa/ooMxr1A3/1gACRD/Qy7FWk4EyeTjDaUu7oeVfYDsHE/3u/tuO" + "/pV1ph/3AoGANqGpRZW8xDiqdukh5LKAak0DymSyayVZhvtW0EUQ+cAcENF04CbH" + "JzBcPIf/aWjhEoboHWuLJadCKiN6HackNktN9Ixo44msdbtCw+HutNBKiGPhT62L" + "dofmElg6VRpoCXH0lJgBLONw2QyELi3mVUfdKu+RqEK2qb3H4czPtPs=" + "-----END RSA PRIVATE KEY-----"; [Fact] public void EncryptAndDecryptTest() { string cipher; cipher = RsaUtil.Encrypt(STR_EN, RSA_PUBLIC_KEY_1024); Assert.NotEmpty(cipher); Assert.Equal(STR_EN, RsaUtil.Decrypt(cipher, RSA_PRIVATE_KEY_1024)); Assert.Equal(STR_EN, RsaUtil.Decrypt("QccbdMDHAZflCKBDrKVH/YH4Nx6XiSNUAbscDppOsIheIM1kTa3+GDnXPjM3l7xXOOHpN3f2JkjX/dfUd5SPdNqwESepO28GRzVq4j4QIg7sKQ2a1NV4jy1Zfz+ssvvyJFDk9ycnb7d0pRS9UwqO/pbgP6YS+2MQrY2r4n7gJEA=", RSA_PRIVATE_KEY_1024)); cipher = RsaUtil.Encrypt(STR_CH, RSA_PUBLIC_KEY_1024); Assert.NotEmpty(cipher); Assert.Equal(STR_CH, RsaUtil.Decrypt(cipher, RSA_PRIVATE_KEY_1024)); Assert.Equal(STR_CH, RsaUtil.Decrypt("OcLlLFAlMCyrgeOsqUaWIsYmBWi5EyWTU1ZnS94gkxYOGdVdkmbmJOB6/sGOfjWmhqg/5eK7VHGa4kpJAZgw5QoDglLiNlKZjCSS7BcliuZEFhhlln6h6UKYQECflgcm73OtbozgOpFG7oLhiaer1ONFMO6az0o4WSp6qBcqTck=", RSA_PRIVATE_KEY_1024)); cipher = RsaUtil.Encrypt(STR_EN, RSA_PUBLIC_KEY_2048); Assert.NotEmpty(cipher); Assert.Equal(STR_EN, RsaUtil.Decrypt(cipher, RSA_PRIVATE_KEY_2048)); cipher = RsaUtil.Encrypt(STR_CH, RSA_PUBLIC_KEY_2048); Assert.NotEmpty(cipher); Assert.Equal(STR_CH, RsaUtil.Decrypt(cipher, RSA_PRIVATE_KEY_2048)); } [Fact] public void OversizeTest() { /** * REF: https://github.com/stulzq/DotnetCore.RSA/issues/2 * https://www.cnblogs.com/CreateMyself/p/9853736.html */ string data = CaptchaUtil.GetCaptcha(4096); string cipher = RsaUtil.Encrypt(data, RSA_PUBLIC_KEY_1024); string sign = RsaUtil.Sign(data, RSA_PRIVATE_KEY_1024); Assert.NotEmpty(cipher); Assert.NotEmpty(sign); Assert.Equal(data, RsaUtil.Decrypt(cipher, RSA_PRIVATE_KEY_1024)); Assert.True(RsaUtil.Verify(data, sign, RSA_PUBLIC_KEY_1024)); } [Fact] public void SignAndVerifyTest() { string sign; sign = RsaUtil.Sign(STR_EN, RSA_PRIVATE_KEY_1024); Assert.NotEmpty(sign); Assert.True(RsaUtil.Verify(STR_EN, sign, RSA_PUBLIC_KEY_1024)); sign = RsaUtil.Sign(STR_CH, RSA_PRIVATE_KEY_1024); Assert.NotEmpty(sign); Assert.True(RsaUtil.Verify(STR_CH, sign, RSA_PUBLIC_KEY_1024)); sign = RsaUtil.Sign(STR_EN, RSA_PRIVATE_KEY_2048); Assert.NotEmpty(sign); Assert.True(RsaUtil.Verify(STR_EN, sign, RSA_PUBLIC_KEY_2048)); sign = RsaUtil.Sign(STR_CH, RSA_PRIVATE_KEY_2048); Assert.NotEmpty(sign); Assert.True(RsaUtil.Verify(STR_CH, sign, RSA_PUBLIC_KEY_2048)); } } #endif }
64.385185
248
0.599977
[ "MIT" ]
fudiwei/DotNetCore.SKIT.Utility
test/SKIT.Utility.UnitTests/RsaUtilUnitTests.cs
8,707
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace WebApIQuartz.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
22.195652
57
0.511263
[ "MIT" ]
wanglong/NetCore22WebApIQuartz
WebApIQuartz/Controllers/ValuesController.cs
1,023
C#
using Akinator.Api.Net.Enumerations; using Akinator.Api.Net.Model; namespace Akinator.Api.Net.Utils { /// <summary> /// Checks, whether or not Akinator is ready to guess /// </summary> public static class GuessDueChecker { public static bool GuessIsDue(AkinatorQuestion currentQuestion, int lastGuessTakenAtStep, Platform platform = Platform.Android) { if (currentQuestion is null) { return false; } switch (platform) { default: case Platform.Android: { var stepsTakenSinceLastGuess = currentQuestion.Step - lastGuessTakenAtStep; if (NoMoreQuestions() || currentQuestion.Step >= 80) { return true; } if (stepsTakenSinceLastGuess < 5) { return false; } if (currentQuestion.Step <= 25) { return !(currentQuestion.Progression <= 97.0f); } if (currentQuestion.Progression <= 80.0f && stepsTakenSinceLastGuess < 30) { return false; } return 80 - currentQuestion.Step > 5; } case Platform.AndroidModified: { var step = currentQuestion.Step; var variance = step - lastGuessTakenAtStep; var progress = currentQuestion.Progression; if (NoMoreQuestions() || step == 80) { return true; } if (variance < 5) { return false; } if (step <= 25) { if (progress > 97.0) { return true; } } else if (progress >= 80.0 || variance >= 30) { if (variance >= 10) { return true; } } return false; } case Platform.WindowsPhone: { return currentQuestion.Step >= 79 || (currentQuestion.Step - lastGuessTakenAtStep >= 5 && (currentQuestion.Progression >= 97f || currentQuestion.Step - lastGuessTakenAtStep == 25) && currentQuestion.Step != 75); } } } private static bool NoMoreQuestions() { //todo return false; } } }
34.844444
235
0.370536
[ "MIT" ]
Forevka/Akinator.Api.Net
Akinator.Api.Net/Utils/GuessDueChecker.cs
3,138
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 06:01:18 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using token = go.go.token_package; using go; #nullable enable namespace go { namespace golang.org { namespace x { namespace tools { namespace go { public static partial class analysis_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct SuggestedFix { // Constructors public SuggestedFix(NilType _) { this.Message = default; this.TextEdits = default; } public SuggestedFix(@string Message = default, slice<TextEdit> TextEdits = default) { this.Message = Message; this.TextEdits = TextEdits; } // Enable comparisons between nil and SuggestedFix struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(SuggestedFix value, NilType nil) => value.Equals(default(SuggestedFix)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(SuggestedFix value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, SuggestedFix value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, SuggestedFix value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator SuggestedFix(NilType nil) => default(SuggestedFix); } [GeneratedCode("go2cs", "0.1.0.0")] public static SuggestedFix SuggestedFix_cast(dynamic value) { return new SuggestedFix(value.Message, value.TextEdits); } } }}}}}
34.147059
115
0.605943
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/diagnostic_SuggestedFixStruct.cs
2,322
C#
namespace CustomerService.MessageQueue.Helpers { public static class Constants { public static class MessageQueue { public const string BookingExchange = "booking-exchange"; public const string OrderExchange = "order-exchange"; } } }
26.727273
69
0.639456
[ "MIT" ]
Exoft/KnowledgeSharing.Microservices
src/CustomerService/CustomerService.MessageQueue/Helpers/Constants.cs
296
C#
/* * Hydrogen Nucleus API * * The Hydrogen Nucleus API * * OpenAPI spec version: 1.9.4 * Contact: info@hydrogenplatform.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = Nucleus.Client.SwaggerDateConverter; namespace Nucleus.ModelEntity { /// <summary> /// SecurityExclusion Object /// </summary> [DataContract] public partial class SecurityExclusion : IEquatable<SecurityExclusion>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="SecurityExclusion" /> class. /// </summary> [JsonConstructorAttribute] protected SecurityExclusion() { } /// <summary> /// Initializes a new instance of the <see cref="SecurityExclusion" /> class. /// </summary> /// <param name="accountId">account id.</param> /// <param name="clientId">Client id (required).</param> /// <param name="createDate">createDate.</param> /// <param name="id">id.</param> /// <param name="isRestrictBuy">restrict buy (required).</param> /// <param name="isRestrictSell">restrict sell (required).</param> /// <param name="metadata">metadata.</param> /// <param name="portfolioId">portfolio id.</param> /// <param name="secondaryId">secondaryId.</param> /// <param name="securityId">Security id (required).</param> /// <param name="updateDate">updateDate.</param> public SecurityExclusion(Guid? accountId = default(Guid?), Guid? clientId = default(Guid?), DateTime? createDate = default(DateTime?), Guid? id = default(Guid?), bool? isRestrictBuy = default(bool?), bool? isRestrictSell = default(bool?), Dictionary<string, string> metadata = default(Dictionary<string, string>), Guid? portfolioId = default(Guid?), string secondaryId = default(string), Guid? securityId = default(Guid?), DateTime? updateDate = default(DateTime?)) { // to ensure "clientId" is required (not null) if (clientId == null) { throw new InvalidDataException("clientId is a required property for SecurityExclusion and cannot be null"); } else { this.ClientId = clientId; } // to ensure "isRestrictBuy" is required (not null) if (isRestrictBuy == null) { throw new InvalidDataException("isRestrictBuy is a required property for SecurityExclusion and cannot be null"); } else { this.IsRestrictBuy = isRestrictBuy; } // to ensure "isRestrictSell" is required (not null) if (isRestrictSell == null) { throw new InvalidDataException("isRestrictSell is a required property for SecurityExclusion and cannot be null"); } else { this.IsRestrictSell = isRestrictSell; } // to ensure "securityId" is required (not null) if (securityId == null) { throw new InvalidDataException("securityId is a required property for SecurityExclusion and cannot be null"); } else { this.SecurityId = securityId; } this.AccountId = accountId; this.CreateDate = createDate; this.Id = id; this.Metadata = metadata; this.PortfolioId = portfolioId; this.SecondaryId = secondaryId; this.UpdateDate = updateDate; } /// <summary> /// account id /// </summary> /// <value>account id</value> [DataMember(Name="account_id", EmitDefaultValue=false)] public Guid? AccountId { get; set; } /// <summary> /// Client id /// </summary> /// <value>Client id</value> [DataMember(Name="client_id", EmitDefaultValue=false)] public Guid? ClientId { get; set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="create_date", EmitDefaultValue=false)] public DateTime? CreateDate { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public Guid? Id { get; set; } /// <summary> /// restrict buy /// </summary> /// <value>restrict buy</value> [DataMember(Name="is_restrict_buy", EmitDefaultValue=false)] public bool? IsRestrictBuy { get; set; } /// <summary> /// restrict sell /// </summary> /// <value>restrict sell</value> [DataMember(Name="is_restrict_sell", EmitDefaultValue=false)] public bool? IsRestrictSell { get; set; } /// <summary> /// Gets or Sets Metadata /// </summary> [DataMember(Name="metadata", EmitDefaultValue=false)] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// portfolio id /// </summary> /// <value>portfolio id</value> [DataMember(Name="portfolio_id", EmitDefaultValue=false)] public Guid? PortfolioId { get; set; } /// <summary> /// Gets or Sets SecondaryId /// </summary> [DataMember(Name="secondary_id", EmitDefaultValue=false)] public string SecondaryId { get; set; } /// <summary> /// Security id /// </summary> /// <value>Security id</value> [DataMember(Name="security_id", EmitDefaultValue=false)] public Guid? SecurityId { get; set; } /// <summary> /// Gets or Sets UpdateDate /// </summary> [DataMember(Name="update_date", EmitDefaultValue=false)] public DateTime? UpdateDate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SecurityExclusion {\n"); sb.Append(" AccountId: ").Append(AccountId).Append("\n"); sb.Append(" ClientId: ").Append(ClientId).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" IsRestrictBuy: ").Append(IsRestrictBuy).Append("\n"); sb.Append(" IsRestrictSell: ").Append(IsRestrictSell).Append("\n"); sb.Append(" Metadata: ").Append(Metadata).Append("\n"); sb.Append(" PortfolioId: ").Append(PortfolioId).Append("\n"); sb.Append(" SecondaryId: ").Append(SecondaryId).Append("\n"); sb.Append(" SecurityId: ").Append(SecurityId).Append("\n"); sb.Append(" UpdateDate: ").Append(UpdateDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SecurityExclusion); } /// <summary> /// Returns true if SecurityExclusion instances are equal /// </summary> /// <param name="input">Instance of SecurityExclusion to be compared</param> /// <returns>Boolean</returns> public bool Equals(SecurityExclusion input) { if (input == null) return false; return ( this.AccountId == input.AccountId || (this.AccountId != null && this.AccountId.Equals(input.AccountId)) ) && ( this.ClientId == input.ClientId || (this.ClientId != null && this.ClientId.Equals(input.ClientId)) ) && ( this.CreateDate == input.CreateDate || (this.CreateDate != null && this.CreateDate.Equals(input.CreateDate)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.IsRestrictBuy == input.IsRestrictBuy || (this.IsRestrictBuy != null && this.IsRestrictBuy.Equals(input.IsRestrictBuy)) ) && ( this.IsRestrictSell == input.IsRestrictSell || (this.IsRestrictSell != null && this.IsRestrictSell.Equals(input.IsRestrictSell)) ) && ( this.Metadata == input.Metadata || this.Metadata != null && this.Metadata.SequenceEqual(input.Metadata) ) && ( this.PortfolioId == input.PortfolioId || (this.PortfolioId != null && this.PortfolioId.Equals(input.PortfolioId)) ) && ( this.SecondaryId == input.SecondaryId || (this.SecondaryId != null && this.SecondaryId.Equals(input.SecondaryId)) ) && ( this.SecurityId == input.SecurityId || (this.SecurityId != null && this.SecurityId.Equals(input.SecurityId)) ) && ( this.UpdateDate == input.UpdateDate || (this.UpdateDate != null && this.UpdateDate.Equals(input.UpdateDate)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AccountId != null) hashCode = hashCode * 59 + this.AccountId.GetHashCode(); if (this.ClientId != null) hashCode = hashCode * 59 + this.ClientId.GetHashCode(); if (this.CreateDate != null) hashCode = hashCode * 59 + this.CreateDate.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.IsRestrictBuy != null) hashCode = hashCode * 59 + this.IsRestrictBuy.GetHashCode(); if (this.IsRestrictSell != null) hashCode = hashCode * 59 + this.IsRestrictSell.GetHashCode(); if (this.Metadata != null) hashCode = hashCode * 59 + this.Metadata.GetHashCode(); if (this.PortfolioId != null) hashCode = hashCode * 59 + this.PortfolioId.GetHashCode(); if (this.SecondaryId != null) hashCode = hashCode * 59 + this.SecondaryId.GetHashCode(); if (this.SecurityId != null) hashCode = hashCode * 59 + this.SecurityId.GetHashCode(); if (this.UpdateDate != null) hashCode = hashCode * 59 + this.UpdateDate.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
39.320122
473
0.531829
[ "Apache-2.0" ]
ShekharPaatni/SDK
atom/nucleus/csharp/src/Nucleus/Model/SecurityExclusion.cs
12,897
C#
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace VisualProgrammer.WPF.Util { public static class DependencyObjectUtils { /// <summary> /// Finds an ancestor (that is of the target type) for this dependency object. /// Returns null if no ancestor of this type exists. /// </summary> /// <typeparam name="T">The type of ancestor to search for.</typeparam> public static T AncestorOfType<T>(DependencyObject self) where T : DependencyObject { var obj = self; do { obj = VisualTreeHelper.GetParent(obj); if (obj is T tObj) return tObj; } while (obj != null); return null; } /// <summary> /// Performs a breadth-first search through all children of the start element to find a child of a specific type matching a predicate. /// Returns null if no child matching the type parameter and predicate are found. /// </summary> /// <typeparam name="T">The type of element to search for.</typeparam> /// <param name="start">The element to start the search at.</param> /// <param name="predicate">A function that will be invoked on any found <typeparamref name="T"/> children. /// If the invocation returns true, this child will be returned otherwise the search will continue.</param> public static T ChildOfType<T>(DependencyObject start, Func<T, bool> predicate) where T : DependencyObject { var itemsToSearch = new Queue<DependencyObject>(); itemsToSearch.Enqueue(start); while (itemsToSearch.Count > 0) { var item = itemsToSearch.Dequeue(); var childCount = VisualTreeHelper.GetChildrenCount(item); for (var i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(item, i); if (child is T tChild && predicate(tChild)) return tChild; itemsToSearch.Enqueue(child); } } return null; } } }
35.903846
136
0.697375
[ "MIT" ]
Wibble199/VisualProgrammer
VisualProgrammer.WPF/Util/DependencyObjectUtils.cs
1,869
C#
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using CpuSkinningDataTypes; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; namespace Pax4.Core { [DataContract] [KnownType(typeof(Pax4ObjectSceneryPartModelSkinned))] public class Pax4ObjectSceneryPartModelSkinned : Pax4ObjectSceneryPartModel { public AnimationPlayer _currentAnimationPlayer = null; public AnimationClip _currentAnimationClip = null; public List<AnimationClip> _animationClip = new List<AnimationClip>(); public Pax4ObjectSceneryPartModelSkinned(String p_name, Pax4Object p_parent0) : base(p_name, p_parent0) { } public override void Update(GameTime gameTime) { base.Update(gameTime); if (_currentAnimationPlayer != null) _currentAnimationPlayer.Update(gameTime.ElapsedGameTime, Matrix.Identity); } public override void Draw(GameTime gameTime) { if (_isOutsideView) return; if (_currentAnimationPlayer == null) return; foreach (ModelMesh mesh in _modelState._model.Meshes) { foreach (SkinnedEffect effect in mesh.Effects) { effect.SetBoneTransforms(_currentAnimationPlayer.SkinTransforms); effect.World = _matWorld; effect.View = Pax4Camera._current._matView; } mesh.Draw(); } } public override void SetModel(String p_modelName = "") { base.SetModel(p_modelName); SkinningData skinningData = (SkinningData)_modelState._model.Tag; _currentAnimationPlayer = new AnimationPlayer(skinningData); foreach (KeyValuePair<String, AnimationClip> kvp in skinningData.AnimationClips) _animationClip.Add(kvp.Value); _currentAnimationClip = _animationClip[0]; _currentAnimationClip.Ini(skinningData); } public override void Enable() { base.Enable(); if (_currentAnimationPlayer == null) return; _currentAnimationPlayer.EnterClip(ref _currentAnimationClip); } public virtual void SetAnimationtVelocityFactor(float p_animationVelocityFactor = 1.0f) { if (_currentAnimationPlayer == null) return; _currentAnimationClip.SetVelocityFactor(p_animationVelocityFactor); } public virtual void EnterClip(AnimationClip p_clip, float p_blendDuration = 0.3f) { if (_currentAnimationPlayer == null) return; //_currentAnimationPlayer.EnterClip(); } #region serialize public override MemoryStream Serialize(bool p_volatile = false) { return Serialize(this.GetType(), p_volatile); } #endregion } }
29.764151
95
0.602219
[ "MIT" ]
stark7/LavaAndIce
Pax4.Core/Pax/Pax4ObjectSceneryPartModelSkinned.cs
3,157
C#
using uVK.ViewModel; namespace uVK { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); DataContext = new WindowViewModel(); } } }
19.1875
49
0.560261
[ "MIT" ]
h10ne/uVK
uVK/MainWindow.xaml.cs
332
C#
using Hcm.Database.Models; namespace Hcm.Database.Repositories { public class SallaryRepository : Repository<Sallary>, ISallaryRepository { public SallaryRepository(DatabaseContext context) : base(context) { } } }
18.928571
76
0.65283
[ "Apache-2.0" ]
arioanindito/ario_hcm
Hcm.Database/Repositories/SallaryRepository.cs
267
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.ResourceManager.Network { /// <summary> Deletes the specified Firewall Policy. </summary> public partial class FirewallPoliciesDeleteOperation : Operation<Response>, IOperationSource<Response> { private readonly ArmOperationHelpers<Response> _operation; internal FirewallPoliciesDeleteOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new ArmOperationHelpers<Response>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "FirewallPoliciesDeleteOperation"); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override Response Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<Response>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<Response>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); Response IOperationSource<Response>.CreateResult(Response response, CancellationToken cancellationToken) { return response; } async ValueTask<Response> IOperationSource<Response>.CreateResultAsync(Response response, CancellationToken cancellationToken) { return await new ValueTask<Response>(response).ConfigureAwait(false); } } }
41.174603
223
0.726291
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/FirewallPoliciesDeleteOperation.cs
2,594
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.ComponentModel; using Pulumi; namespace Pulumi.AzureNative.Authorization.V20151001Preview { /// <summary> /// The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. /// </summary> [EnumType] public readonly struct PolicyType : IEquatable<PolicyType> { private readonly string _value; private PolicyType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static PolicyType NotSpecified { get; } = new PolicyType("NotSpecified"); public static PolicyType BuiltIn { get; } = new PolicyType("BuiltIn"); public static PolicyType Custom { get; } = new PolicyType("Custom"); public static bool operator ==(PolicyType left, PolicyType right) => left.Equals(right); public static bool operator !=(PolicyType left, PolicyType right) => !left.Equals(right); public static explicit operator string(PolicyType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is PolicyType other && Equals(other); public bool Equals(PolicyType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
39.190476
110
0.681652
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Authorization/V20151001Preview/Enums.cs
1,646
C#
using FluentAssertions; using Moq; using RockLib.Encryption.Async; using System.Text; using System.Threading; using Xunit; namespace RockLib.Encryption.Tests.Async { public class SynchronousAsyncCryptoTests { private Mock<ICrypto> _cryptoMock; private IEncryptor _encryptor; private IDecryptor _decryptor; private void Setup(string cryptoId) { _cryptoMock = new Mock<ICrypto>(); _encryptor = new Mock<IEncryptor>().Object; _decryptor = new Mock<IDecryptor>().Object; _cryptoMock.Setup(f => f.CanEncrypt(cryptoId)).Returns(true); _cryptoMock.Setup(f => f.CanEncrypt(It.Is<string>(s => s != cryptoId))).Returns(false); _cryptoMock.Setup(f => f.Encrypt(It.IsAny<string>(), It.IsAny<string>())).Returns($"EncryptedString : {cryptoId}"); _cryptoMock.Setup(f => f.Encrypt(It.IsAny<byte[]>(), It.IsAny<string>())).Returns(Encoding.UTF8.GetBytes(cryptoId)); _cryptoMock.Setup(f => f.GetEncryptor(cryptoId)).Returns(_encryptor); _cryptoMock.Setup(f => f.CanDecrypt(cryptoId)).Returns(true); _cryptoMock.Setup(f => f.CanDecrypt(It.Is<string>(s => s != cryptoId))).Returns(false); _cryptoMock.Setup(f => f.Decrypt(It.IsAny<string>(), It.IsAny<string>())).Returns($"DecryptedString : {cryptoId}"); _cryptoMock.Setup(f => f.Decrypt(It.IsAny<byte[]>(), It.IsAny<string>())).Returns(Encoding.UTF8.GetBytes(cryptoId)); _cryptoMock.Setup(f => f.GetDecryptor(cryptoId)).Returns(_decryptor); } [Fact] public void Crypto_IsTheSameInstancePassedToTheConstructor() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); asyncCrypto.Crypto.Should().BeSameAs(_cryptoMock.Object); } [Fact] public void EncryptAsync_string_ReturnsACompletedTask() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encryptTask = asyncCrypto.EncryptAsync("stuff", "foo", default(CancellationToken)); encryptTask.IsCompleted.Should().BeTrue(); } [Fact] public void EncryptAsync_string_ReturnsTheResultReturnedByCryptoEncrypt() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encrypted = asyncCrypto.EncryptAsync("stuff", "foo", default(CancellationToken)).Result; encrypted.Should().Be("EncryptedString : foo"); } [Fact] public void EncryptAsync_bytearray_ReturnsACompletedTask() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encryptTask = asyncCrypto.EncryptAsync(new byte[0], "foo", default(CancellationToken)); encryptTask.IsCompleted.Should().BeTrue(); } [Fact] public void EncryptAsync_bytearray_ReturnsTheResultReturnedByCryptoEncrypt() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encrypted = asyncCrypto.EncryptAsync(new byte[0], "foo", default(CancellationToken)).Result; encrypted.Should().BeEquivalentTo(Encoding.UTF8.GetBytes("foo")); } [Fact] public void DecryptAsync_string_ReturnsACompletedTask() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encryptTask = asyncCrypto.DecryptAsync("stuff", "foo", default(CancellationToken)); encryptTask.IsCompleted.Should().BeTrue(); } [Fact] public void DecryptAsync_string_ReturnsTheResultReturnedByCryptoEncrypt() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encrypted = asyncCrypto.DecryptAsync("stuff", "foo", default(CancellationToken)).Result; encrypted.Should().Be("DecryptedString : foo"); } [Fact] public void DecryptAsync_bytearray_ReturnsACompletedTask() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encryptTask = asyncCrypto.DecryptAsync(new byte[0], "foo", default(CancellationToken)); encryptTask.IsCompleted.Should().BeTrue(); } [Fact] public void DecryptAsync_bytearray_ReturnsTheResultReturnedByCryptoEncrypt() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encrypted = asyncCrypto.DecryptAsync(new byte[0], "foo", default(CancellationToken)).Result; encrypted.Should().BeEquivalentTo(Encoding.UTF8.GetBytes("foo")); } [Fact] public void GetEncryptorAsync_ReturnsASynchronousAsyncEncryptor() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encryptor = asyncCrypto.GetAsyncEncryptor("foo"); encryptor.Should().BeOfType<SynchronousAsyncEncryptor>(); } [Fact] public void GetEncryptorAsync_ReturnsASynchronousAsyncEncryptorWhoseEncryptorIsTheOneReturnedByACallToTheCryptoGetEncryptorMethod() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var encryptor = (SynchronousAsyncEncryptor)asyncCrypto.GetAsyncEncryptor("foo"); encryptor.Encryptor.Should().BeSameAs(_encryptor); } [Fact] public void GetDecryptorAsync_ReturnsASynchronousAsyncDecryptor() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var decryptor = asyncCrypto.GetAsyncDecryptor("foo"); decryptor.Should().BeOfType<SynchronousAsyncDecryptor>(); } [Fact] public void GetDecryptorAsync_ReturnsASynchronousAsyncDecryptorWhoseDecryptorIsTheOneReturnedByACallToTheCryptoGetDecryptorMethod() { Setup("foo"); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); var decryptor = (SynchronousAsyncDecryptor)asyncCrypto.GetAsyncDecryptor("foo"); decryptor.Decryptor.Should().BeSameAs(_decryptor); } [Fact] public void CanEncrypt_ReturnsTheSameThingAsACallToCryptoCanEncrypt() { Setup("foo"); // Assumptions _cryptoMock.Object.CanEncrypt("foo").Should().BeTrue(); _cryptoMock.Object.CanEncrypt("bar").Should().BeFalse(); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); asyncCrypto.CanEncrypt("foo").Should().BeTrue(); asyncCrypto.CanEncrypt("bar").Should().BeFalse(); } [Fact] public void CanDecrypt_ReturnsTheSameThingAsACallToCryptoCanDecrypt() { Setup("foo"); // Assumptions _cryptoMock.Object.CanDecrypt("foo").Should().BeTrue(); _cryptoMock.Object.CanDecrypt("bar").Should().BeFalse(); var asyncCrypto = new SynchronousAsyncCrypto(_cryptoMock.Object); asyncCrypto.CanDecrypt("foo").Should().BeTrue(); asyncCrypto.CanDecrypt("bar").Should().BeFalse(); } } }
34.331818
139
0.633523
[ "MIT" ]
RockLib/RockLib.Encryption
Tests/RockLib.Encryption.Tests/Async/SynchronousAsyncCryptoTests.cs
7,555
C#
using ResidentsSocialCarePlatformApi.V1.Boundary.Requests; using ResidentsSocialCarePlatformApi.V1.Boundary.Responses; namespace ResidentsSocialCarePlatformApi.V1.UseCase.Interfaces { public interface IAddResidentUseCase { ResidentInformation Execute(AddResidentRequest addResident); } }
28.090909
68
0.822006
[ "MIT" ]
LBHackney-IT/residents-social-care-platform-api
ResidentsSocialCarePlatformApi/V1/UseCase/Interfaces/IAddResidentUseCase.cs
309
C#
// ***************************************************************************** // // © 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, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.451.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; namespace ExpandingHeaderGroupsSplitters { public partial class Form1 : KryptonForm { private int _heightUpDown; private int _widthLeftRight; public Form1() { InitializeComponent(); // Hook into the click events on the header buttons kryptonHeaderGroupRightBottom.ButtonSpecs[0].Click += new EventHandler(OnUpDown); kryptonHeaderGroupLeft.ButtonSpecs[0].Click += new EventHandler(OnLeftRight); } private void Form1_Load(object sender, EventArgs e) { // Set position of caret in the text boxes, so it looks nicer at runtime! textBoxLeft.SelectionStart = textBoxRightTop.SelectionStart = textBoxRightBottom.SelectionStart = 0; textBoxLeft.SelectionLength = textBoxRightTop.SelectionLength = textBoxRightBottom.SelectionLength = 0; } private void OnUpDown(object sender, EventArgs e) { // Suspend layout changes until all splitter properties have been updated kryptonSplitContainerVertical.SuspendLayout(); // Is the bottom right header group currently expanded? if (kryptonSplitContainerVertical.FixedPanel == FixedPanel.None) { // Make the bottom panel of the splitter fixed in size kryptonSplitContainerVertical.FixedPanel = FixedPanel.Panel2; kryptonSplitContainerVertical.IsSplitterFixed = true; // Remember the current height of the header group (to restore later) _heightUpDown = kryptonHeaderGroupRightBottom.Height; // Find the new height to use for the header group int newHeight = kryptonHeaderGroupRightBottom.PreferredSize.Height; // Make the header group fixed to the new height kryptonSplitContainerVertical.Panel2MinSize = newHeight; kryptonSplitContainerVertical.SplitterDistance = kryptonSplitContainerVertical.Height; } else { // Make the bottom panel not-fixed in size anymore kryptonSplitContainerVertical.FixedPanel = FixedPanel.None; kryptonSplitContainerVertical.IsSplitterFixed = false; // Put back the minimise size to the original kryptonSplitContainerVertical.Panel2MinSize = 100; // Calculate the correct splitter we want to put back kryptonSplitContainerVertical.SplitterDistance = kryptonSplitContainerVertical.Height - _heightUpDown - kryptonSplitContainerVertical.SplitterWidth; } kryptonSplitContainerVertical.ResumeLayout(); } private void OnLeftRight(object sender, EventArgs e) { // Suspend layout changes until all splitter properties have been updated kryptonSplitContainerHorizontal.SuspendLayout(); // Is the left header group currently expanded? if (kryptonSplitContainerHorizontal.FixedPanel == FixedPanel.None) { // Make the left panel of the splitter fixed in size kryptonSplitContainerHorizontal.FixedPanel = FixedPanel.Panel1; kryptonSplitContainerHorizontal.IsSplitterFixed = true; // Remember the current height of the header group _widthLeftRight = kryptonHeaderGroupLeft.Width; // We have not changed the orientation of the header yet, so the width of // the splitter panel is going to be the height of the collapsed header group int newWidth = kryptonHeaderGroupLeft.PreferredSize.Height; // Make the header group fixed just as the new height kryptonSplitContainerHorizontal.Panel1MinSize = newWidth; kryptonSplitContainerHorizontal.SplitterDistance = newWidth; // Change header to be vertical and button to near edge kryptonHeaderGroupLeft.HeaderPositionPrimary = VisualOrientation.Right; kryptonHeaderGroupLeft.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Near; } else { // Make the bottom panel not-fixed in size anymore kryptonSplitContainerHorizontal.FixedPanel = FixedPanel.None; kryptonSplitContainerHorizontal.IsSplitterFixed = false; // Put back the minimise size to the original kryptonSplitContainerHorizontal.Panel1MinSize = 100; // Calculate the correct splitter we want to put back kryptonSplitContainerHorizontal.SplitterDistance = _widthLeftRight; // Change header to be horizontal and button to far edge kryptonHeaderGroupLeft.HeaderPositionPrimary = VisualOrientation.Top; kryptonHeaderGroupLeft.ButtonSpecs[0].Edge = PaletteRelativeEdgeAlign.Far; } kryptonSplitContainerHorizontal.ResumeLayout(); } private void UpdateCollapsedSizing() { // Is the bottom right header group currently collapsed? if (kryptonSplitContainerVertical.FixedPanel == FixedPanel.Panel2) { // Suspend layout changes until all splitter properties have been updated kryptonSplitContainerHorizontal.SuspendLayout(); // Get the new preferred height of the header group and apply it int newHeight = kryptonHeaderGroupRightBottom.PreferredSize.Height; kryptonSplitContainerVertical.Panel2MinSize = newHeight; kryptonSplitContainerVertical.SplitterDistance = kryptonSplitContainerVertical.Height; kryptonSplitContainerHorizontal.ResumeLayout(); } // Is the left header group currently collapsed? if (kryptonSplitContainerHorizontal.FixedPanel == FixedPanel.Panel1) { // Suspend layout changes until all splitter properties have been updated kryptonSplitContainerVertical.SuspendLayout(); // Get the new preferred width of the header group and apply it int newWidth = kryptonHeaderGroupLeft.PreferredSize.Width; kryptonSplitContainerHorizontal.Panel1MinSize = newWidth; kryptonSplitContainerHorizontal.SplitterDistance = newWidth; kryptonSplitContainerVertical.ResumeLayout(); } } private void toolOffice2010_Click(object sender, EventArgs e) { if (!toolOffice2010.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Blue; toolOffice2010.Checked = menuOffice2010.Checked = true; toolOffice2007.Checked = menuOffice2007.Checked = false; toolSystem.Checked = menuSystem.Checked = false; toolSparkle.Checked = menuSparkle.Checked = false; UpdateCollapsedSizing(); } } private void toolOffice2007_Click(object sender, EventArgs e) { if (!toolOffice2007.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Blue; toolOffice2010.Checked = menuOffice2010.Checked = false; toolOffice2007.Checked = menuOffice2007.Checked = true; toolSystem.Checked = menuSystem.Checked = false; toolSparkle.Checked = menuSparkle.Checked = false; UpdateCollapsedSizing(); } } private void toolSystem_Click(object sender, EventArgs e) { if (!toolSystem.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem; toolOffice2010.Checked = menuOffice2010.Checked = false; toolOffice2007.Checked = menuOffice2007.Checked = false; toolSystem.Checked = menuSystem.Checked = true; toolSparkle.Checked = menuSparkle.Checked = false; UpdateCollapsedSizing(); } } private void toolSparkle_Click(object sender, EventArgs e) { if (!toolSparkle.Checked) { kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleBlue; toolOffice2010.Checked = menuOffice2010.Checked = false; toolOffice2007.Checked = menuOffice2007.Checked = false; toolSystem.Checked = menuSystem.Checked = false; toolSparkle.Checked = menuSparkle.Checked = true; UpdateCollapsedSizing(); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } } }
45.075472
164
0.627459
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.451
Source/Demos/Non-NuGet/Krypton Toolkit Examples/Expanding HeaderGroups (Splitters)/Form1.cs
9,559
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FlatRedBall.TileGraphics; using FlatRedBall.Math; namespace FlatRedBall.AI.Pathfinding { public static class TileNodeNetworkCreator { public static TileNodeNetwork CreateFrom(LayeredTileMap layeredTileMap, DirectionalType directionalType, Func<List<TMXGlueLib.DataTypes.NamedValue>, bool> predicate) { TileNodeNetwork nodeNetwork = CreateTileNodeNetwork(layeredTileMap, directionalType); var dimensionHalf = layeredTileMap.WidthPerTile.Value / 2.0f; var properties = layeredTileMap.TileProperties; foreach (var kvp in properties) { string name = kvp.Key; var namedValues = kvp.Value; if (predicate(namedValues)) { foreach (var layer in layeredTileMap.MapLayers) { var dictionary = layer.NamedTileOrderedIndexes; if (dictionary.ContainsKey(name)) { var indexList = dictionary[name]; foreach (var index in indexList) { float left; float bottom; layer.GetBottomLeftWorldCoordinateForOrderedTile(index, out left, out bottom); var centerX = left + dimensionHalf; var centerY = bottom + dimensionHalf; nodeNetwork.AddAndLinkTiledNodeWorld(centerX, centerY); } } } } } nodeNetwork.Visible = true; return nodeNetwork; } public static TileNodeNetwork CreateFromTypes(LayeredTileMap layeredTileMap, DirectionalType directionalType, ICollection<string> types) { Func<List<TMXGlueLib.DataTypes.NamedValue>, bool> predicate = (list) => { var toReturn = false; foreach (var namedValue in list) { if (namedValue.Name == "Type") { var valueAsString = namedValue.Value as string; if (!string.IsNullOrEmpty(valueAsString) && types.Contains(valueAsString)) { toReturn = true; break; } } } return toReturn; }; return CreateFrom(layeredTileMap, directionalType, predicate); } private static TileNodeNetwork CreateTileNodeNetwork(LayeredTileMap layeredTileMap, DirectionalType directionalType) { var numberOfTilesWide = MathFunctions.RoundToInt(layeredTileMap.Width / layeredTileMap.WidthPerTile.Value); var numberOfTilesTall = MathFunctions.RoundToInt(layeredTileMap.Height / layeredTileMap.HeightPerTile.Value); var tileWidth = layeredTileMap.WidthPerTile.Value; var dimensionHalf = tileWidth / 2.0f; TileNodeNetwork nodeNetwork = new TileNodeNetwork( 0 + dimensionHalf, -layeredTileMap.Height + tileWidth / 2.0f, tileWidth, numberOfTilesWide, numberOfTilesTall, directionalType); return nodeNetwork; } } }
34.091743
124
0.526642
[ "MIT" ]
Cabrill/StoryNavigator
StoryNavigator/StoryNavigator/TileGraphics/TileNodeNetworkCreator.cs
3,718
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fire : MonoBehaviour { public Character character; public int FireForce; public int FireForceMin = 20; public int FireForceMax = 40; private void Start () { RandomFireForce (); } private void Update () { if (character.stats.characterOnFire == true && character.stats.characterDie == true) { character.stats.characterOnFire = false; } } public void RandomFireForce () { FireForce = Random.Range (FireForceMin, FireForceMax); } private void OnTriggerEnter2D (Collider2D collider) { if (collider.tag == "Character") { character.stats.characterOnFire = true; Quemar (); RandomFireForce (); } } private void OnTriggerExit2D (Collider2D collider) { if (collider.tag == "Character") { character.stats.characterOnFire = false; } } public void Quemar () { if (character.stats.characterOnFire == true && character.stats.characterDie == false) { character.stats.characterLive = character.stats.characterLive - FireForce; character.actions.showFireForceInText = FireForce; character.actions.ShowFloatingText (); character.actions.animations.hurtAnimation (); FireForce = Random.Range (FireForceMin, FireForceMax); Invoke ("Quemar", 1f); } } }
30.734694
95
0.622842
[ "MIT" ]
facundoezequiel/FinalGame
Assets/Fire.cs
1,508
C#
using System.ComponentModel; using DevExpress.ExpressApp; using DevExpress.ExpressApp.Actions; using DevExpress.ExpressApp.Web.SystemModule; namespace XafDelta.Web { public partial class VcWebActions : ViewController { public VcWebActions() { InitializeComponent(); RegisterActions(components); } #region Changes private WebDetailViewController detController; protected override void OnActivated() { base.OnActivated(); detController = Frame.GetController<WebDetailViewController>(); detController.EditAction.Executing += collectObjectSpace; detController.SaveAction.Executing += collectObjectSpace; detController.SaveAndCloseAction.Executing += collectObjectSpace; detController.SaveAndNewAction.Executing += collectObjectSpace; detController.EditAction.Execute += collectExecute; detController.SaveAction.Execute += collectExecute; detController.SaveAndCloseAction.Execute += collectExecute; detController.SaveAndNewAction.Execute += collectExecute; } protected override void OnDeactivated() { if (detController != null) { detController.EditAction.Executing -= collectObjectSpace; detController.SaveAction.Executing -= collectObjectSpace; detController.SaveAndCloseAction.Executing -= collectObjectSpace; detController.SaveAndNewAction.Executing -= collectObjectSpace; detController.EditAction.Execute -= collectExecute; detController.SaveAction.Execute -= collectExecute; detController.SaveAndCloseAction.Execute -= collectExecute; detController.SaveAndNewAction.Execute -= collectExecute; } base.OnDeactivated(); } void collectExecute(object sender, SimpleActionExecuteEventArgs e) { if (detController != null && detController.View != null) { XafDeltaModule.Instance.CollectObjectSpace(detController.View.ObjectSpace); } } void collectObjectSpace(object sender, CancelEventArgs e) { if (detController != null && detController.View != null) { XafDeltaModule.Instance.CollectObjectSpace(detController.View.ObjectSpace); } } #endregion } }
34.712329
91
0.638122
[ "MIT" ]
xafdelta/xafdelta
src/XafDelta.Web/VcWebActions.cs
2,536
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApiAttributeRoutingSample.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
40.472222
140
0.640357
[ "Apache-2.0" ]
ASCITSOL/asp.net
samples/aspnet/WebApi/WebApiAttributeRoutingSample/WebApiAttributeRoutingSample/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs
1,457
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace FunctionApp { public class ExpectedException : Exception { public ExpectedException(HttpStatusCode code, string message = "") : base(message) { Code = code; } public HttpStatusCode Code { get; } public HttpResponseMessage CreateErroResponseMessage(HttpRequestMessage request) { var result = request.CreateErrorResponse(Code, Message); ApplyResponseDetails(result); return result; } protected virtual void ApplyResponseDetails(HttpResponseMessage response) { } } }
25.09375
88
0.666252
[ "MIT" ]
SergioETrillo/SpikeAzureFunctions
src/FunctionApp/ExpectedException.cs
805
C#
using System.Runtime.CompilerServices; namespace LinqBenchmarks; readonly struct IntEqualityComparer : IEqualityComparer<int> { [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(int x, int y) => x == y; [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetHashCode(int obj) => obj; }
23.6
60
0.720339
[ "MIT" ]
NetFabric/LinqBenchmarks
LinqBenchmarks/IntEqualityComparer.cs
356
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. namespace Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal { public static class ScaffoldingAnnotationNames { public const string Prefix = "Scaffolding:"; public const string UseProviderMethodName = "UseProviderMethodName"; public const string ColumnOrdinal = "ColumnOrdinal"; public const string DependentEndNavigation = "DependentEndNavigation"; public const string PrincipalEndNavigation = "PrincipalEndNavigation"; public const string EntityTypeErrors = "EntityTypeErrors"; } }
45.0625
111
0.751734
[ "Apache-2.0" ]
davidroth/EntityFrameworkCore
src/Microsoft.EntityFrameworkCore.Relational.Design/Metadata/Internal/ScaffoldingAnnotationNames.cs
721
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 dms-2016-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Net; using Amazon.DatabaseMigrationService.Model; using Amazon.DatabaseMigrationService.Model.Internal.MarshallTransformations; using Amazon.DatabaseMigrationService.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.DatabaseMigrationService { /// <summary> /// Implementation for accessing DatabaseMigrationService /// /// AWS Database Migration Service /// <para> /// AWS Database Migration Service (AWS DMS) can migrate your data to and from the most /// widely used commercial and open-source databases such as Oracle, PostgreSQL, Microsoft /// SQL Server, Amazon Redshift, MariaDB, Amazon Aurora, MySQL, and SAP Adaptive Server /// Enterprise (ASE). The service supports homogeneous migrations such as Oracle to Oracle, /// as well as heterogeneous migrations between different database platforms, such as /// Oracle to MySQL or SQL Server to PostgreSQL. /// </para> /// /// <para> /// For more information about AWS DMS, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html">What /// Is AWS Database Migration Service?</a> in the <i>AWS Database Migration User Guide.</i> /// /// </para> /// </summary> public partial class AmazonDatabaseMigrationServiceClient : AmazonServiceClient, IAmazonDatabaseMigrationService { private static IServiceMetadata serviceMetadata = new AmazonDatabaseMigrationServiceMetadata(); #region Constructors /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonDatabaseMigrationServiceClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonDatabaseMigrationServiceConfig()) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonDatabaseMigrationServiceClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonDatabaseMigrationServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonDatabaseMigrationServiceClient Configuration Object</param> public AmazonDatabaseMigrationServiceClient(AmazonDatabaseMigrationServiceConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonDatabaseMigrationServiceClient(AWSCredentials credentials) : this(credentials, new AmazonDatabaseMigrationServiceConfig()) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonDatabaseMigrationServiceClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonDatabaseMigrationServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient with AWS Credentials and an /// AmazonDatabaseMigrationServiceClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonDatabaseMigrationServiceClient Configuration Object</param> public AmazonDatabaseMigrationServiceClient(AWSCredentials credentials, AmazonDatabaseMigrationServiceConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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 AmazonDatabaseMigrationServiceClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonDatabaseMigrationServiceConfig()) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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 AmazonDatabaseMigrationServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonDatabaseMigrationServiceConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonDatabaseMigrationServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonDatabaseMigrationServiceClient Configuration Object</param> public AmazonDatabaseMigrationServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDatabaseMigrationServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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 AmazonDatabaseMigrationServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDatabaseMigrationServiceConfig()) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient 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 AmazonDatabaseMigrationServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDatabaseMigrationServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDatabaseMigrationServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonDatabaseMigrationServiceClient 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 AmazonDatabaseMigrationServiceClient Configuration Object</param> public AmazonDatabaseMigrationServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDatabaseMigrationServiceConfig 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 AddTagsToResource /// <summary> /// Adds metadata tags to an AWS DMS resource, including replication instance, endpoint, /// security group, and migration task. These tags can also be used with cost allocation /// reporting to track cost associated with DMS resources, or used in a Condition statement /// in an IAM policy for DMS. For more information, see <a href="https://docs.aws.amazon.com/dms/latest/APIReference/API_Tag.html"> /// <code>Tag</code> </a> data type description. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AddTagsToResource service method.</param> /// /// <returns>The response from the AddTagsToResource service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/AddTagsToResource">REST API Reference for AddTagsToResource Operation</seealso> public virtual AddTagsToResourceResponse AddTagsToResource(AddTagsToResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AddTagsToResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = AddTagsToResourceResponseUnmarshaller.Instance; return Invoke<AddTagsToResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the AddTagsToResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddTagsToResource operation on AmazonDatabaseMigrationServiceClient.</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 EndAddTagsToResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/AddTagsToResource">REST API Reference for AddTagsToResource Operation</seealso> public virtual IAsyncResult BeginAddTagsToResource(AddTagsToResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = AddTagsToResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = AddTagsToResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the AddTagsToResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddTagsToResource.</param> /// /// <returns>Returns a AddTagsToResourceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/AddTagsToResource">REST API Reference for AddTagsToResource Operation</seealso> public virtual AddTagsToResourceResponse EndAddTagsToResource(IAsyncResult asyncResult) { return EndInvoke<AddTagsToResourceResponse>(asyncResult); } #endregion #region ApplyPendingMaintenanceAction /// <summary> /// Applies a pending maintenance action to a resource (for example, to a replication /// instance). /// </summary> /// <param name="request">Container for the necessary parameters to execute the ApplyPendingMaintenanceAction service method.</param> /// /// <returns>The response from the ApplyPendingMaintenanceAction service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ApplyPendingMaintenanceAction">REST API Reference for ApplyPendingMaintenanceAction Operation</seealso> public virtual ApplyPendingMaintenanceActionResponse ApplyPendingMaintenanceAction(ApplyPendingMaintenanceActionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ApplyPendingMaintenanceActionRequestMarshaller.Instance; options.ResponseUnmarshaller = ApplyPendingMaintenanceActionResponseUnmarshaller.Instance; return Invoke<ApplyPendingMaintenanceActionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ApplyPendingMaintenanceAction operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ApplyPendingMaintenanceAction operation on AmazonDatabaseMigrationServiceClient.</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 EndApplyPendingMaintenanceAction /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ApplyPendingMaintenanceAction">REST API Reference for ApplyPendingMaintenanceAction Operation</seealso> public virtual IAsyncResult BeginApplyPendingMaintenanceAction(ApplyPendingMaintenanceActionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ApplyPendingMaintenanceActionRequestMarshaller.Instance; options.ResponseUnmarshaller = ApplyPendingMaintenanceActionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ApplyPendingMaintenanceAction operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginApplyPendingMaintenanceAction.</param> /// /// <returns>Returns a ApplyPendingMaintenanceActionResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ApplyPendingMaintenanceAction">REST API Reference for ApplyPendingMaintenanceAction Operation</seealso> public virtual ApplyPendingMaintenanceActionResponse EndApplyPendingMaintenanceAction(IAsyncResult asyncResult) { return EndInvoke<ApplyPendingMaintenanceActionResponse>(asyncResult); } #endregion #region CancelReplicationTaskAssessmentRun /// <summary> /// Cancels a single premigration assessment run. /// /// /// <para> /// This operation prevents any individual assessments from running if they haven't started /// running. It also attempts to cancel any individual assessments that are currently /// running. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelReplicationTaskAssessmentRun service method.</param> /// /// <returns>The response from the CancelReplicationTaskAssessmentRun service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CancelReplicationTaskAssessmentRun">REST API Reference for CancelReplicationTaskAssessmentRun Operation</seealso> public virtual CancelReplicationTaskAssessmentRunResponse CancelReplicationTaskAssessmentRun(CancelReplicationTaskAssessmentRunRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CancelReplicationTaskAssessmentRunRequestMarshaller.Instance; options.ResponseUnmarshaller = CancelReplicationTaskAssessmentRunResponseUnmarshaller.Instance; return Invoke<CancelReplicationTaskAssessmentRunResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CancelReplicationTaskAssessmentRun operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelReplicationTaskAssessmentRun operation on AmazonDatabaseMigrationServiceClient.</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 EndCancelReplicationTaskAssessmentRun /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CancelReplicationTaskAssessmentRun">REST API Reference for CancelReplicationTaskAssessmentRun Operation</seealso> public virtual IAsyncResult BeginCancelReplicationTaskAssessmentRun(CancelReplicationTaskAssessmentRunRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CancelReplicationTaskAssessmentRunRequestMarshaller.Instance; options.ResponseUnmarshaller = CancelReplicationTaskAssessmentRunResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CancelReplicationTaskAssessmentRun operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCancelReplicationTaskAssessmentRun.</param> /// /// <returns>Returns a CancelReplicationTaskAssessmentRunResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CancelReplicationTaskAssessmentRun">REST API Reference for CancelReplicationTaskAssessmentRun Operation</seealso> public virtual CancelReplicationTaskAssessmentRunResponse EndCancelReplicationTaskAssessmentRun(IAsyncResult asyncResult) { return EndInvoke<CancelReplicationTaskAssessmentRunResponse>(asyncResult); } #endregion #region CreateEndpoint /// <summary> /// Creates an endpoint using the provided settings. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateEndpoint service method.</param> /// /// <returns>The response from the CreateEndpoint service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.S3AccessDeniedException"> /// Insufficient privileges are preventing access to an Amazon S3 object. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEndpoint">REST API Reference for CreateEndpoint Operation</seealso> public virtual CreateEndpointResponse CreateEndpoint(CreateEndpointRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateEndpointResponseUnmarshaller.Instance; return Invoke<CreateEndpointResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateEndpoint operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateEndpoint operation on AmazonDatabaseMigrationServiceClient.</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 EndCreateEndpoint /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEndpoint">REST API Reference for CreateEndpoint Operation</seealso> public virtual IAsyncResult BeginCreateEndpoint(CreateEndpointRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateEndpointResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateEndpoint operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateEndpoint.</param> /// /// <returns>Returns a CreateEndpointResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEndpoint">REST API Reference for CreateEndpoint Operation</seealso> public virtual CreateEndpointResponse EndCreateEndpoint(IAsyncResult asyncResult) { return EndInvoke<CreateEndpointResponse>(asyncResult); } #endregion #region CreateEventSubscription /// <summary> /// Creates an AWS DMS event notification subscription. /// /// /// <para> /// You can specify the type of source (<code>SourceType</code>) you want to be notified /// of, provide a list of AWS DMS source IDs (<code>SourceIds</code>) that triggers the /// events, and provide a list of event categories (<code>EventCategories</code>) for /// events you want to be notified of. If you specify both the <code>SourceType</code> /// and <code>SourceIds</code>, such as <code>SourceType = replication-instance</code> /// and <code>SourceIdentifier = my-replinstance</code>, you will be notified of all the /// replication instance events for the specified source. If you specify a <code>SourceType</code> /// but don't specify a <code>SourceIdentifier</code>, you receive notice of the events /// for that source type for all your AWS DMS sources. If you don't specify either <code>SourceType</code> /// nor <code>SourceIdentifier</code>, you will be notified of events generated from all /// AWS DMS sources belonging to your customer account. /// </para> /// /// <para> /// For more information about AWS DMS events, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html">Working /// with Events and Notifications</a> in the <i>AWS Database Migration Service User Guide.</i> /// /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateEventSubscription service method.</param> /// /// <returns>The response from the CreateEventSubscription service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSAccessDeniedException"> /// The ciphertext references a key that doesn't exist or that the DMS account doesn't /// have access to. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSDisabledException"> /// The specified master key (CMK) isn't enabled. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSInvalidStateException"> /// The state of the specified AWS KMS resource isn't valid for this request. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSNotFoundException"> /// The specified AWS KMS entity or resource can't be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSThrottlingException"> /// This request triggered AWS KMS request throttling. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.SNSInvalidTopicException"> /// The SNS topic is invalid. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.SNSNoAuthorizationException"> /// You are not authorized for the SNS subscription. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEventSubscription">REST API Reference for CreateEventSubscription Operation</seealso> public virtual CreateEventSubscriptionResponse CreateEventSubscription(CreateEventSubscriptionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateEventSubscriptionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateEventSubscriptionResponseUnmarshaller.Instance; return Invoke<CreateEventSubscriptionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateEventSubscription operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateEventSubscription operation on AmazonDatabaseMigrationServiceClient.</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 EndCreateEventSubscription /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEventSubscription">REST API Reference for CreateEventSubscription Operation</seealso> public virtual IAsyncResult BeginCreateEventSubscription(CreateEventSubscriptionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateEventSubscriptionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateEventSubscriptionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateEventSubscription operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateEventSubscription.</param> /// /// <returns>Returns a CreateEventSubscriptionResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateEventSubscription">REST API Reference for CreateEventSubscription Operation</seealso> public virtual CreateEventSubscriptionResponse EndCreateEventSubscription(IAsyncResult asyncResult) { return EndInvoke<CreateEventSubscriptionResponse>(asyncResult); } #endregion #region CreateReplicationInstance /// <summary> /// Creates the replication instance using the specified parameters. /// /// /// <para> /// AWS DMS requires that your account have certain roles with appropriate permissions /// before you can create a replication instance. For information on the required roles, /// see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Security.html#CHAP_Security.APIRole">Creating /// the IAM Roles to Use With the AWS CLI and AWS DMS API</a>. For information on the /// required permissions, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Security.html#CHAP_Security.IAMPermissions">IAM /// Permissions Needed to Use AWS DMS</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateReplicationInstance service method.</param> /// /// <returns>The response from the CreateReplicationInstance service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InsufficientResourceCapacityException"> /// There are not enough resources allocated to the database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidSubnetException"> /// The subnet provided is invalid. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ReplicationSubnetGroupDoesNotCoverEnoughAZsException"> /// The replication subnet group does not cover enough Availability Zones (AZs). Edit /// the replication subnet group and add more AZs. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.StorageQuotaExceededException"> /// The storage quota has been exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationInstance">REST API Reference for CreateReplicationInstance Operation</seealso> public virtual CreateReplicationInstanceResponse CreateReplicationInstance(CreateReplicationInstanceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateReplicationInstanceResponseUnmarshaller.Instance; return Invoke<CreateReplicationInstanceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateReplicationInstance operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateReplicationInstance operation on AmazonDatabaseMigrationServiceClient.</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 EndCreateReplicationInstance /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationInstance">REST API Reference for CreateReplicationInstance Operation</seealso> public virtual IAsyncResult BeginCreateReplicationInstance(CreateReplicationInstanceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateReplicationInstanceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateReplicationInstance operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateReplicationInstance.</param> /// /// <returns>Returns a CreateReplicationInstanceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationInstance">REST API Reference for CreateReplicationInstance Operation</seealso> public virtual CreateReplicationInstanceResponse EndCreateReplicationInstance(IAsyncResult asyncResult) { return EndInvoke<CreateReplicationInstanceResponse>(asyncResult); } #endregion #region CreateReplicationSubnetGroup /// <summary> /// Creates a replication subnet group given a list of the subnet IDs in a VPC. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateReplicationSubnetGroup service method.</param> /// /// <returns>The response from the CreateReplicationSubnetGroup service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidSubnetException"> /// The subnet provided is invalid. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ReplicationSubnetGroupDoesNotCoverEnoughAZsException"> /// The replication subnet group does not cover enough Availability Zones (AZs). Edit /// the replication subnet group and add more AZs. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationSubnetGroup">REST API Reference for CreateReplicationSubnetGroup Operation</seealso> public virtual CreateReplicationSubnetGroupResponse CreateReplicationSubnetGroup(CreateReplicationSubnetGroupRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateReplicationSubnetGroupRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateReplicationSubnetGroupResponseUnmarshaller.Instance; return Invoke<CreateReplicationSubnetGroupResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateReplicationSubnetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateReplicationSubnetGroup operation on AmazonDatabaseMigrationServiceClient.</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 EndCreateReplicationSubnetGroup /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationSubnetGroup">REST API Reference for CreateReplicationSubnetGroup Operation</seealso> public virtual IAsyncResult BeginCreateReplicationSubnetGroup(CreateReplicationSubnetGroupRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateReplicationSubnetGroupRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateReplicationSubnetGroupResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateReplicationSubnetGroup operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateReplicationSubnetGroup.</param> /// /// <returns>Returns a CreateReplicationSubnetGroupResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationSubnetGroup">REST API Reference for CreateReplicationSubnetGroup Operation</seealso> public virtual CreateReplicationSubnetGroupResponse EndCreateReplicationSubnetGroup(IAsyncResult asyncResult) { return EndInvoke<CreateReplicationSubnetGroupResponse>(asyncResult); } #endregion #region CreateReplicationTask /// <summary> /// Creates a replication task using the specified parameters. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateReplicationTask service method.</param> /// /// <returns>The response from the CreateReplicationTask service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationTask">REST API Reference for CreateReplicationTask Operation</seealso> public virtual CreateReplicationTaskResponse CreateReplicationTask(CreateReplicationTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateReplicationTaskResponseUnmarshaller.Instance; return Invoke<CreateReplicationTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateReplicationTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateReplicationTask operation on AmazonDatabaseMigrationServiceClient.</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 EndCreateReplicationTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationTask">REST API Reference for CreateReplicationTask Operation</seealso> public virtual IAsyncResult BeginCreateReplicationTask(CreateReplicationTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateReplicationTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateReplicationTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateReplicationTask.</param> /// /// <returns>Returns a CreateReplicationTaskResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CreateReplicationTask">REST API Reference for CreateReplicationTask Operation</seealso> public virtual CreateReplicationTaskResponse EndCreateReplicationTask(IAsyncResult asyncResult) { return EndInvoke<CreateReplicationTaskResponse>(asyncResult); } #endregion #region DeleteCertificate /// <summary> /// Deletes the specified certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteCertificate service method.</param> /// /// <returns>The response from the DeleteCertificate service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso> public virtual DeleteCertificateResponse DeleteCertificate(DeleteCertificateRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteCertificateResponseUnmarshaller.Instance; return Invoke<DeleteCertificateResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCertificate operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteCertificate /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso> public virtual IAsyncResult BeginDeleteCertificate(DeleteCertificateRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteCertificateResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteCertificate operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteCertificate.</param> /// /// <returns>Returns a DeleteCertificateResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteCertificate">REST API Reference for DeleteCertificate Operation</seealso> public virtual DeleteCertificateResponse EndDeleteCertificate(IAsyncResult asyncResult) { return EndInvoke<DeleteCertificateResponse>(asyncResult); } #endregion #region DeleteConnection /// <summary> /// Deletes the connection between a replication instance and an endpoint. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteConnection service method.</param> /// /// <returns>The response from the DeleteConnection service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso> public virtual DeleteConnectionResponse DeleteConnection(DeleteConnectionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteConnectionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteConnectionResponseUnmarshaller.Instance; return Invoke<DeleteConnectionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteConnection operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteConnection operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteConnection /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso> public virtual IAsyncResult BeginDeleteConnection(DeleteConnectionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteConnectionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteConnectionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteConnection operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteConnection.</param> /// /// <returns>Returns a DeleteConnectionResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso> public virtual DeleteConnectionResponse EndDeleteConnection(IAsyncResult asyncResult) { return EndInvoke<DeleteConnectionResponse>(asyncResult); } #endregion #region DeleteEndpoint /// <summary> /// Deletes the specified endpoint. /// /// <note> /// <para> /// All tasks associated with the endpoint must be deleted before you can delete the endpoint. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteEndpoint service method.</param> /// /// <returns>The response from the DeleteEndpoint service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEndpoint">REST API Reference for DeleteEndpoint Operation</seealso> public virtual DeleteEndpointResponse DeleteEndpoint(DeleteEndpointRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteEndpointResponseUnmarshaller.Instance; return Invoke<DeleteEndpointResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteEndpoint operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteEndpoint operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteEndpoint /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEndpoint">REST API Reference for DeleteEndpoint Operation</seealso> public virtual IAsyncResult BeginDeleteEndpoint(DeleteEndpointRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteEndpointResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteEndpoint operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteEndpoint.</param> /// /// <returns>Returns a DeleteEndpointResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEndpoint">REST API Reference for DeleteEndpoint Operation</seealso> public virtual DeleteEndpointResponse EndDeleteEndpoint(IAsyncResult asyncResult) { return EndInvoke<DeleteEndpointResponse>(asyncResult); } #endregion #region DeleteEventSubscription /// <summary> /// Deletes an AWS DMS event subscription. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteEventSubscription service method.</param> /// /// <returns>The response from the DeleteEventSubscription service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEventSubscription">REST API Reference for DeleteEventSubscription Operation</seealso> public virtual DeleteEventSubscriptionResponse DeleteEventSubscription(DeleteEventSubscriptionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteEventSubscriptionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteEventSubscriptionResponseUnmarshaller.Instance; return Invoke<DeleteEventSubscriptionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteEventSubscription operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteEventSubscription operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteEventSubscription /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEventSubscription">REST API Reference for DeleteEventSubscription Operation</seealso> public virtual IAsyncResult BeginDeleteEventSubscription(DeleteEventSubscriptionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteEventSubscriptionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteEventSubscriptionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteEventSubscription operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteEventSubscription.</param> /// /// <returns>Returns a DeleteEventSubscriptionResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteEventSubscription">REST API Reference for DeleteEventSubscription Operation</seealso> public virtual DeleteEventSubscriptionResponse EndDeleteEventSubscription(IAsyncResult asyncResult) { return EndInvoke<DeleteEventSubscriptionResponse>(asyncResult); } #endregion #region DeleteReplicationInstance /// <summary> /// Deletes the specified replication instance. /// /// <note> /// <para> /// You must delete any migration tasks that are associated with the replication instance /// before you can delete it. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationInstance service method.</param> /// /// <returns>The response from the DeleteReplicationInstance service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationInstance">REST API Reference for DeleteReplicationInstance Operation</seealso> public virtual DeleteReplicationInstanceResponse DeleteReplicationInstance(DeleteReplicationInstanceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationInstanceResponseUnmarshaller.Instance; return Invoke<DeleteReplicationInstanceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteReplicationInstance operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationInstance operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteReplicationInstance /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationInstance">REST API Reference for DeleteReplicationInstance Operation</seealso> public virtual IAsyncResult BeginDeleteReplicationInstance(DeleteReplicationInstanceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationInstanceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteReplicationInstance operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteReplicationInstance.</param> /// /// <returns>Returns a DeleteReplicationInstanceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationInstance">REST API Reference for DeleteReplicationInstance Operation</seealso> public virtual DeleteReplicationInstanceResponse EndDeleteReplicationInstance(IAsyncResult asyncResult) { return EndInvoke<DeleteReplicationInstanceResponse>(asyncResult); } #endregion #region DeleteReplicationSubnetGroup /// <summary> /// Deletes a subnet group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationSubnetGroup service method.</param> /// /// <returns>The response from the DeleteReplicationSubnetGroup service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationSubnetGroup">REST API Reference for DeleteReplicationSubnetGroup Operation</seealso> public virtual DeleteReplicationSubnetGroupResponse DeleteReplicationSubnetGroup(DeleteReplicationSubnetGroupRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationSubnetGroupRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationSubnetGroupResponseUnmarshaller.Instance; return Invoke<DeleteReplicationSubnetGroupResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteReplicationSubnetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationSubnetGroup operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteReplicationSubnetGroup /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationSubnetGroup">REST API Reference for DeleteReplicationSubnetGroup Operation</seealso> public virtual IAsyncResult BeginDeleteReplicationSubnetGroup(DeleteReplicationSubnetGroupRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationSubnetGroupRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationSubnetGroupResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteReplicationSubnetGroup operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteReplicationSubnetGroup.</param> /// /// <returns>Returns a DeleteReplicationSubnetGroupResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationSubnetGroup">REST API Reference for DeleteReplicationSubnetGroup Operation</seealso> public virtual DeleteReplicationSubnetGroupResponse EndDeleteReplicationSubnetGroup(IAsyncResult asyncResult) { return EndInvoke<DeleteReplicationSubnetGroupResponse>(asyncResult); } #endregion #region DeleteReplicationTask /// <summary> /// Deletes the specified replication task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationTask service method.</param> /// /// <returns>The response from the DeleteReplicationTask service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTask">REST API Reference for DeleteReplicationTask Operation</seealso> public virtual DeleteReplicationTaskResponse DeleteReplicationTask(DeleteReplicationTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationTaskResponseUnmarshaller.Instance; return Invoke<DeleteReplicationTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteReplicationTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationTask operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteReplicationTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTask">REST API Reference for DeleteReplicationTask Operation</seealso> public virtual IAsyncResult BeginDeleteReplicationTask(DeleteReplicationTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteReplicationTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteReplicationTask.</param> /// /// <returns>Returns a DeleteReplicationTaskResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTask">REST API Reference for DeleteReplicationTask Operation</seealso> public virtual DeleteReplicationTaskResponse EndDeleteReplicationTask(IAsyncResult asyncResult) { return EndInvoke<DeleteReplicationTaskResponse>(asyncResult); } #endregion #region DeleteReplicationTaskAssessmentRun /// <summary> /// Deletes the record of a single premigration assessment run. /// /// /// <para> /// This operation removes all metadata that AWS DMS maintains about this assessment run. /// However, the operation leaves untouched all information about this assessment run /// that is stored in your Amazon S3 bucket. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationTaskAssessmentRun service method.</param> /// /// <returns>The response from the DeleteReplicationTaskAssessmentRun service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTaskAssessmentRun">REST API Reference for DeleteReplicationTaskAssessmentRun Operation</seealso> public virtual DeleteReplicationTaskAssessmentRunResponse DeleteReplicationTaskAssessmentRun(DeleteReplicationTaskAssessmentRunRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationTaskAssessmentRunRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationTaskAssessmentRunResponseUnmarshaller.Instance; return Invoke<DeleteReplicationTaskAssessmentRunResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteReplicationTaskAssessmentRun operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationTaskAssessmentRun operation on AmazonDatabaseMigrationServiceClient.</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 EndDeleteReplicationTaskAssessmentRun /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTaskAssessmentRun">REST API Reference for DeleteReplicationTaskAssessmentRun Operation</seealso> public virtual IAsyncResult BeginDeleteReplicationTaskAssessmentRun(DeleteReplicationTaskAssessmentRunRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteReplicationTaskAssessmentRunRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteReplicationTaskAssessmentRunResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteReplicationTaskAssessmentRun operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteReplicationTaskAssessmentRun.</param> /// /// <returns>Returns a DeleteReplicationTaskAssessmentRunResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTaskAssessmentRun">REST API Reference for DeleteReplicationTaskAssessmentRun Operation</seealso> public virtual DeleteReplicationTaskAssessmentRunResponse EndDeleteReplicationTaskAssessmentRun(IAsyncResult asyncResult) { return EndInvoke<DeleteReplicationTaskAssessmentRunResponse>(asyncResult); } #endregion #region DescribeAccountAttributes /// <summary> /// Lists all of the AWS DMS attributes for a customer account. These attributes include /// AWS DMS quotas for the account and a unique account identifier in a particular DMS /// region. DMS quotas include a list of resource quotas supported by the account, such /// as the number of replication instances allowed. The description for each resource /// quota, includes the quota name, current usage toward that quota, and the quota's maximum /// value. DMS uses the unique account identifier to name each artifact used by DMS in /// the given region. /// /// /// <para> /// This command does not take any parameters. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeAccountAttributes service method.</param> /// /// <returns>The response from the DescribeAccountAttributes service method, as returned by DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeAccountAttributes">REST API Reference for DescribeAccountAttributes Operation</seealso> public virtual DescribeAccountAttributesResponse DescribeAccountAttributes(DescribeAccountAttributesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeAccountAttributesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeAccountAttributesResponseUnmarshaller.Instance; return Invoke<DescribeAccountAttributesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeAccountAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAccountAttributes operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeAccountAttributes /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeAccountAttributes">REST API Reference for DescribeAccountAttributes Operation</seealso> public virtual IAsyncResult BeginDescribeAccountAttributes(DescribeAccountAttributesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeAccountAttributesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeAccountAttributesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeAccountAttributes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAccountAttributes.</param> /// /// <returns>Returns a DescribeAccountAttributesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeAccountAttributes">REST API Reference for DescribeAccountAttributes Operation</seealso> public virtual DescribeAccountAttributesResponse EndDescribeAccountAttributes(IAsyncResult asyncResult) { return EndInvoke<DescribeAccountAttributesResponse>(asyncResult); } #endregion #region DescribeApplicableIndividualAssessments /// <summary> /// Provides a list of individual assessments that you can specify for a new premigration /// assessment run, given one or more parameters. /// /// /// <para> /// If you specify an existing migration task, this operation provides the default individual /// assessments you can specify for that task. Otherwise, the specified parameters model /// elements of a possible migration task on which to base a premigration assessment run. /// </para> /// /// <para> /// To use these migration task modeling parameters, you must specify an existing replication /// instance, a source database engine, a target database engine, and a migration type. /// This combination of parameters potentially limits the default individual assessments /// available for an assessment run created for a corresponding migration task. /// </para> /// /// <para> /// If you specify no parameters, this operation provides a list of all possible individual /// assessments that you can specify for an assessment run. If you specify any one of /// the task modeling parameters, you must specify all of them or the operation cannot /// provide a list of individual assessments. The only parameter that you can specify /// alone is for an existing migration task. The specified task definition then determines /// the default list of individual assessments that you can specify in an assessment run /// for the task. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeApplicableIndividualAssessments service method.</param> /// /// <returns>The response from the DescribeApplicableIndividualAssessments service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeApplicableIndividualAssessments">REST API Reference for DescribeApplicableIndividualAssessments Operation</seealso> public virtual DescribeApplicableIndividualAssessmentsResponse DescribeApplicableIndividualAssessments(DescribeApplicableIndividualAssessmentsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeApplicableIndividualAssessmentsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeApplicableIndividualAssessmentsResponseUnmarshaller.Instance; return Invoke<DescribeApplicableIndividualAssessmentsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeApplicableIndividualAssessments operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeApplicableIndividualAssessments operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeApplicableIndividualAssessments /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeApplicableIndividualAssessments">REST API Reference for DescribeApplicableIndividualAssessments Operation</seealso> public virtual IAsyncResult BeginDescribeApplicableIndividualAssessments(DescribeApplicableIndividualAssessmentsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeApplicableIndividualAssessmentsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeApplicableIndividualAssessmentsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeApplicableIndividualAssessments operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeApplicableIndividualAssessments.</param> /// /// <returns>Returns a DescribeApplicableIndividualAssessmentsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeApplicableIndividualAssessments">REST API Reference for DescribeApplicableIndividualAssessments Operation</seealso> public virtual DescribeApplicableIndividualAssessmentsResponse EndDescribeApplicableIndividualAssessments(IAsyncResult asyncResult) { return EndInvoke<DescribeApplicableIndividualAssessmentsResponse>(asyncResult); } #endregion #region DescribeCertificates /// <summary> /// Provides a description of the certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCertificates service method.</param> /// /// <returns>The response from the DescribeCertificates service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeCertificates">REST API Reference for DescribeCertificates Operation</seealso> public virtual DescribeCertificatesResponse DescribeCertificates(DescribeCertificatesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeCertificatesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeCertificatesResponseUnmarshaller.Instance; return Invoke<DescribeCertificatesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeCertificates operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCertificates operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeCertificates /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeCertificates">REST API Reference for DescribeCertificates Operation</seealso> public virtual IAsyncResult BeginDescribeCertificates(DescribeCertificatesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeCertificatesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeCertificatesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeCertificates operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeCertificates.</param> /// /// <returns>Returns a DescribeCertificatesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeCertificates">REST API Reference for DescribeCertificates Operation</seealso> public virtual DescribeCertificatesResponse EndDescribeCertificates(IAsyncResult asyncResult) { return EndInvoke<DescribeCertificatesResponse>(asyncResult); } #endregion #region DescribeConnections /// <summary> /// Describes the status of the connections that have been made between the replication /// instance and an endpoint. Connections are created when you test an endpoint. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeConnections service method.</param> /// /// <returns>The response from the DescribeConnections service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeConnections">REST API Reference for DescribeConnections Operation</seealso> public virtual DescribeConnectionsResponse DescribeConnections(DescribeConnectionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeConnectionsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeConnectionsResponseUnmarshaller.Instance; return Invoke<DescribeConnectionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeConnections operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConnections operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeConnections /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeConnections">REST API Reference for DescribeConnections Operation</seealso> public virtual IAsyncResult BeginDescribeConnections(DescribeConnectionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeConnectionsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeConnectionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeConnections operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeConnections.</param> /// /// <returns>Returns a DescribeConnectionsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeConnections">REST API Reference for DescribeConnections Operation</seealso> public virtual DescribeConnectionsResponse EndDescribeConnections(IAsyncResult asyncResult) { return EndInvoke<DescribeConnectionsResponse>(asyncResult); } #endregion #region DescribeEndpoints /// <summary> /// Returns information about the endpoints for your account in the current region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEndpoints service method.</param> /// /// <returns>The response from the DescribeEndpoints service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpoints">REST API Reference for DescribeEndpoints Operation</seealso> public virtual DescribeEndpointsResponse DescribeEndpoints(DescribeEndpointsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEndpointsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEndpointsResponseUnmarshaller.Instance; return Invoke<DescribeEndpointsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeEndpoints operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEndpoints operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeEndpoints /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpoints">REST API Reference for DescribeEndpoints Operation</seealso> public virtual IAsyncResult BeginDescribeEndpoints(DescribeEndpointsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEndpointsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEndpointsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeEndpoints operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEndpoints.</param> /// /// <returns>Returns a DescribeEndpointsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpoints">REST API Reference for DescribeEndpoints Operation</seealso> public virtual DescribeEndpointsResponse EndDescribeEndpoints(IAsyncResult asyncResult) { return EndInvoke<DescribeEndpointsResponse>(asyncResult); } #endregion #region DescribeEndpointTypes /// <summary> /// Returns information about the type of endpoints available. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEndpointTypes service method.</param> /// /// <returns>The response from the DescribeEndpointTypes service method, as returned by DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpointTypes">REST API Reference for DescribeEndpointTypes Operation</seealso> public virtual DescribeEndpointTypesResponse DescribeEndpointTypes(DescribeEndpointTypesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEndpointTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEndpointTypesResponseUnmarshaller.Instance; return Invoke<DescribeEndpointTypesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeEndpointTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEndpointTypes operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeEndpointTypes /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpointTypes">REST API Reference for DescribeEndpointTypes Operation</seealso> public virtual IAsyncResult BeginDescribeEndpointTypes(DescribeEndpointTypesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEndpointTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEndpointTypesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeEndpointTypes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEndpointTypes.</param> /// /// <returns>Returns a DescribeEndpointTypesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEndpointTypes">REST API Reference for DescribeEndpointTypes Operation</seealso> public virtual DescribeEndpointTypesResponse EndDescribeEndpointTypes(IAsyncResult asyncResult) { return EndInvoke<DescribeEndpointTypesResponse>(asyncResult); } #endregion #region DescribeEventCategories /// <summary> /// Lists categories for all event source types, or, if specified, for a specified source /// type. You can see a list of the event categories and source types in <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html">Working /// with Events and Notifications</a> in the <i>AWS Database Migration Service User Guide.</i> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEventCategories service method.</param> /// /// <returns>The response from the DescribeEventCategories service method, as returned by DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEventCategories">REST API Reference for DescribeEventCategories Operation</seealso> public virtual DescribeEventCategoriesResponse DescribeEventCategories(DescribeEventCategoriesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEventCategoriesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEventCategoriesResponseUnmarshaller.Instance; return Invoke<DescribeEventCategoriesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeEventCategories operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEventCategories operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeEventCategories /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEventCategories">REST API Reference for DescribeEventCategories Operation</seealso> public virtual IAsyncResult BeginDescribeEventCategories(DescribeEventCategoriesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEventCategoriesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEventCategoriesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeEventCategories operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEventCategories.</param> /// /// <returns>Returns a DescribeEventCategoriesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEventCategories">REST API Reference for DescribeEventCategories Operation</seealso> public virtual DescribeEventCategoriesResponse EndDescribeEventCategories(IAsyncResult asyncResult) { return EndInvoke<DescribeEventCategoriesResponse>(asyncResult); } #endregion #region DescribeEvents /// <summary> /// Lists events for a given source identifier and source type. You can also specify /// a start and end time. For more information on AWS DMS events, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html">Working /// with Events and Notifications</a> in the <i>AWS Database Migration User Guide.</i> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEvents service method.</param> /// /// <returns>The response from the DescribeEvents service method, as returned by DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEvents">REST API Reference for DescribeEvents Operation</seealso> public virtual DescribeEventsResponse DescribeEvents(DescribeEventsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEventsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEventsResponseUnmarshaller.Instance; return Invoke<DescribeEventsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEvents operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeEvents /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEvents">REST API Reference for DescribeEvents Operation</seealso> public virtual IAsyncResult BeginDescribeEvents(DescribeEventsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEventsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEventsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeEvents operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEvents.</param> /// /// <returns>Returns a DescribeEventsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEvents">REST API Reference for DescribeEvents Operation</seealso> public virtual DescribeEventsResponse EndDescribeEvents(IAsyncResult asyncResult) { return EndInvoke<DescribeEventsResponse>(asyncResult); } #endregion #region DescribeEventSubscriptions /// <summary> /// Lists all the event subscriptions for a customer account. The description of a subscription /// includes <code>SubscriptionName</code>, <code>SNSTopicARN</code>, <code>CustomerID</code>, /// <code>SourceType</code>, <code>SourceID</code>, <code>CreationTime</code>, and <code>Status</code>. /// /// /// /// <para> /// If you specify <code>SubscriptionName</code>, this action lists the description for /// that subscription. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEventSubscriptions service method.</param> /// /// <returns>The response from the DescribeEventSubscriptions service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEventSubscriptions">REST API Reference for DescribeEventSubscriptions Operation</seealso> public virtual DescribeEventSubscriptionsResponse DescribeEventSubscriptions(DescribeEventSubscriptionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEventSubscriptionsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEventSubscriptionsResponseUnmarshaller.Instance; return Invoke<DescribeEventSubscriptionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeEventSubscriptions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEventSubscriptions operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeEventSubscriptions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEventSubscriptions">REST API Reference for DescribeEventSubscriptions Operation</seealso> public virtual IAsyncResult BeginDescribeEventSubscriptions(DescribeEventSubscriptionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeEventSubscriptionsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeEventSubscriptionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeEventSubscriptions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEventSubscriptions.</param> /// /// <returns>Returns a DescribeEventSubscriptionsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeEventSubscriptions">REST API Reference for DescribeEventSubscriptions Operation</seealso> public virtual DescribeEventSubscriptionsResponse EndDescribeEventSubscriptions(IAsyncResult asyncResult) { return EndInvoke<DescribeEventSubscriptionsResponse>(asyncResult); } #endregion #region DescribeOrderableReplicationInstances /// <summary> /// Returns information about the replication instance types that can be created in the /// specified region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeOrderableReplicationInstances service method.</param> /// /// <returns>The response from the DescribeOrderableReplicationInstances service method, as returned by DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeOrderableReplicationInstances">REST API Reference for DescribeOrderableReplicationInstances Operation</seealso> public virtual DescribeOrderableReplicationInstancesResponse DescribeOrderableReplicationInstances(DescribeOrderableReplicationInstancesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeOrderableReplicationInstancesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeOrderableReplicationInstancesResponseUnmarshaller.Instance; return Invoke<DescribeOrderableReplicationInstancesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeOrderableReplicationInstances operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeOrderableReplicationInstances operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeOrderableReplicationInstances /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeOrderableReplicationInstances">REST API Reference for DescribeOrderableReplicationInstances Operation</seealso> public virtual IAsyncResult BeginDescribeOrderableReplicationInstances(DescribeOrderableReplicationInstancesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeOrderableReplicationInstancesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeOrderableReplicationInstancesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeOrderableReplicationInstances operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeOrderableReplicationInstances.</param> /// /// <returns>Returns a DescribeOrderableReplicationInstancesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeOrderableReplicationInstances">REST API Reference for DescribeOrderableReplicationInstances Operation</seealso> public virtual DescribeOrderableReplicationInstancesResponse EndDescribeOrderableReplicationInstances(IAsyncResult asyncResult) { return EndInvoke<DescribeOrderableReplicationInstancesResponse>(asyncResult); } #endregion #region DescribePendingMaintenanceActions /// <summary> /// For internal use only /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribePendingMaintenanceActions service method.</param> /// /// <returns>The response from the DescribePendingMaintenanceActions service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribePendingMaintenanceActions">REST API Reference for DescribePendingMaintenanceActions Operation</seealso> public virtual DescribePendingMaintenanceActionsResponse DescribePendingMaintenanceActions(DescribePendingMaintenanceActionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribePendingMaintenanceActionsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribePendingMaintenanceActionsResponseUnmarshaller.Instance; return Invoke<DescribePendingMaintenanceActionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribePendingMaintenanceActions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribePendingMaintenanceActions operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribePendingMaintenanceActions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribePendingMaintenanceActions">REST API Reference for DescribePendingMaintenanceActions Operation</seealso> public virtual IAsyncResult BeginDescribePendingMaintenanceActions(DescribePendingMaintenanceActionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribePendingMaintenanceActionsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribePendingMaintenanceActionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribePendingMaintenanceActions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribePendingMaintenanceActions.</param> /// /// <returns>Returns a DescribePendingMaintenanceActionsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribePendingMaintenanceActions">REST API Reference for DescribePendingMaintenanceActions Operation</seealso> public virtual DescribePendingMaintenanceActionsResponse EndDescribePendingMaintenanceActions(IAsyncResult asyncResult) { return EndInvoke<DescribePendingMaintenanceActionsResponse>(asyncResult); } #endregion #region DescribeRefreshSchemasStatus /// <summary> /// Returns the status of the RefreshSchemas operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeRefreshSchemasStatus service method.</param> /// /// <returns>The response from the DescribeRefreshSchemasStatus service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeRefreshSchemasStatus">REST API Reference for DescribeRefreshSchemasStatus Operation</seealso> public virtual DescribeRefreshSchemasStatusResponse DescribeRefreshSchemasStatus(DescribeRefreshSchemasStatusRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeRefreshSchemasStatusRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeRefreshSchemasStatusResponseUnmarshaller.Instance; return Invoke<DescribeRefreshSchemasStatusResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeRefreshSchemasStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeRefreshSchemasStatus operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeRefreshSchemasStatus /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeRefreshSchemasStatus">REST API Reference for DescribeRefreshSchemasStatus Operation</seealso> public virtual IAsyncResult BeginDescribeRefreshSchemasStatus(DescribeRefreshSchemasStatusRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeRefreshSchemasStatusRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeRefreshSchemasStatusResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeRefreshSchemasStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeRefreshSchemasStatus.</param> /// /// <returns>Returns a DescribeRefreshSchemasStatusResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeRefreshSchemasStatus">REST API Reference for DescribeRefreshSchemasStatus Operation</seealso> public virtual DescribeRefreshSchemasStatusResponse EndDescribeRefreshSchemasStatus(IAsyncResult asyncResult) { return EndInvoke<DescribeRefreshSchemasStatusResponse>(asyncResult); } #endregion #region DescribeReplicationInstances /// <summary> /// Returns information about replication instances for your account in the current region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationInstances service method.</param> /// /// <returns>The response from the DescribeReplicationInstances service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstances">REST API Reference for DescribeReplicationInstances Operation</seealso> public virtual DescribeReplicationInstancesResponse DescribeReplicationInstances(DescribeReplicationInstancesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationInstancesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationInstancesResponseUnmarshaller.Instance; return Invoke<DescribeReplicationInstancesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationInstances operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationInstances operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationInstances /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstances">REST API Reference for DescribeReplicationInstances Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationInstances(DescribeReplicationInstancesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationInstancesRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationInstancesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationInstances operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationInstances.</param> /// /// <returns>Returns a DescribeReplicationInstancesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstances">REST API Reference for DescribeReplicationInstances Operation</seealso> public virtual DescribeReplicationInstancesResponse EndDescribeReplicationInstances(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationInstancesResponse>(asyncResult); } #endregion #region DescribeReplicationInstanceTaskLogs /// <summary> /// Returns information about the task logs for the specified task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationInstanceTaskLogs service method.</param> /// /// <returns>The response from the DescribeReplicationInstanceTaskLogs service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstanceTaskLogs">REST API Reference for DescribeReplicationInstanceTaskLogs Operation</seealso> public virtual DescribeReplicationInstanceTaskLogsResponse DescribeReplicationInstanceTaskLogs(DescribeReplicationInstanceTaskLogsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationInstanceTaskLogsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationInstanceTaskLogsResponseUnmarshaller.Instance; return Invoke<DescribeReplicationInstanceTaskLogsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationInstanceTaskLogs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationInstanceTaskLogs operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationInstanceTaskLogs /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstanceTaskLogs">REST API Reference for DescribeReplicationInstanceTaskLogs Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationInstanceTaskLogs(DescribeReplicationInstanceTaskLogsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationInstanceTaskLogsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationInstanceTaskLogsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationInstanceTaskLogs operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationInstanceTaskLogs.</param> /// /// <returns>Returns a DescribeReplicationInstanceTaskLogsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationInstanceTaskLogs">REST API Reference for DescribeReplicationInstanceTaskLogs Operation</seealso> public virtual DescribeReplicationInstanceTaskLogsResponse EndDescribeReplicationInstanceTaskLogs(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationInstanceTaskLogsResponse>(asyncResult); } #endregion #region DescribeReplicationSubnetGroups /// <summary> /// Returns information about the replication subnet groups. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationSubnetGroups service method.</param> /// /// <returns>The response from the DescribeReplicationSubnetGroups service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationSubnetGroups">REST API Reference for DescribeReplicationSubnetGroups Operation</seealso> public virtual DescribeReplicationSubnetGroupsResponse DescribeReplicationSubnetGroups(DescribeReplicationSubnetGroupsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationSubnetGroupsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationSubnetGroupsResponseUnmarshaller.Instance; return Invoke<DescribeReplicationSubnetGroupsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationSubnetGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationSubnetGroups operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationSubnetGroups /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationSubnetGroups">REST API Reference for DescribeReplicationSubnetGroups Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationSubnetGroups(DescribeReplicationSubnetGroupsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationSubnetGroupsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationSubnetGroupsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationSubnetGroups operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationSubnetGroups.</param> /// /// <returns>Returns a DescribeReplicationSubnetGroupsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationSubnetGroups">REST API Reference for DescribeReplicationSubnetGroups Operation</seealso> public virtual DescribeReplicationSubnetGroupsResponse EndDescribeReplicationSubnetGroups(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationSubnetGroupsResponse>(asyncResult); } #endregion #region DescribeReplicationTaskAssessmentResults /// <summary> /// Returns the task assessment results from Amazon S3. This action always returns the /// latest results. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTaskAssessmentResults service method.</param> /// /// <returns>The response from the DescribeReplicationTaskAssessmentResults service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentResults">REST API Reference for DescribeReplicationTaskAssessmentResults Operation</seealso> public virtual DescribeReplicationTaskAssessmentResultsResponse DescribeReplicationTaskAssessmentResults(DescribeReplicationTaskAssessmentResultsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTaskAssessmentResultsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTaskAssessmentResultsResponseUnmarshaller.Instance; return Invoke<DescribeReplicationTaskAssessmentResultsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationTaskAssessmentResults operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTaskAssessmentResults operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationTaskAssessmentResults /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentResults">REST API Reference for DescribeReplicationTaskAssessmentResults Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationTaskAssessmentResults(DescribeReplicationTaskAssessmentResultsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTaskAssessmentResultsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTaskAssessmentResultsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationTaskAssessmentResults operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationTaskAssessmentResults.</param> /// /// <returns>Returns a DescribeReplicationTaskAssessmentResultsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentResults">REST API Reference for DescribeReplicationTaskAssessmentResults Operation</seealso> public virtual DescribeReplicationTaskAssessmentResultsResponse EndDescribeReplicationTaskAssessmentResults(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationTaskAssessmentResultsResponse>(asyncResult); } #endregion #region DescribeReplicationTaskAssessmentRuns /// <summary> /// Returns a paginated list of premigration assessment runs based on filter settings. /// /// /// <para> /// These filter settings can specify a combination of premigration assessment runs, migration /// tasks, replication instances, and assessment run status values. /// </para> /// <note> /// <para> /// This operation doesn't return information about individual assessments. For this information, /// see the <code>DescribeReplicationTaskIndividualAssessments</code> operation. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTaskAssessmentRuns service method.</param> /// /// <returns>The response from the DescribeReplicationTaskAssessmentRuns service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentRuns">REST API Reference for DescribeReplicationTaskAssessmentRuns Operation</seealso> public virtual DescribeReplicationTaskAssessmentRunsResponse DescribeReplicationTaskAssessmentRuns(DescribeReplicationTaskAssessmentRunsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTaskAssessmentRunsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTaskAssessmentRunsResponseUnmarshaller.Instance; return Invoke<DescribeReplicationTaskAssessmentRunsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationTaskAssessmentRuns operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTaskAssessmentRuns operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationTaskAssessmentRuns /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentRuns">REST API Reference for DescribeReplicationTaskAssessmentRuns Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationTaskAssessmentRuns(DescribeReplicationTaskAssessmentRunsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTaskAssessmentRunsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTaskAssessmentRunsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationTaskAssessmentRuns operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationTaskAssessmentRuns.</param> /// /// <returns>Returns a DescribeReplicationTaskAssessmentRunsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentRuns">REST API Reference for DescribeReplicationTaskAssessmentRuns Operation</seealso> public virtual DescribeReplicationTaskAssessmentRunsResponse EndDescribeReplicationTaskAssessmentRuns(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationTaskAssessmentRunsResponse>(asyncResult); } #endregion #region DescribeReplicationTaskIndividualAssessments /// <summary> /// Returns a paginated list of individual assessments based on filter settings. /// /// /// <para> /// These filter settings can specify a combination of premigration assessment runs, migration /// tasks, and assessment status values. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTaskIndividualAssessments service method.</param> /// /// <returns>The response from the DescribeReplicationTaskIndividualAssessments service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskIndividualAssessments">REST API Reference for DescribeReplicationTaskIndividualAssessments Operation</seealso> public virtual DescribeReplicationTaskIndividualAssessmentsResponse DescribeReplicationTaskIndividualAssessments(DescribeReplicationTaskIndividualAssessmentsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTaskIndividualAssessmentsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTaskIndividualAssessmentsResponseUnmarshaller.Instance; return Invoke<DescribeReplicationTaskIndividualAssessmentsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationTaskIndividualAssessments operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTaskIndividualAssessments operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationTaskIndividualAssessments /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskIndividualAssessments">REST API Reference for DescribeReplicationTaskIndividualAssessments Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationTaskIndividualAssessments(DescribeReplicationTaskIndividualAssessmentsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTaskIndividualAssessmentsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTaskIndividualAssessmentsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationTaskIndividualAssessments operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationTaskIndividualAssessments.</param> /// /// <returns>Returns a DescribeReplicationTaskIndividualAssessmentsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskIndividualAssessments">REST API Reference for DescribeReplicationTaskIndividualAssessments Operation</seealso> public virtual DescribeReplicationTaskIndividualAssessmentsResponse EndDescribeReplicationTaskIndividualAssessments(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationTaskIndividualAssessmentsResponse>(asyncResult); } #endregion #region DescribeReplicationTasks /// <summary> /// Returns information about replication tasks for your account in the current region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTasks service method.</param> /// /// <returns>The response from the DescribeReplicationTasks service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks">REST API Reference for DescribeReplicationTasks Operation</seealso> public virtual DescribeReplicationTasksResponse DescribeReplicationTasks(DescribeReplicationTasksRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTasksRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTasksResponseUnmarshaller.Instance; return Invoke<DescribeReplicationTasksResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationTasks operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeReplicationTasks /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks">REST API Reference for DescribeReplicationTasks Operation</seealso> public virtual IAsyncResult BeginDescribeReplicationTasks(DescribeReplicationTasksRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeReplicationTasksRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeReplicationTasksResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeReplicationTasks operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeReplicationTasks.</param> /// /// <returns>Returns a DescribeReplicationTasksResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks">REST API Reference for DescribeReplicationTasks Operation</seealso> public virtual DescribeReplicationTasksResponse EndDescribeReplicationTasks(IAsyncResult asyncResult) { return EndInvoke<DescribeReplicationTasksResponse>(asyncResult); } #endregion #region DescribeSchemas /// <summary> /// Returns information about the schema for the specified endpoint. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeSchemas service method.</param> /// /// <returns>The response from the DescribeSchemas service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeSchemas">REST API Reference for DescribeSchemas Operation</seealso> public virtual DescribeSchemasResponse DescribeSchemas(DescribeSchemasRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeSchemasRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeSchemasResponseUnmarshaller.Instance; return Invoke<DescribeSchemasResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeSchemas operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSchemas operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeSchemas /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeSchemas">REST API Reference for DescribeSchemas Operation</seealso> public virtual IAsyncResult BeginDescribeSchemas(DescribeSchemasRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeSchemasRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeSchemasResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeSchemas operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeSchemas.</param> /// /// <returns>Returns a DescribeSchemasResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeSchemas">REST API Reference for DescribeSchemas Operation</seealso> public virtual DescribeSchemasResponse EndDescribeSchemas(IAsyncResult asyncResult) { return EndInvoke<DescribeSchemasResponse>(asyncResult); } #endregion #region DescribeTableStatistics /// <summary> /// Returns table statistics on the database migration task, including table name, rows /// inserted, rows updated, and rows deleted. /// /// /// <para> /// Note that the "last updated" column the DMS console only indicates the time that AWS /// DMS last updated the table statistics record for a table. It does not indicate the /// time of the last update to the table. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTableStatistics service method.</param> /// /// <returns>The response from the DescribeTableStatistics service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeTableStatistics">REST API Reference for DescribeTableStatistics Operation</seealso> public virtual DescribeTableStatisticsResponse DescribeTableStatistics(DescribeTableStatisticsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTableStatisticsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTableStatisticsResponseUnmarshaller.Instance; return Invoke<DescribeTableStatisticsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DescribeTableStatistics operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeTableStatistics operation on AmazonDatabaseMigrationServiceClient.</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 EndDescribeTableStatistics /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeTableStatistics">REST API Reference for DescribeTableStatistics Operation</seealso> public virtual IAsyncResult BeginDescribeTableStatistics(DescribeTableStatisticsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTableStatisticsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTableStatisticsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DescribeTableStatistics operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeTableStatistics.</param> /// /// <returns>Returns a DescribeTableStatisticsResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeTableStatistics">REST API Reference for DescribeTableStatistics Operation</seealso> public virtual DescribeTableStatisticsResponse EndDescribeTableStatistics(IAsyncResult asyncResult) { return EndInvoke<DescribeTableStatisticsResponse>(asyncResult); } #endregion #region ImportCertificate /// <summary> /// Uploads the specified certificate. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ImportCertificate service method.</param> /// /// <returns>The response from the ImportCertificate service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidCertificateException"> /// The certificate was not valid. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ImportCertificate">REST API Reference for ImportCertificate Operation</seealso> public virtual ImportCertificateResponse ImportCertificate(ImportCertificateRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ImportCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = ImportCertificateResponseUnmarshaller.Instance; return Invoke<ImportCertificateResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ImportCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ImportCertificate operation on AmazonDatabaseMigrationServiceClient.</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 EndImportCertificate /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ImportCertificate">REST API Reference for ImportCertificate Operation</seealso> public virtual IAsyncResult BeginImportCertificate(ImportCertificateRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ImportCertificateRequestMarshaller.Instance; options.ResponseUnmarshaller = ImportCertificateResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ImportCertificate operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginImportCertificate.</param> /// /// <returns>Returns a ImportCertificateResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ImportCertificate">REST API Reference for ImportCertificate Operation</seealso> public virtual ImportCertificateResponse EndImportCertificate(IAsyncResult asyncResult) { return EndInvoke<ImportCertificateResponse>(asyncResult); } #endregion #region ListTagsForResource /// <summary> /// Lists all metadata tags attached to an AWS DMS resource, including replication instance, /// endpoint, security group, and migration task. For more information, see <a href="https://docs.aws.amazon.com/dms/latest/APIReference/API_Tag.html"> /// <code>Tag</code> </a> data type description. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// /// <returns>The response from the ListTagsForResource service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return Invoke<ListTagsForResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonDatabaseMigrationServiceClient.</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 EndListTagsForResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param> /// /// <returns>Returns a ListTagsForResourceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult) { return EndInvoke<ListTagsForResourceResponse>(asyncResult); } #endregion #region ModifyEndpoint /// <summary> /// Modifies the specified endpoint. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyEndpoint service method.</param> /// /// <returns>The response from the ModifyEndpoint service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEndpoint">REST API Reference for ModifyEndpoint Operation</seealso> public virtual ModifyEndpointResponse ModifyEndpoint(ModifyEndpointRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyEndpointResponseUnmarshaller.Instance; return Invoke<ModifyEndpointResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ModifyEndpoint operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyEndpoint operation on AmazonDatabaseMigrationServiceClient.</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 EndModifyEndpoint /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEndpoint">REST API Reference for ModifyEndpoint Operation</seealso> public virtual IAsyncResult BeginModifyEndpoint(ModifyEndpointRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyEndpointRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyEndpointResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ModifyEndpoint operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginModifyEndpoint.</param> /// /// <returns>Returns a ModifyEndpointResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEndpoint">REST API Reference for ModifyEndpoint Operation</seealso> public virtual ModifyEndpointResponse EndModifyEndpoint(IAsyncResult asyncResult) { return EndInvoke<ModifyEndpointResponse>(asyncResult); } #endregion #region ModifyEventSubscription /// <summary> /// Modifies an existing AWS DMS event notification subscription. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyEventSubscription service method.</param> /// /// <returns>The response from the ModifyEventSubscription service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSAccessDeniedException"> /// The ciphertext references a key that doesn't exist or that the DMS account doesn't /// have access to. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSDisabledException"> /// The specified master key (CMK) isn't enabled. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSInvalidStateException"> /// The state of the specified AWS KMS resource isn't valid for this request. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSNotFoundException"> /// The specified AWS KMS entity or resource can't be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSThrottlingException"> /// This request triggered AWS KMS request throttling. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.SNSInvalidTopicException"> /// The SNS topic is invalid. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.SNSNoAuthorizationException"> /// You are not authorized for the SNS subscription. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEventSubscription">REST API Reference for ModifyEventSubscription Operation</seealso> public virtual ModifyEventSubscriptionResponse ModifyEventSubscription(ModifyEventSubscriptionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyEventSubscriptionRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyEventSubscriptionResponseUnmarshaller.Instance; return Invoke<ModifyEventSubscriptionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ModifyEventSubscription operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyEventSubscription operation on AmazonDatabaseMigrationServiceClient.</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 EndModifyEventSubscription /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEventSubscription">REST API Reference for ModifyEventSubscription Operation</seealso> public virtual IAsyncResult BeginModifyEventSubscription(ModifyEventSubscriptionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyEventSubscriptionRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyEventSubscriptionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ModifyEventSubscription operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginModifyEventSubscription.</param> /// /// <returns>Returns a ModifyEventSubscriptionResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyEventSubscription">REST API Reference for ModifyEventSubscription Operation</seealso> public virtual ModifyEventSubscriptionResponse EndModifyEventSubscription(IAsyncResult asyncResult) { return EndInvoke<ModifyEventSubscriptionResponse>(asyncResult); } #endregion #region ModifyReplicationInstance /// <summary> /// Modifies the replication instance to apply new settings. You can change one or more /// parameters by specifying these parameters and the new values in the request. /// /// /// <para> /// Some settings are applied during the maintenance window. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationInstance service method.</param> /// /// <returns>The response from the ModifyReplicationInstance service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InsufficientResourceCapacityException"> /// There are not enough resources allocated to the database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.StorageQuotaExceededException"> /// The storage quota has been exceeded. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.UpgradeDependencyFailureException"> /// An upgrade dependency is preventing the database migration. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationInstance">REST API Reference for ModifyReplicationInstance Operation</seealso> public virtual ModifyReplicationInstanceResponse ModifyReplicationInstance(ModifyReplicationInstanceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyReplicationInstanceResponseUnmarshaller.Instance; return Invoke<ModifyReplicationInstanceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ModifyReplicationInstance operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationInstance operation on AmazonDatabaseMigrationServiceClient.</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 EndModifyReplicationInstance /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationInstance">REST API Reference for ModifyReplicationInstance Operation</seealso> public virtual IAsyncResult BeginModifyReplicationInstance(ModifyReplicationInstanceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyReplicationInstanceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ModifyReplicationInstance operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginModifyReplicationInstance.</param> /// /// <returns>Returns a ModifyReplicationInstanceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationInstance">REST API Reference for ModifyReplicationInstance Operation</seealso> public virtual ModifyReplicationInstanceResponse EndModifyReplicationInstance(IAsyncResult asyncResult) { return EndInvoke<ModifyReplicationInstanceResponse>(asyncResult); } #endregion #region ModifyReplicationSubnetGroup /// <summary> /// Modifies the settings for the specified replication subnet group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationSubnetGroup service method.</param> /// /// <returns>The response from the ModifyReplicationSubnetGroup service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidSubnetException"> /// The subnet provided is invalid. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ReplicationSubnetGroupDoesNotCoverEnoughAZsException"> /// The replication subnet group does not cover enough Availability Zones (AZs). Edit /// the replication subnet group and add more AZs. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.SubnetAlreadyInUseException"> /// The specified subnet is already in use. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationSubnetGroup">REST API Reference for ModifyReplicationSubnetGroup Operation</seealso> public virtual ModifyReplicationSubnetGroupResponse ModifyReplicationSubnetGroup(ModifyReplicationSubnetGroupRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyReplicationSubnetGroupRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyReplicationSubnetGroupResponseUnmarshaller.Instance; return Invoke<ModifyReplicationSubnetGroupResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ModifyReplicationSubnetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationSubnetGroup operation on AmazonDatabaseMigrationServiceClient.</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 EndModifyReplicationSubnetGroup /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationSubnetGroup">REST API Reference for ModifyReplicationSubnetGroup Operation</seealso> public virtual IAsyncResult BeginModifyReplicationSubnetGroup(ModifyReplicationSubnetGroupRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyReplicationSubnetGroupRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyReplicationSubnetGroupResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ModifyReplicationSubnetGroup operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginModifyReplicationSubnetGroup.</param> /// /// <returns>Returns a ModifyReplicationSubnetGroupResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationSubnetGroup">REST API Reference for ModifyReplicationSubnetGroup Operation</seealso> public virtual ModifyReplicationSubnetGroupResponse EndModifyReplicationSubnetGroup(IAsyncResult asyncResult) { return EndInvoke<ModifyReplicationSubnetGroupResponse>(asyncResult); } #endregion #region ModifyReplicationTask /// <summary> /// Modifies the specified replication task. /// /// /// <para> /// You can't modify the task endpoints. The task must be stopped before you can modify /// it. /// </para> /// /// <para> /// For more information about AWS DMS tasks, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html">Working /// with Migration Tasks</a> in the <i>AWS Database Migration Service User Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationTask service method.</param> /// /// <returns>The response from the ModifyReplicationTask service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationTask">REST API Reference for ModifyReplicationTask Operation</seealso> public virtual ModifyReplicationTaskResponse ModifyReplicationTask(ModifyReplicationTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyReplicationTaskResponseUnmarshaller.Instance; return Invoke<ModifyReplicationTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ModifyReplicationTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationTask operation on AmazonDatabaseMigrationServiceClient.</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 EndModifyReplicationTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationTask">REST API Reference for ModifyReplicationTask Operation</seealso> public virtual IAsyncResult BeginModifyReplicationTask(ModifyReplicationTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ModifyReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = ModifyReplicationTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ModifyReplicationTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginModifyReplicationTask.</param> /// /// <returns>Returns a ModifyReplicationTaskResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ModifyReplicationTask">REST API Reference for ModifyReplicationTask Operation</seealso> public virtual ModifyReplicationTaskResponse EndModifyReplicationTask(IAsyncResult asyncResult) { return EndInvoke<ModifyReplicationTaskResponse>(asyncResult); } #endregion #region MoveReplicationTask /// <summary> /// Moves a replication task from its current replication instance to a different target /// replication instance using the specified parameters. The target replication instance /// must be created with the same or later AWS DMS version as the current replication /// instance. /// </summary> /// <param name="request">Container for the necessary parameters to execute the MoveReplicationTask service method.</param> /// /// <returns>The response from the MoveReplicationTask service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/MoveReplicationTask">REST API Reference for MoveReplicationTask Operation</seealso> public virtual MoveReplicationTaskResponse MoveReplicationTask(MoveReplicationTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = MoveReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = MoveReplicationTaskResponseUnmarshaller.Instance; return Invoke<MoveReplicationTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the MoveReplicationTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the MoveReplicationTask operation on AmazonDatabaseMigrationServiceClient.</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 EndMoveReplicationTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/MoveReplicationTask">REST API Reference for MoveReplicationTask Operation</seealso> public virtual IAsyncResult BeginMoveReplicationTask(MoveReplicationTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = MoveReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = MoveReplicationTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the MoveReplicationTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginMoveReplicationTask.</param> /// /// <returns>Returns a MoveReplicationTaskResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/MoveReplicationTask">REST API Reference for MoveReplicationTask Operation</seealso> public virtual MoveReplicationTaskResponse EndMoveReplicationTask(IAsyncResult asyncResult) { return EndInvoke<MoveReplicationTaskResponse>(asyncResult); } #endregion #region RebootReplicationInstance /// <summary> /// Reboots a replication instance. Rebooting results in a momentary outage, until the /// replication instance becomes available again. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RebootReplicationInstance service method.</param> /// /// <returns>The response from the RebootReplicationInstance service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RebootReplicationInstance">REST API Reference for RebootReplicationInstance Operation</seealso> public virtual RebootReplicationInstanceResponse RebootReplicationInstance(RebootReplicationInstanceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = RebootReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = RebootReplicationInstanceResponseUnmarshaller.Instance; return Invoke<RebootReplicationInstanceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the RebootReplicationInstance operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RebootReplicationInstance operation on AmazonDatabaseMigrationServiceClient.</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 EndRebootReplicationInstance /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RebootReplicationInstance">REST API Reference for RebootReplicationInstance Operation</seealso> public virtual IAsyncResult BeginRebootReplicationInstance(RebootReplicationInstanceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = RebootReplicationInstanceRequestMarshaller.Instance; options.ResponseUnmarshaller = RebootReplicationInstanceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the RebootReplicationInstance operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRebootReplicationInstance.</param> /// /// <returns>Returns a RebootReplicationInstanceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RebootReplicationInstance">REST API Reference for RebootReplicationInstance Operation</seealso> public virtual RebootReplicationInstanceResponse EndRebootReplicationInstance(IAsyncResult asyncResult) { return EndInvoke<RebootReplicationInstanceResponse>(asyncResult); } #endregion #region RefreshSchemas /// <summary> /// Populates the schema for the specified endpoint. This is an asynchronous operation /// and can take several minutes. You can check the status of this operation by calling /// the DescribeRefreshSchemasStatus operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RefreshSchemas service method.</param> /// /// <returns>The response from the RefreshSchemas service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RefreshSchemas">REST API Reference for RefreshSchemas Operation</seealso> public virtual RefreshSchemasResponse RefreshSchemas(RefreshSchemasRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = RefreshSchemasRequestMarshaller.Instance; options.ResponseUnmarshaller = RefreshSchemasResponseUnmarshaller.Instance; return Invoke<RefreshSchemasResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the RefreshSchemas operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RefreshSchemas operation on AmazonDatabaseMigrationServiceClient.</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 EndRefreshSchemas /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RefreshSchemas">REST API Reference for RefreshSchemas Operation</seealso> public virtual IAsyncResult BeginRefreshSchemas(RefreshSchemasRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = RefreshSchemasRequestMarshaller.Instance; options.ResponseUnmarshaller = RefreshSchemasResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the RefreshSchemas operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRefreshSchemas.</param> /// /// <returns>Returns a RefreshSchemasResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RefreshSchemas">REST API Reference for RefreshSchemas Operation</seealso> public virtual RefreshSchemasResponse EndRefreshSchemas(IAsyncResult asyncResult) { return EndInvoke<RefreshSchemasResponse>(asyncResult); } #endregion #region ReloadTables /// <summary> /// Reloads the target database table with the source data. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ReloadTables service method.</param> /// /// <returns>The response from the ReloadTables service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ReloadTables">REST API Reference for ReloadTables Operation</seealso> public virtual ReloadTablesResponse ReloadTables(ReloadTablesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ReloadTablesRequestMarshaller.Instance; options.ResponseUnmarshaller = ReloadTablesResponseUnmarshaller.Instance; return Invoke<ReloadTablesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ReloadTables operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReloadTables operation on AmazonDatabaseMigrationServiceClient.</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 EndReloadTables /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ReloadTables">REST API Reference for ReloadTables Operation</seealso> public virtual IAsyncResult BeginReloadTables(ReloadTablesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ReloadTablesRequestMarshaller.Instance; options.ResponseUnmarshaller = ReloadTablesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ReloadTables operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginReloadTables.</param> /// /// <returns>Returns a ReloadTablesResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/ReloadTables">REST API Reference for ReloadTables Operation</seealso> public virtual ReloadTablesResponse EndReloadTables(IAsyncResult asyncResult) { return EndInvoke<ReloadTablesResponse>(asyncResult); } #endregion #region RemoveTagsFromResource /// <summary> /// Removes metadata tags from an AWS DMS resource, including replication instance, endpoint, /// security group, and migration task. For more information, see <a href="https://docs.aws.amazon.com/dms/latest/APIReference/API_Tag.html"> /// <code>Tag</code> </a> data type description. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromResource service method.</param> /// /// <returns>The response from the RemoveTagsFromResource service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RemoveTagsFromResource">REST API Reference for RemoveTagsFromResource Operation</seealso> public virtual RemoveTagsFromResourceResponse RemoveTagsFromResource(RemoveTagsFromResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = RemoveTagsFromResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = RemoveTagsFromResourceResponseUnmarshaller.Instance; return Invoke<RemoveTagsFromResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the RemoveTagsFromResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromResource operation on AmazonDatabaseMigrationServiceClient.</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 EndRemoveTagsFromResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RemoveTagsFromResource">REST API Reference for RemoveTagsFromResource Operation</seealso> public virtual IAsyncResult BeginRemoveTagsFromResource(RemoveTagsFromResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = RemoveTagsFromResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = RemoveTagsFromResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the RemoveTagsFromResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRemoveTagsFromResource.</param> /// /// <returns>Returns a RemoveTagsFromResourceResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/RemoveTagsFromResource">REST API Reference for RemoveTagsFromResource Operation</seealso> public virtual RemoveTagsFromResourceResponse EndRemoveTagsFromResource(IAsyncResult asyncResult) { return EndInvoke<RemoveTagsFromResourceResponse>(asyncResult); } #endregion #region StartReplicationTask /// <summary> /// Starts the replication task. /// /// /// <para> /// For more information about AWS DMS tasks, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html">Working /// with Migration Tasks </a> in the <i>AWS Database Migration Service User Guide.</i> /// /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartReplicationTask service method.</param> /// /// <returns>The response from the StartReplicationTask service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTask">REST API Reference for StartReplicationTask Operation</seealso> public virtual StartReplicationTaskResponse StartReplicationTask(StartReplicationTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = StartReplicationTaskResponseUnmarshaller.Instance; return Invoke<StartReplicationTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartReplicationTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartReplicationTask operation on AmazonDatabaseMigrationServiceClient.</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 EndStartReplicationTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTask">REST API Reference for StartReplicationTask Operation</seealso> public virtual IAsyncResult BeginStartReplicationTask(StartReplicationTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = StartReplicationTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartReplicationTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartReplicationTask.</param> /// /// <returns>Returns a StartReplicationTaskResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTask">REST API Reference for StartReplicationTask Operation</seealso> public virtual StartReplicationTaskResponse EndStartReplicationTask(IAsyncResult asyncResult) { return EndInvoke<StartReplicationTaskResponse>(asyncResult); } #endregion #region StartReplicationTaskAssessment /// <summary> /// Starts the replication task assessment for unsupported data types in the source database. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartReplicationTaskAssessment service method.</param> /// /// <returns>The response from the StartReplicationTaskAssessment service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessment">REST API Reference for StartReplicationTaskAssessment Operation</seealso> public virtual StartReplicationTaskAssessmentResponse StartReplicationTaskAssessment(StartReplicationTaskAssessmentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartReplicationTaskAssessmentRequestMarshaller.Instance; options.ResponseUnmarshaller = StartReplicationTaskAssessmentResponseUnmarshaller.Instance; return Invoke<StartReplicationTaskAssessmentResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartReplicationTaskAssessment operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartReplicationTaskAssessment operation on AmazonDatabaseMigrationServiceClient.</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 EndStartReplicationTaskAssessment /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessment">REST API Reference for StartReplicationTaskAssessment Operation</seealso> public virtual IAsyncResult BeginStartReplicationTaskAssessment(StartReplicationTaskAssessmentRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartReplicationTaskAssessmentRequestMarshaller.Instance; options.ResponseUnmarshaller = StartReplicationTaskAssessmentResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartReplicationTaskAssessment operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartReplicationTaskAssessment.</param> /// /// <returns>Returns a StartReplicationTaskAssessmentResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessment">REST API Reference for StartReplicationTaskAssessment Operation</seealso> public virtual StartReplicationTaskAssessmentResponse EndStartReplicationTaskAssessment(IAsyncResult asyncResult) { return EndInvoke<StartReplicationTaskAssessmentResponse>(asyncResult); } #endregion #region StartReplicationTaskAssessmentRun /// <summary> /// Starts a new premigration assessment run for one or more individual assessments of /// a migration task. /// /// /// <para> /// The assessments that you can specify depend on the source and target database engine /// and the migration type defined for the given task. To run this operation, your migration /// task must already be created. After you run this operation, you can review the status /// of each individual assessment. You can also run the migration task manually after /// the assessment run and its individual assessments complete. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartReplicationTaskAssessmentRun service method.</param> /// /// <returns>The response from the StartReplicationTaskAssessmentRun service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.AccessDeniedException"> /// AWS DMS was denied access to the endpoint. Check that the role is correctly configured. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSAccessDeniedException"> /// The ciphertext references a key that doesn't exist or that the DMS account doesn't /// have access to. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSDisabledException"> /// The specified master key (CMK) isn't enabled. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSException"> /// An AWS Key Management Service (AWS KMS) error is preventing access to AWS KMS. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSInvalidStateException"> /// The state of the specified AWS KMS resource isn't valid for this request. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSNotFoundException"> /// The specified AWS KMS entity or resource can't be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceAlreadyExistsException"> /// The resource you are attempting to create already exists. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.S3AccessDeniedException"> /// Insufficient privileges are preventing access to an Amazon S3 object. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.S3ResourceNotFoundException"> /// A specified Amazon S3 bucket, bucket folder, or other object can't be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessmentRun">REST API Reference for StartReplicationTaskAssessmentRun Operation</seealso> public virtual StartReplicationTaskAssessmentRunResponse StartReplicationTaskAssessmentRun(StartReplicationTaskAssessmentRunRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartReplicationTaskAssessmentRunRequestMarshaller.Instance; options.ResponseUnmarshaller = StartReplicationTaskAssessmentRunResponseUnmarshaller.Instance; return Invoke<StartReplicationTaskAssessmentRunResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartReplicationTaskAssessmentRun operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartReplicationTaskAssessmentRun operation on AmazonDatabaseMigrationServiceClient.</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 EndStartReplicationTaskAssessmentRun /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessmentRun">REST API Reference for StartReplicationTaskAssessmentRun Operation</seealso> public virtual IAsyncResult BeginStartReplicationTaskAssessmentRun(StartReplicationTaskAssessmentRunRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartReplicationTaskAssessmentRunRequestMarshaller.Instance; options.ResponseUnmarshaller = StartReplicationTaskAssessmentRunResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartReplicationTaskAssessmentRun operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartReplicationTaskAssessmentRun.</param> /// /// <returns>Returns a StartReplicationTaskAssessmentRunResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessmentRun">REST API Reference for StartReplicationTaskAssessmentRun Operation</seealso> public virtual StartReplicationTaskAssessmentRunResponse EndStartReplicationTaskAssessmentRun(IAsyncResult asyncResult) { return EndInvoke<StartReplicationTaskAssessmentRunResponse>(asyncResult); } #endregion #region StopReplicationTask /// <summary> /// Stops the replication task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopReplicationTask service method.</param> /// /// <returns>The response from the StopReplicationTask service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTask">REST API Reference for StopReplicationTask Operation</seealso> public virtual StopReplicationTaskResponse StopReplicationTask(StopReplicationTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StopReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = StopReplicationTaskResponseUnmarshaller.Instance; return Invoke<StopReplicationTaskResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StopReplicationTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopReplicationTask operation on AmazonDatabaseMigrationServiceClient.</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 EndStopReplicationTask /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTask">REST API Reference for StopReplicationTask Operation</seealso> public virtual IAsyncResult BeginStopReplicationTask(StopReplicationTaskRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StopReplicationTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = StopReplicationTaskResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StopReplicationTask operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStopReplicationTask.</param> /// /// <returns>Returns a StopReplicationTaskResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTask">REST API Reference for StopReplicationTask Operation</seealso> public virtual StopReplicationTaskResponse EndStopReplicationTask(IAsyncResult asyncResult) { return EndInvoke<StopReplicationTaskResponse>(asyncResult); } #endregion #region TestConnection /// <summary> /// Tests the connection between the replication instance and the endpoint. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TestConnection service method.</param> /// /// <returns>The response from the TestConnection service method, as returned by DatabaseMigrationService.</returns> /// <exception cref="Amazon.DatabaseMigrationService.Model.InvalidResourceStateException"> /// The resource is in a state that prevents it from being used for database migration. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.KMSKeyNotAccessibleException"> /// AWS DMS cannot access the AWS KMS key. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceNotFoundException"> /// The resource could not be found. /// </exception> /// <exception cref="Amazon.DatabaseMigrationService.Model.ResourceQuotaExceededException"> /// The quota for this resource quota has been exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/TestConnection">REST API Reference for TestConnection Operation</seealso> public virtual TestConnectionResponse TestConnection(TestConnectionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = TestConnectionRequestMarshaller.Instance; options.ResponseUnmarshaller = TestConnectionResponseUnmarshaller.Instance; return Invoke<TestConnectionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the TestConnection operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TestConnection operation on AmazonDatabaseMigrationServiceClient.</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 EndTestConnection /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/TestConnection">REST API Reference for TestConnection Operation</seealso> public virtual IAsyncResult BeginTestConnection(TestConnectionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = TestConnectionRequestMarshaller.Instance; options.ResponseUnmarshaller = TestConnectionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the TestConnection operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginTestConnection.</param> /// /// <returns>Returns a TestConnectionResult from DatabaseMigrationService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/TestConnection">REST API Reference for TestConnection Operation</seealso> public virtual TestConnectionResponse EndTestConnection(IAsyncResult asyncResult) { return EndInvoke<TestConnectionResponse>(asyncResult); } #endregion } }
62.361402
215
0.688225
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DatabaseMigrationService/Generated/_bcl35/AmazonDatabaseMigrationServiceClient.cs
238,470
C#
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Gremlin.Net.Process.Traversal { /// <summary> /// A language agnostic representation of <see cref="ITraversal" /> mutations. /// </summary> /// <remarks> /// Bytecode is simply a list of ordered instructions. /// Bytecode can be serialized between environments and machines by way of a GraphSON representation. /// Thus, Gremlin.Net can create bytecode in C# and ship it to Gremlin-Java for evaluation in Java. /// </remarks> public class Bytecode { private static readonly object[] EmptyArray = new object[0]; /// <summary> /// Initializes a new instance of the <see cref="Bytecode" /> class. /// </summary> public Bytecode() { } /// <summary> /// Initializes a new instance of the <see cref="Bytecode" /> class. /// </summary> /// <param name="byteCode">Already existing <see cref="Bytecode" /> that should be cloned.</param> public Bytecode(Bytecode byteCode) { SourceInstructions = new List<Instruction>(byteCode.SourceInstructions); StepInstructions = new List<Instruction>(byteCode.StepInstructions); } /// <summary> /// Gets the traversal source instructions. /// </summary> public List<Instruction> SourceInstructions { get; } = new List<Instruction>(); /// <summary> /// Gets the <see cref="ITraversal" /> instructions. /// </summary> public List<Instruction> StepInstructions { get; } = new List<Instruction>(); /// <summary> /// Add a traversal source instruction to the bytecode. /// </summary> /// <param name="sourceName">The traversal source method name (e.g. withSack()).</param> /// <param name="args">The traversal source method arguments.</param> public void AddSource(string sourceName, params object[] args) { SourceInstructions.Add(new Instruction(sourceName, FlattenArguments(args))); Bindings.Clear(); } /// <summary> /// Adds a <see cref="ITraversal" /> instruction to the bytecode. /// </summary> /// <param name="stepName">The traversal method name (e.g. out()).</param> /// <param name="args">The traversal method arguments.</param> public void AddStep(string stepName, params object[] args) { StepInstructions.Add(new Instruction(stepName, FlattenArguments(args))); Bindings.Clear(); } private object[] FlattenArguments(object[] arguments) { if (arguments.Length == 0) return EmptyArray; var flatArguments = new List<object>(); foreach (var arg in arguments) { if (arg is object[] objects) { flatArguments.AddRange(objects.Select(nestObject => ConvertArgument(nestObject, true))); } else { flatArguments.Add(ConvertArgument(arg, true)); } } return flatArguments.ToArray(); } private object ConvertArgument(object argument, bool searchBindings) { if (searchBindings) { var variable = Bindings.GetBoundVariable(argument); if (variable != null) return new Binding(variable, ConvertArgument(argument, false)); } if (null == argument) { return null; } if (IsDictionaryType(argument.GetType())) { var dict = new Dictionary<object, object>(); foreach (DictionaryEntry item in (IDictionary)argument) { dict[ConvertArgument(item.Key, true)] = ConvertArgument(item.Value, true); } return dict; } if (IsListType(argument.GetType())) { var list = new List<object>(((IList) argument).Count); list.AddRange(from object item in (IList) argument select ConvertArgument(item, true)); return list; } if (IsHashSetType(argument.GetType())) { var set = new HashSet<object>(); foreach (var item in (IEnumerable)argument) { set.Add(ConvertArgument(item, true)); } return set; } return argument; } private bool IsDictionaryType(Type type) { return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>); } private bool IsListType(Type type) { return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(List<>); } private bool IsHashSetType(Type type) { return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(HashSet<>); } } }
36.724551
109
0.575249
[ "Apache-2.0" ]
BourneW/tinkerpop
gremlin-dotnet/src/Gremlin.Net/Process/Traversal/Bytecode.cs
6,133
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace SuperGlue.Web.Output.Spark { public class EmbeddedTemplateSource : BaseTemplateSource { private readonly IEnumerable<Assembly> _assemblies; public EmbeddedTemplateSource(IEnumerable<Assembly> assemblies) { _assemblies = assemblies; } public override IEnumerable<Template> FindTemplates() { var resources = GetResourcesFromAssemblies(_assemblies); return resources.Select(x => GetTemplate(x, _assemblies)); } private static IEnumerable<EmbeddedResource> GetResourcesFromAssemblies(IEnumerable<Assembly> assemblies) { return assemblies.SelectMany(x => x.GetManifestResourceNames().Where(y => y.EndsWith(".spark")).Select(y => new EmbeddedResource(y, x))); } private static Template GetTemplate(EmbeddedResource resource, IEnumerable<Assembly> availableAssemblies) { Func<TextReader> getContentReader = () => { var stream = resource.Assembly.GetManifestResourceStream(resource.GetResourceName()); return new StreamReader(stream ?? new MemoryStream()); }; return new Template(resource.GetViewName(), resource.GetPath(), ".", FindModelType(getContentReader(), availableAssemblies), getContentReader); } private class EmbeddedResource { private readonly string _resourceName; public EmbeddedResource(string resourceName, Assembly assembly) { Assembly = assembly; _resourceName = resourceName; } public Assembly Assembly { get; } public string GetPath() { return _resourceName.Replace(GetViewName(), string.Empty); } public string GetViewName() { var splitted = _resourceName.Split('.'); return $"{splitted[splitted.Length - 2]}.{splitted.Last()}"; } public string GetResourceName() { return _resourceName; } } } }
30.376623
149
0.587431
[ "MIT" ]
MattiasJakobsson/Jajo.Web
src/SuperGlue.Web.Output.Spark/EmbeddedTemplateSource.cs
2,341
C#
using System.Collections; using System.Collections.Generic; using JetBrains.Annotations; using pdxpartyparrot.Core.Collections; using pdxpartyparrot.Core.Util; using UnityEngine; namespace pdxpartyparrot.Core { // TODO: when writing to disk - https://docs.unity3d.com/Manual/JSONSerialization.html public class SaveGameManager : SingletonBehavior<SaveGameManager> { [SerializeField] private string _saveFileName = "default.partyparrot"; [SerializeField] [ReadOnly] private bool _isSaving; public bool IsSaving => _isSaving; private readonly Dictionary<string, object> _data = new Dictionary<string, object>(); #region Get / Set Values public void SetValue(string key, object value) { _data[key] = value; } public void SetValue<T>(string key, T value) { _data[key] = value; } [CanBeNull] public object GetValue(string key) { return _data.GetOrDefault(key); } // NOTE: this isn't type checked, so it can crash if an invalid typecast is done [CanBeNull] public T GetValue<T>(string key) { return (T)_data.GetOrDefault(key); } #endregion public IEnumerator LoadSaveRoutine() { Debug.Log($"Loading save file '{_saveFileName}'..."); // TODO: read the save file yield break; } public void SaveAsync() { StartCoroutine(SaveRoutine()); } private IEnumerator SaveRoutine() { _isSaving = true; // TODO: write the save file _isSaving = false; yield break; } } }
23.368421
93
0.583333
[ "Apache-2.0" ]
pdxparrot/ggj2019
Assets/Scripts/Core/SaveGameManager.cs
1,778
C#
 namespace Core.CrossCuttingConcerns.Logging.NLog.Loggers { public class MsSqlLogger : LoggerServiceBase { public MsSqlLogger() : base("MsSqlLogger") { } } }
15.153846
56
0.619289
[ "MIT" ]
kurtbogan88/Sennedjem
Core/CrossCuttingConcerns/Logging/NLog/Loggers/MsSqlLogger.cs
199
C#
using System.ComponentModel; using GaiaProject.Common.Reflection; namespace GaiaProject.Engine.Enums { public enum FinalScoringTileType { [Description("Number of buildings that are part of a federations")] BuildingsInAFederation, [Description("Number of buildings on the map")] BuildingsOnTheMap, [Description("Number of different planet types")] KnownPlanetTypes, [Description("Number of colonized Gaia planets")] GaiaPlanets, [Description("Number of sectors with at least 1 colonized planet")] Sectors, [Description("Number of satellites used to form federations")] Satellites } public static partial class EnumFormatters { public static string ToDescription(this FinalScoringTileType o) { return o.GetAttributeOfType<DescriptionAttribute>()?.Description ?? o.ToString(); } } }
24.264706
84
0.763636
[ "MIT" ]
Etchelon/gaiaproject
Backend/Libraries/Engine/Enums/FinalScoringTileType.cs
825
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UnityStandardAssets.Utility { public class ObjectResetter : MonoBehaviour { private Vector3 originalPosition; private Quaternion originalRotation; private List<Transform> originalStructure; private Rigidbody Rigidbody; // Use this for initialization private void Start() { originalStructure = new List<Transform>(GetComponentsInChildren<Transform>()); originalPosition = transform.position; originalRotation = transform.rotation; Rigidbody = GetComponent<Rigidbody>(); } public void DelayedReset(float delay) { StartCoroutine(ResetCoroutine(delay)); } public IEnumerator ResetCoroutine(float delay) { yield return new WaitForSeconds(delay); // remove any gameobjects added (fire, skid trails, etc) foreach (Transform t in GetComponentsInChildren<Transform>()) { if (!originalStructure.Contains(t)) { t.parent = null; } } transform.position = originalPosition; transform.rotation = originalRotation; if (Rigidbody) { Rigidbody.velocity = Vector3.zero; Rigidbody.angularVelocity = Vector3.zero; } SendMessage("Reset"); } } }
27
90
0.580247
[ "MIT" ]
rishavnathpati/Beatrex_Ball_MuSync-Unity-Android
Assets/Standard Assets/Utility/ObjectResetter.cs
1,539
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; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Transactions; using Microsoft.Data.Common; namespace Microsoft.Data.SqlClient { sealed internal partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification { private static int _objectTypeCount; internal int ObjectID { get; } = Interlocked.Increment(ref _objectTypeCount); private const int _globalTransactionsTokenVersionSizeInBytes = 4; // the size of the version in the PromotedDTCToken for Global Transactions // WARNING!!! Multithreaded object! // Locking strategy: Any potentailly-multithreaded operation must first lock the associated connection, then // validate this object's active state. Locked activities should ONLY include Sql-transaction state altering activities // or notifications of same. Updates to the connection's association with the transaction or to the connection pool // may be initiated here AFTER the connection lock is released, but should NOT fall under this class's locking strategy. private SqlInternalConnection _connection; // the internal connection that is the root of the transaction private System.Data.IsolationLevel _isolationLevel; // the IsolationLevel of the transaction we delegated to the server private SqlInternalTransaction _internalTransaction; // the SQL Server transaction we're delegating to private Transaction _atomicTransaction; private bool _active; // Is the transaction active? internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx) { Debug.Assert(null != connection, "null connection?"); _connection = connection; _atomicTransaction = tx; _active = false; System.Transactions.IsolationLevel systxIsolationLevel = (System.Transactions.IsolationLevel)tx.IsolationLevel; // We need to map the System.Transactions IsolationLevel to the one // that System.Data uses and communicates to SqlServer. We could // arguably do that in Initialize when the transaction is delegated, // however it is better to do this before we actually begin the process // of delegation, in case System.Transactions adds another isolation // level we don't know about -- we can throw the exception at a better // place. switch (systxIsolationLevel) { case System.Transactions.IsolationLevel.ReadCommitted: _isolationLevel = System.Data.IsolationLevel.ReadCommitted; break; case System.Transactions.IsolationLevel.ReadUncommitted: _isolationLevel = System.Data.IsolationLevel.ReadUncommitted; break; case System.Transactions.IsolationLevel.RepeatableRead: _isolationLevel = System.Data.IsolationLevel.RepeatableRead; break; case System.Transactions.IsolationLevel.Serializable: _isolationLevel = System.Data.IsolationLevel.Serializable; break; case System.Transactions.IsolationLevel.Snapshot: _isolationLevel = System.Data.IsolationLevel.Snapshot; break; default: throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel); } } internal Transaction Transaction { get { return _atomicTransaction; } } public void Initialize() { // if we get here, then we know for certain that we're the delegated // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Initialize|RES|CPOOL> {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { if (connection.IsEnlistedInTransaction) { SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Initialize|RES|CPOOL> {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); // defect first connection.EnlistNull(); } _internalTransaction = new SqlInternalTransaction(connection, TransactionType.Delegated, null); connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true); // Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw. if (null == connection.CurrentTransaction) { connection.DoomThisConnection(); throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure); } _active = true; } catch (System.OutOfMemoryException e) { usersConnection.Abort(e); throw; } catch (System.StackOverflowException e) { usersConnection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { usersConnection.Abort(e); throw; } } internal bool IsActive { get { return _active; } } public byte[] Promote() { // Operations that might be affected by multi-threaded use MUST be done inside the lock. // Don't read values off of the connection outside the lock unless it doesn't really matter // from an operational standpoint (i.e. logging connection's ObjectID should be fine, // but the PromotedDTCToken can change over calls. so that must be protected). SqlInternalConnection connection = GetValidConnection(); Exception promoteException; byte[] returnValue = null; if (null != connection) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Promote|RES|CPOOL> {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { lock (connection) { try { // Now that we've acquired the lock, make sure we still have valid state for this operation. ValidateActiveOnConnection(connection); connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, System.Data.IsolationLevel.Unspecified, _internalTransaction, true); returnValue = _connection.PromotedDTCToken; // For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type. if (_connection.IsGlobalTransaction) { if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null) { throw SQL.UnsupportedSysTxForGlobalTransactions(); } if (!_connection.IsGlobalTransactionsEnabledForServer) { throw SQL.GlobalTransactionsNotEnabled(); } SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() }); } promoteException = null; } catch (SqlException e) { promoteException = e; // Doom the connection, to make sure that the transaction is // eventually rolled back. // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event connection.DoomThisConnection(); } catch (InvalidOperationException e) { promoteException = e; connection.DoomThisConnection(); } } } catch (System.OutOfMemoryException e) { usersConnection.Abort(e); throw; } catch (System.StackOverflowException e) { usersConnection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { usersConnection.Abort(e); throw; } //Throw exception only if Transaction is still active and not yet aborted. if (promoteException != null && Transaction.TransactionInformation.Status != TransactionStatus.Aborted) { throw SQL.PromotionFailed(promoteException); } else { // The transaction was aborted externally, since it's already doomed above, we only log the same. SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Promote|RES|CPOOL> {0}, Connection {1}, aborted during promotion.", ObjectID, connection.ObjectID); } } else { // The transaction was aborted externally, doom the connection to make sure it's eventually rolled back and log the same. SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Promote|RES|CPOOL> {0}, Connection {1}, aborted before promoting.", ObjectID, connection.ObjectID); } return returnValue; } // Called by transaction to initiate abort sequence public void Rollback(SinglePhaseEnlistment enlistment) { Debug.Assert(null != enlistment, "null enlistment?"); SqlInternalConnection connection = GetValidConnection(); if (null != connection) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Rollback|RES|CPOOL> {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { lock (connection) { try { // Now that we've acquired the lock, make sure we still have valid state for this operation. ValidateActiveOnConnection(connection); _active = false; // set to inactive first, doesn't matter how the execute completes, this transaction is done. _connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event // If we haven't already rolled back (or aborted) then tell the SQL Server to roll back if (!_internalTransaction.IsAborted) { connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, null, System.Data.IsolationLevel.Unspecified, _internalTransaction, true); } } catch (SqlException) { // Doom the connection, to make sure that the transaction is // eventually rolled back. // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event connection.DoomThisConnection(); // Unlike SinglePhaseCommit, a rollback is a rollback, regardless // of how it happens, so SysTx won't throw an exception, and we // don't want to throw an exception either, because SysTx isn't // handling it and it may create a fail fast scenario. In the end, // there is no way for us to communicate to the consumer that this // failed for more serious reasons than usual. // // This is a bit like "should you throw if Close fails", however, // it only matters when you really need to know. In that case, // we have the tracing that we're doing to fallback on for the // investigation. } catch (InvalidOperationException) { connection.DoomThisConnection(); } } // it doesn't matter whether the rollback succeeded or not, we presume // that the transaction is aborted, because it will be eventually. connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction); enlistment.Aborted(); } catch (System.OutOfMemoryException e) { usersConnection.Abort(e); throw; } catch (System.StackOverflowException e) { usersConnection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { usersConnection.Abort(e); throw; } } else { // The transaction was aborted, report that to SysTx and log the same. enlistment.Aborted(); SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.Rollback|RES|CPOOL> {0}, Connection {1}, aborted before rollback.", ObjectID, connection.ObjectID); } } // Called by the transaction to initiate commit sequence public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) { Debug.Assert(null != enlistment, "null enlistment?"); SqlInternalConnection connection = GetValidConnection(); if (null != connection) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.SinglePhaseCommit|RES|CPOOL> {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { // If the connection is doomed, we can be certain that the // transaction will eventually be rolled back, and we shouldn't // attempt to commit it. if (connection.IsConnectionDoomed) { lock (connection) { _active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done. _connection = null; } enlistment.Aborted(SQL.ConnectionDoomed()); } else { Exception commitException; lock (connection) { try { // Now that we've acquired the lock, make sure we still have valid state for this operation. ValidateActiveOnConnection(connection); _active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done. _connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, System.Data.IsolationLevel.Unspecified, _internalTransaction, true); commitException = null; } catch (SqlException e) { commitException = e; // Doom the connection, to make sure that the transaction is // eventually rolled back. // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event connection.DoomThisConnection(); } catch (InvalidOperationException e) { commitException = e; connection.DoomThisConnection(); } } if (commitException != null) { // connection.ExecuteTransaction failed with exception if (_internalTransaction.IsCommitted) { // Even though we got an exception, the transaction // was committed by the server. enlistment.Committed(); } else if (_internalTransaction.IsAborted) { // The transaction was aborted, report that to // SysTx. enlistment.Aborted(commitException); } else { // The transaction is still active, we cannot // know the state of the transaction. enlistment.InDoubt(commitException); } // We eat the exception. This is called on the SysTx // thread, not the applications thread. If we don't // eat the exception an UnhandledException will occur, // causing the process to FailFast. } connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction); if (commitException == null) { // connection.ExecuteTransaction succeeded enlistment.Committed(); } } } catch (System.OutOfMemoryException e) { usersConnection.Abort(e); throw; } catch (System.StackOverflowException e) { usersConnection.Abort(e); throw; } catch (System.Threading.ThreadAbortException e) { usersConnection.Abort(e); throw; } } else { // The transaction was aborted before we could commit, report that to SysTx and log the same. enlistment.Aborted(); SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.SinglePhaseCommit|RES|CPOOL> {0}, Connection {1}, aborted before commit.", ObjectID, connection.ObjectID); } } // Event notification that transaction ended. This comes from the subscription to the Transaction's // ended event via the internal connection. If it occurs without a prior Rollback or SinglePhaseCommit call, // it indicates the transaction was ended externally (generally that one of the DTC participants aborted // the transaction). internal void TransactionEnded(Transaction transaction) { SqlInternalConnection connection = _connection; if (connection != null) { SqlClientEventSource.Log.TraceEvent("<sc.SqlDelegatedTransaction.TransactionEnded|RES|CPOOL> {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); lock (connection) { if (_atomicTransaction.Equals(transaction)) { // No need to validate active on connection, this operation can be called on completed transactions _active = false; _connection = null; } // Safest approach is to doom this connection, whose transaction has been aborted externally. // If we want to avoid dooming the connection for performance, state needs to be properly restored. (future TODO) connection.DoomThisConnection(); } } } // Check for connection validity private SqlInternalConnection GetValidConnection() { SqlInternalConnection connection = _connection; if (null == connection && Transaction.TransactionInformation.Status != TransactionStatus.Aborted) { throw ADP.ObjectDisposed(this); } return connection; } // Dooms connection and throws and error if not a valid, active, delegated transaction for the given // connection. Designed to be called AFTER a lock is placed on the connection, otherwise a normal return // may not be trusted. private void ValidateActiveOnConnection(SqlInternalConnection connection) { bool valid = _active && (connection == _connection) && (connection.DelegatedTransaction == this); if (!valid) { // Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance) // Doom anything remotely involved. if (null != connection) { connection.DoomThisConnection(); } if (connection != _connection && null != _connection) { _connection.DoomThisConnection(); } throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); //TODO: Create a new code } } } }
49.403259
197
0.532053
[ "MIT" ]
karinazhou/SqlClient
src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs
24,257
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 09.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NullableByte.NullableInt64{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Byte>; using T_DATA2 =System.Nullable<System.Int64>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__03__NV public static class TestSet_504__param__03__NV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ == /*}OP*/ vv2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__03__NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NullableByte.NullableInt64
26.19708
139
0.529395
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Equal/Complete/NullableByte/NullableInt64/TestSet_504__param__03__NV.cs
3,591
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// ZhimaMerchantOrderCreditPayModel Data Structure. /// </summary> [Serializable] public class ZhimaMerchantOrderCreditPayModel : AopObject { /// <summary> /// 优惠券金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000],无支付行为时为空,例如订单取消或者支付金额为0 /// </summary> [XmlElement("coupon_amount")] public string CouponAmount { get; set; } /// <summary> /// CANCEL,FINISH, INSTALLMENT 订单完结类型,目前包括取消(CANCEL)、完结(FINISH) 分期扣款(INSTALLMENT) /// </summary> [XmlElement("order_operate_type")] public string OrderOperateType { get; set; } /// <summary> /// 外部订单号,包含字母、数字、下划线,调用方需要保证订单号唯一 /// </summary> [XmlElement("out_order_no")] public string OutOrderNo { get; set; } /// <summary> /// 外部资金订单号,可包含字母、数字、下划线 /// </summary> [XmlElement("out_trans_no")] public string OutTransNo { get; set; } /// <summary> /// 支付总金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000],无支付行为时为空,例如订单取消或者支付金额为0 /// </summary> [XmlElement("pay_amount")] public string PayAmount { get; set; } /// <summary> /// 订单操作说明 /// </summary> [XmlElement("remark")] public string Remark { get; set; } /// <summary> /// 是否使用优惠券,默认为false,可选值:true或false,字符串形式,目前仅针对回收行业生效 /// </summary> [XmlElement("use_coupon")] public string UseCoupon { get; set; } /// <summary> /// 芝麻订单号 /// </summary> [XmlElement("zm_order_no")] public string ZmOrderNo { get; set; } } }
29.196721
91
0.54183
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/ZhimaMerchantOrderCreditPayModel.cs
2,205
C#
using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Text; namespace Microsoft.AnalysisServices.AdomdClient { internal class NTAuthentication { private const int ERROR_BUFFER_OVERFLOW = 111; private const int ERROR_INVALID_PARAMETER = 87; private const string ServiceClassName = "MSOLAPSvc.3"; private const string SqlBrowserClassName = "MSOLAPDisco.3"; private static SecurityPackageInfoClass[] m_SupportedSecurityPackages = SSPIWrapper.EnumerateSecurityPackages(); private CredentialsContext m_CredentialsHandle; private SecurityContext m_SecurityContext; private Endianness m_Endianness; private string m_RemotePeerId; private int m_TokenSize; private int m_Capabilities; private int m_ContextFlags; private ContextFlags m_RequestedFlags; private bool m_isSchannel; internal SecurityContext SecurityContext { get { return this.m_SecurityContext; } } public bool IsSchannel { get { return this.m_isSchannel; } } internal NTAuthentication(ConnectionInfo connectionInfo, SecurityContextMode securityContextMode) { this.m_isSchannel = connectionInfo.IsSchannelSspi(); this.InitializeSPN(connectionInfo); this.InitializePackageSpecificMembers(connectionInfo.Sspi); this.InitializeFlags(connectionInfo, securityContextMode); this.InitializeCredentialsHandle(connectionInfo); this.m_Endianness = Endianness.Network; this.m_SecurityContext = new SecurityContext(securityContextMode); } private void InitializeSPN(ConnectionInfo connectionInfo) { if (this.m_isSchannel) { this.m_RemotePeerId = connectionInfo.Server; return; } if (connectionInfo.InstanceName != null) { string server = connectionInfo.Server; if (string.Compare(server, "localhost", StringComparison.OrdinalIgnoreCase) == 0 || connectionInfo.IsServerLocal || string.Compare(server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0) { this.m_RemotePeerId = null; return; } this.m_RemotePeerId = "MSOLAPSvc.3/" + server + ":" + connectionInfo.InstanceName; return; } else { string strName = connectionInfo.IsServerLocal ? Environment.MachineName : connectionInfo.Server; uint num = 0u; string strClass; ushort iPort; if (connectionInfo.IsForSqlBrowser) { strClass = "MSOLAPDisco.3"; iPort = 0; } else { strClass = "MSOLAPSvc.3"; iPort = (ushort) ((connectionInfo.Port == null) ? 0 : ushort.Parse(connectionInfo.Port, CultureInfo.InvariantCulture)); } int num2 = UnsafeNclNativeMethods.NativeNTSSPI.DsMakeSpnW(strClass, strName, null, iPort, null, ref num, null); int num3 = num2; if (num3 == 87) { this.m_RemotePeerId = string.Empty; return; } if (num3 != 111) { throw new Win32Exception(num2); } StringBuilder stringBuilder = new StringBuilder((int)num, (int)num); num2 = UnsafeNclNativeMethods.NativeNTSSPI.DsMakeSpnW(strClass, strName, null, iPort, null, ref num, stringBuilder); if (num2 != 0) { throw new Win32Exception(num2); } this.m_RemotePeerId = stringBuilder.ToString(); return; } } private void InitializePackageSpecificMembers(string packageName) { if (NTAuthentication.m_SupportedSecurityPackages != null) { int i = 0; int num = NTAuthentication.m_SupportedSecurityPackages.Length; while (i < num) { if (string.Compare(NTAuthentication.m_SupportedSecurityPackages[i].Name, packageName, StringComparison.OrdinalIgnoreCase) == 0) { this.m_TokenSize = NTAuthentication.m_SupportedSecurityPackages[i].MaxToken; this.m_Capabilities = NTAuthentication.m_SupportedSecurityPackages[i].Capabilities; return; } i++; } } throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_PackageNotFound(packageName), null, ConnectionExceptionCause.AuthenticationFailed); } private void InitializeFlags(ConnectionInfo connectionInfo, SecurityContextMode securityContextMode) { string sspi = connectionInfo.Sspi; ImpersonationLevel impersonationLevel = connectionInfo.ImpersonationLevel; if (this.m_isSchannel) { switch (securityContextMode) { case SecurityContextMode.block: this.CheckIfCapabilityIsSupported(sspi, PackageCapabilities.Connection); this.m_RequestedFlags = ContextFlags.Connection; break; case SecurityContextMode.stream: this.CheckIfCapabilityIsSupported(sspi, PackageCapabilities.Stream); this.m_RequestedFlags = ContextFlags.Stream; break; default: throw new AdomdConnectionException("Unsupported TLS mode " + securityContextMode.ToString(), null, ConnectionExceptionCause.AuthenticationFailed); } switch (impersonationLevel) { case ImpersonationLevel.Anonymous: case ImpersonationLevel.Identify: case ImpersonationLevel.Impersonate: switch (connectionInfo.ProtectionLevel) { case ProtectionLevel.None: case ProtectionLevel.Connection: case ProtectionLevel.Integrity: throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_SchannelSupportsOnlyPrivacyLevel, null, ConnectionExceptionCause.AuthenticationFailed); case ProtectionLevel.Privacy: this.m_RequestedFlags |= (ContextFlags.ReplayDetect | ContextFlags.SequenceDetect | ContextFlags.Confidentiality | ContextFlags.UseSuppliedCreds | ContextFlags.Integrity); return; default: throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_SchannelUnsupportedProtectionLevel, null, ConnectionExceptionCause.AuthenticationFailed); } case ImpersonationLevel.Delegate: throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_SchannelCantDelegate, null, ConnectionExceptionCause.AuthenticationFailed); default: throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_SchannelUnsupportedImpersonationLevel, null, ConnectionExceptionCause.AuthenticationFailed); } } else { this.m_RequestedFlags = (ContextFlags.MutualAuth | ContextFlags.Connection); switch (impersonationLevel) { case ImpersonationLevel.Identify: this.m_RequestedFlags |= ContextFlags.Identify; break; case ImpersonationLevel.Impersonate: this.CheckIfCapabilityIsSupported(sspi, PackageCapabilities.Impersonation); break; case ImpersonationLevel.Delegate: this.m_RequestedFlags |= ContextFlags.Delegate; break; } switch (connectionInfo.ProtectionLevel) { case ProtectionLevel.Connection: this.m_RequestedFlags |= ContextFlags.NoIntegrity; return; case ProtectionLevel.Integrity: this.CheckIfCapabilityIsSupported(sspi, PackageCapabilities.Integrity); this.m_RequestedFlags |= (ContextFlags.ReplayDetect | ContextFlags.SequenceDetect | ContextFlags.Integrity); return; case ProtectionLevel.Privacy: this.CheckIfCapabilityIsSupported(sspi, PackageCapabilities.Privacy); this.m_RequestedFlags |= (ContextFlags.ReplayDetect | ContextFlags.SequenceDetect | ContextFlags.Confidentiality | ContextFlags.Integrity); return; default: return; } } } private void InitializeCredentialsHandle(ConnectionInfo connectionInfo) { string sspi = connectionInfo.Sspi; if (connectionInfo.ImpersonationLevel == ImpersonationLevel.Anonymous) { if (this.m_isSchannel) { if (string.IsNullOrEmpty(connectionInfo.Certificate)) { this.m_CredentialsHandle = new CredentialsContext(null); return; } throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_SchannelAnonymousAmbiguity, null, ConnectionExceptionCause.AuthenticationFailed); } else { IntPtr currentThread = UnsafeNclNativeMethods.GetCurrentThread(); if (!UnsafeNclNativeMethods.ImpersonateAnonymousToken(currentThread)) { uint lastError = UnsafeNclNativeMethods.GetLastError(); throw new Win32Exception((int)lastError); } try { this.m_CredentialsHandle = new CredentialsContext(sspi, CredentialUse.Outgoing); return; } finally { if (!UnsafeNclNativeMethods.RevertToSelf()) { Process.GetCurrentProcess().Kill(); } } } } if (this.m_isSchannel) { string certificate = connectionInfo.Certificate; if (string.IsNullOrEmpty(certificate)) { this.m_CredentialsHandle = new CredentialsContext(null); return; } this.m_CredentialsHandle = new CredentialsContext(CertUtils.LoadCertificateByThumbprint(certificate, true)); return; } else { this.m_CredentialsHandle = new CredentialsContext(sspi, CredentialUse.Outgoing); } } public byte[] GetOutgoingBlob(byte[] incomingBlob, out bool handshakeComplete) { handshakeComplete = true; if (this.m_SecurityContext.Handle.Initialized && incomingBlob == null) { return null; } SecurityBufferClass inputBuffer = null; if (incomingBlob != null) { inputBuffer = new SecurityBufferClass(incomingBlob, BufferType.Token); } SecurityBufferClass securityBufferClass = new SecurityBufferClass(this.m_TokenSize, BufferType.Token); int num = SSPIWrapper.InitializeSecurityContext(ref this.m_CredentialsHandle.Handle, ref this.m_SecurityContext.Handle, this.m_RemotePeerId, (int)this.m_RequestedFlags, this.m_Endianness, inputBuffer, ref this.m_SecurityContext.Handle, securityBufferClass, ref this.m_ContextFlags, ref this.m_SecurityContext.TimeStamp); int num2 = num & -2147483648; if (num2 != 0) { throw new Win32Exception(num); } if (num != 0 && this.m_SecurityContext.Handle.Initialized) { handshakeComplete = false; } else { switch (this.m_SecurityContext.SecurityContextMode) { case SecurityContextMode.stream: this.CheckIfFlagWasObtainedIfRequested(ContextFlags.Stream); break; } this.CheckIfFlagWasObtainedIfRequested(ContextFlags.MutualAuth); this.CheckIfFlagWasObtainedIfRequested(ContextFlags.ReplayDetect); this.CheckIfFlagWasObtainedIfRequested(ContextFlags.SequenceDetect); this.CheckIfFlagWasObtainedIfRequested(ContextFlags.Confidentiality); } return securityBufferClass.token; } private void CheckIfCapabilityIsSupported(string packageName, PackageCapabilities capability) { if ((this.m_Capabilities & (int)capability) == 0) { throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_PackageDoesntSupportCapability(packageName, capability.ToString()), null, ConnectionExceptionCause.AuthenticationFailed); } } private void CheckIfFlagWasObtainedIfRequested(ContextFlags flag) { if ((this.m_RequestedFlags & flag) != (ContextFlags)0 && (this.m_ContextFlags & (int)flag) == 0) { throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_FlagNotEstablished(flag.ToString()), null, ConnectionExceptionCause.AuthenticationFailed); } } } }
33.640244
323
0.745514
[ "MIT" ]
VitaliyMF/Unofficial.Microsoft.AnalysisServices.AdomdClientNetCore
AdomdClientNetCore/Microsoft.AnalysisServices.AdomdClient/NTAuthentication.cs
11,034
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- namespace Microsoft.Health.Fhir.Core.Configs { public class ExportJobFormatConfiguration { /// <summary> /// The name of the format. This is how the format is referenced in the _format parameter when creating a new export job. /// The name is used as a unique identifier. Formats should not share names. /// </summary> public string Name { get; set; } = string.Empty; /// <summary> /// The format definition string. An export job's format is used to create the folder stucture inside the container. /// The format is defined by tags and characters. Supported tags are defined below. The / character is used to indicate a subfolder. /// <timestamp> - Places a timestamp corisponding to the time the export job was enqueued. /// <resourcename> - The name of the resource currently being exported. /// <id> - The GUID id of the export job. /// </summary> public string Format { get; set; } /// <summary> /// Whether the format is the default format for when no format is specified by the user. /// </summary> public bool Default { get; set; } = false; } }
50.419355
140
0.568778
[ "MIT" ]
10thmagnitude/fhir-server
src/Microsoft.Health.Fhir.Core/Configs/ExportJobFormatConfiguration.cs
1,565
C#
using System; using System.Reflection; namespace PicoDilly { public interface IContainer { T GetInstance<T>(); void Configure(Action<IContainer> configureAction); IContainer For<T>(); IContainer Use<T>(T instance); } }
23.636364
59
0.65
[ "MIT" ]
DarkDeny/PicoDilly
PicoDilly/IContainer.cs
262
C#
using System; using System.Collections.Generic; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using SFA.DAS.Api.Common.AppStart; using SFA.DAS.Api.Common.Configuration; using SFA.DAS.Reservations.Api.AppStart; using SFA.DAS.Reservations.Application.TrainingCourses.Queries.GetTrainingCourseList; using SFA.DAS.SharedOuterApi.AppStart; using SFA.DAS.SharedOuterApi.Infrastructure.HealthCheck; namespace SFA.DAS.Reservations.Api { public class Startup { private readonly IWebHostEnvironment _env; private readonly IConfiguration _configuration; public Startup(IConfiguration configuration, IWebHostEnvironment env) { _env = env; _configuration = configuration.BuildSharedConfiguration(); } public void ConfigureServices(IServiceCollection services) { services.AddSingleton(_env); services.AddConfigurationOptions(_configuration); if (!_configuration.IsLocalOrDev()) { var azureAdConfiguration = _configuration .GetSection("AzureAd") .Get<AzureActiveDirectoryConfiguration>(); var policies = new Dictionary<string, string> { {"default", "APIM"} }; services.AddAuthentication(azureAdConfiguration, policies); } services.AddMediatR(typeof(GetTrainingCoursesQuery).Assembly); services.AddServiceRegistration(); services .AddMvc(o => { if (!_configuration.IsLocalOrDev()) { o.Filters.Add(new AuthorizeFilter("default")); } }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); if (_configuration["Environment"] != "DEV") { services.AddHealthChecks() .AddCheck<CoursesApiHealthCheck>("Courses API health check") .AddCheck<CourseDeliveryApiHealthCheck>("CourseDelivery API health check"); } services.AddApplicationInsightsTelemetry(_configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ReservationsOuterApi", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); if (!_configuration["Environment"].Equals("DEV", StringComparison.CurrentCultureIgnoreCase)) { app.UseHealthChecks(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "api/{controller=TrainingCourses}/{action=GetList}/{id?}"); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ReservationsOuterApi"); c.RoutePrefix = string.Empty; }); } } }
34.636364
106
0.590026
[ "MIT" ]
SkillsFundingAgency/das-apim-endpoints
src/SFA.DAS.Reservations.Api/Startup.cs
3,810
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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Testing; using Templates.Test.Helpers; using Xunit; using Xunit.Abstractions; namespace Templates.Test { public class GrpcTemplateTest : LoggedTest { public GrpcTemplateTest(ProjectFactoryFixture projectFactory) { ProjectFactory = projectFactory; } public ProjectFactoryFixture ProjectFactory { get; } private ITestOutputHelper _output; public ITestOutputHelper Output { get { if (_output == null) { _output = new TestOutputLogger(Logger); } return _output; } } [ConditionalFact] [SkipOnHelix( "Not supported queues", Queues = "Windows.7.Amd64;Windows.7.Amd64.Open;Windows.81.Amd64.Open;All.OSX;" + HelixConstants.Windows10Arm64 + HelixConstants.DebianArm64 )] [SkipOnAlpine("https://github.com/grpc/grpc/issues/18338")] public async Task GrpcTemplate() { var project = await ProjectFactory.GetOrCreateProject("grpc", Output); var createResult = await project.RunDotNetNewAsync("grpc"); Assert.True( 0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", project, createResult) ); var publishResult = await project.RunDotNetPublishAsync(); Assert.True( 0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", project, publishResult) ); var buildResult = await project.RunDotNetBuildAsync(); Assert.True( 0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", project, buildResult) ); var isOsx = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); var isWindowsOld = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.OSVersion.Version < new Version(6, 2); var unsupported = isOsx || isWindowsOld; using ( var serverProcess = project.StartBuiltProjectAsync( hasListeningUri: !unsupported, logger: Logger ) ) { // These templates are HTTPS + HTTP/2 only which is not supported on Mac due to missing ALPN support. // https://github.com/dotnet/aspnetcore/issues/11061 if (isOsx) { serverProcess.Process.WaitForExit(assertSuccess: false); Assert.True(serverProcess.Process.HasExited, "built"); Assert.Contains( "System.NotSupportedException: HTTP/2 over TLS is not supported on macOS due to missing ALPN support.", ErrorMessages.GetFailedProcessMessageOrEmpty( "Run built service", project, serverProcess.Process ) ); } else if (isWindowsOld) { serverProcess.Process.WaitForExit(assertSuccess: false); Assert.True(serverProcess.Process.HasExited, "built"); Assert.Contains( "System.NotSupportedException: HTTP/2 over TLS is not supported on Windows 7 due to missing ALPN support.", ErrorMessages.GetFailedProcessMessageOrEmpty( "Run built service", project, serverProcess.Process ) ); } else { Assert.False( serverProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty( "Run built service", project, serverProcess.Process ) ); } } using ( var aspNetProcess = project.StartPublishedProjectAsync( hasListeningUri: !unsupported ) ) { // These templates are HTTPS + HTTP/2 only which is not supported on Mac due to missing ALPN support. // https://github.com/dotnet/aspnetcore/issues/11061 if (isOsx) { aspNetProcess.Process.WaitForExit(assertSuccess: false); Assert.True(aspNetProcess.Process.HasExited, "published"); Assert.Contains( "System.NotSupportedException: HTTP/2 over TLS is not supported on macOS due to missing ALPN support.", ErrorMessages.GetFailedProcessMessageOrEmpty( "Run published service", project, aspNetProcess.Process ) ); } else if (isWindowsOld) { aspNetProcess.Process.WaitForExit(assertSuccess: false); Assert.True(aspNetProcess.Process.HasExited, "published"); Assert.Contains( "System.NotSupportedException: HTTP/2 over TLS is not supported on Windows 7 due to missing ALPN support.", ErrorMessages.GetFailedProcessMessageOrEmpty( "Run published service", project, aspNetProcess.Process ) ); } else { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty( "Run published service", project, aspNetProcess.Process ) ); } } } } }
39.535294
131
0.49933
[ "Apache-2.0" ]
belav/aspnetcore
src/ProjectTemplates/test/GrpcTemplateTest.cs
6,721
C#
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using Abp.Organizations; using CarnaApp.Authorization.Roles; namespace CarnaApp.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IAsyncQueryableExecuter asyncQueryableExecuter, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository) : base( unitOfWorkManager, userRepository, roleRepository, asyncQueryableExecuter, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository, userOrganizationUnitRepository, organizationUnitRoleRepository) { } } }
36.236842
85
0.658678
[ "MIT" ]
atbostan/CarnaApp
aspnet-core/src/CarnaApp.Core/Authorization/Users/UserStore.cs
1,377
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; namespace david.hotelbooking.domain.Entities.RBAC { public class Permission { [Key] public int Id { get; set; } [Required] public string Name { get; set; } public string Description { get; set; } [JsonIgnore] public virtual ICollection<RolePermission> RolePermissions { get; set; } } }
24.947368
80
0.662447
[ "MIT" ]
daviddongguo/HotelBooking
david.hotelbooking.domain/Entities/RBAC/Permission.cs
476
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Specialized; using System.ComponentModel; namespace EphemerisCalculator { [Serializable] public class PlanetManager : INotifyPropertyChanged { #region Static definition public const int DefaultOff = 0; public const int DefaultOn = 1; public static BitVector32.Section LongitudeMask; //The bit 0 indicates if the longitude is display or not public static BitVector32.Section LatitudeMask; //The bit 1 indicates if the latitude is on public static BitVector32.Section DistanceMask; //The bit 2 indicates if the distance is on public static BitVector32.Section LongitudeVelocitiesMask; //The bit 3 indicates if the longitude velocity is display or not public static BitVector32.Section LatitudeVelocitiesMask; //The bit 4 indicates if the latitude velocity is display or not public static BitVector32.Section DistanceVelocitiesMask; //The bit 5 indicates if the distance velocity is display or not public static BitVector32.Section AscendingMask; //The bit 6 indicates if the Ascending is displayed or not public static BitVector32.Section DescendingMask; //The bit 7 indicates if the Descending is displayed or not public static BitVector32.Section PerigeeMask; //The bit 8 indicates if the Perigee is displayed or not public static BitVector32.Section ApogeeMask; //The bit 9 indicates if the Apogee is displayed or not public static BitVector32.Section AscendingLatitudeMask; //The bit 10 indicates if the AscendingLatitude is displayed or not public static BitVector32.Section DescendingLatitudeMask; //The bit 11 indicates if the DescendingLatitude is displayed or not public static BitVector32.Section PerigeeLatitudeMask; //The bit 12 indicates if the PerigeeLatitude is displayed or not public static BitVector32.Section ApogeeLatitudeMask; //The bit 13 indicates if the ApogeeLatitude is displayed or not public static BitVector32.Section AscendingVelocitiesMask; //The bit 14 indicates if the AscendingVelocities is displayed or not public static BitVector32.Section DescendingVelocitiesMask; //The bit 15 indicates if the DescendingVelocities is displayed or not public static BitVector32.Section PerigeeVelocitiesMask; //The bit 16 indicates if the PerigeeVelocities is displayed or not public static BitVector32.Section ApogeeVelocitiesMask; //The bit 17 indicates if the ApogeeVelocities is displayed or not public static BitVector32.Section LowBitsMask; public static BitVector32.Section HighBitsMask; static PlanetManager() { LowBitsMask = BitVector32.CreateSection(0xFF); HighBitsMask = BitVector32.CreateSection(0xFF, LowBitsMask); LongitudeMask = BitVector32.CreateSection(1); //The bit 0 indicates if the longitude is display or not LatitudeMask = BitVector32.CreateSection(1, LongitudeMask); //The bit 1 indicates if the latitude is on DistanceMask = BitVector32.CreateSection(1, LatitudeMask); //The bit 2 indicates if the distance is on LongitudeVelocitiesMask = BitVector32.CreateSection(1, DistanceMask); //The bit 3 indicates if the longitude velocity is display or not LatitudeVelocitiesMask = BitVector32.CreateSection(1, LongitudeVelocitiesMask); //The bit 4 indicates if the latitude velocity is display or not DistanceVelocitiesMask = BitVector32.CreateSection(1, LatitudeVelocitiesMask); //The bit 5 indicates if the distance velocity is display or not AscendingMask = BitVector32.CreateSection(1, DistanceVelocitiesMask); //The bit 6 indicates if the Ascending is displayed or not DescendingMask = BitVector32.CreateSection(1, AscendingMask); //The bit 7 indicates if the Descending is displayed or not PerigeeMask = BitVector32.CreateSection(1, DescendingMask); //The bit 8 indicates if the Perigee is displayed or not ApogeeMask = BitVector32.CreateSection(1, PerigeeMask); //The bit 9 indicates if the Apogee is displayed or not AscendingLatitudeMask = BitVector32.CreateSection(1, ApogeeMask); //The bit 10 indicates if the AscendingLatitude is displayed or not DescendingLatitudeMask = BitVector32.CreateSection(1, AscendingLatitudeMask); //The bit 11 indicates if the DescendingLatitude is displayed or not PerigeeLatitudeMask = BitVector32.CreateSection(1, DescendingLatitudeMask); //The bit 12 indicates if the PerigeeLatitude is displayed or not ApogeeLatitudeMask = BitVector32.CreateSection(1, PerigeeLatitudeMask); //The bit 13 indicates if the ApogeeLatitude is displayed or not AscendingVelocitiesMask = BitVector32.CreateSection(1, ApogeeLatitudeMask); //The bit 14 indicates if the AscendingVelocities is displayed or not DescendingVelocitiesMask = BitVector32.CreateSection(1, AscendingVelocitiesMask); //The bit 15 indicates if the DescendingVelocities is displayed or not PerigeeVelocitiesMask = BitVector32.CreateSection(1, DescendingVelocitiesMask); //The bit 16 indicates if the PerigeeVelocities is displayed or not ApogeeVelocitiesMask = BitVector32.CreateSection(1, PerigeeVelocitiesMask); //The bit 17 indicates if the ApogeeVelocities is displayed or not } #endregion #region Properties public PlanetId Star { get; set; } private BitVector32 manager; public bool IsPlanetShown { get { return manager.Data != DefaultOff; } set { if(value != (manager.Data != DefaultOff)) { manager[LowBitsMask] = value ? DefaultOn : DefaultOff; manager[HighBitsMask] = 0; NotifyPropertyChanged(OrbitInfoType.Longitude); } } } public bool LongitudeShown { get { return manager[LongitudeMask] == 1; } set { if (value != (manager[LongitudeMask] == 1)) { manager[LongitudeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Longitude); } } } public bool LatitudeShown { get { return manager[LatitudeMask] == 1; } set { if (value != (manager[LatitudeMask] == 1)) { manager[LatitudeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Latitude); } } } public bool DistanceShown { get { return manager[DistanceMask] == 1; } set { if (value != (manager[DistanceMask] == 1)) { manager[DistanceMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Distance); } } } public bool LongitudeVelocitiesShown { get { return manager[LongitudeVelocitiesMask] == 1; } set { if (value != (manager[LongitudeVelocitiesMask] == 1)) { manager[LongitudeVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.LongitudeVelocities); } } } public bool LatitudeVelocitiesShown { get { return manager[LatitudeVelocitiesMask] == 1; } set { if (value != (manager[LatitudeVelocitiesMask] == 1)) { manager[LatitudeVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.LatitudeVelocities); } } } public bool DistanceVelocitiesShown { get { return manager[DistanceVelocitiesMask] == 1; } set { if (value != (manager[DistanceVelocitiesMask] == 1)) { manager[DistanceVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.DistanceVelocities); } } } public bool AscendingShown { get { return manager[AscendingMask] == 1; } set { if (value != (manager[AscendingMask] == 1)) { manager[AscendingMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Ascending); } } } public bool DescendingShown { get { return manager[DescendingMask] == 1; } set { if (value != (manager[DescendingMask] == 1)) { manager[DescendingMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Descending); } } } public bool PerigeeShown { get { return manager[PerigeeMask] == 1; } set { if (value != (manager[PerigeeMask] == 1)) { manager[PerigeeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Perigee); } } } public bool ApogeeShown { get { return manager[ApogeeMask] == 1; } set { if (value != (manager[ApogeeMask] == 1)) { manager[ApogeeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.Apogee); } } } public bool AscendingLatitudeShown { get { return manager[AscendingLatitudeMask] == 1; } set { if (value != (manager[AscendingLatitudeMask] == 1)) { manager[AscendingLatitudeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.AscendingLatitude); } } } public bool DescendingLatitudeShown { get { return manager[DescendingLatitudeMask] == 1; } set { if (value != (manager[DescendingLatitudeMask] == 1)) { manager[DescendingLatitudeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.DescendingLatitude); } } } public bool PerigeeLatitudeShown { get { return manager[PerigeeLatitudeMask] == 1; } set { if (value != (manager[PerigeeLatitudeMask] == 1)) { manager[PerigeeLatitudeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.PerigeeLatitude); } } } public bool ApogeeLatitudeShown { get { return manager[ApogeeLatitudeMask] == 1; } set { if (value != (manager[ApogeeLatitudeMask] == 1)) { manager[ApogeeLatitudeMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.ApogeeLatitude); } } } public bool AscendingVelocitiesShown { get { return manager[AscendingVelocitiesMask] == 1; } set { if (value != (manager[AscendingVelocitiesMask] == 1)) { manager[AscendingVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.AscendingVelocities); } } } public bool DescendingVelocitiesShown { get { return manager[DescendingVelocitiesMask] == 1; } set { if (value != (manager[DescendingVelocitiesMask] == 1)) { manager[DescendingVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.DescendingVelocities); } } } public bool PerigeeVelocitiesShown { get { return manager[PerigeeVelocitiesMask] == 1; } set { if (value != (manager[PerigeeVelocitiesMask] == 1)) { manager[PerigeeVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.PerigeeVelocities); } } } public bool ApogeeVelocitiesShown { get { return manager[ApogeeVelocitiesMask] == 1; } set { if (value != (manager[ApogeeVelocitiesMask] == 1)) { manager[ApogeeVelocitiesMask] = value ? 1 : 0; NotifyPropertyChanged(OrbitInfoType.ApogeeVelocities); } } } public bool this[OrbitInfoType type] { get { switch(type) { //case OrbitInfoType.All: return IsPlanetShown; case OrbitInfoType.Longitude: return LatitudeShown; case OrbitInfoType.Latitude: return LatitudeShown; case OrbitInfoType.Distance: return DistanceShown; case OrbitInfoType.LongitudeVelocities: return LongitudeVelocitiesShown; case OrbitInfoType.LatitudeVelocities: return LatitudeVelocitiesShown; case OrbitInfoType.DistanceVelocities: return DistanceVelocitiesShown; case OrbitInfoType.Ascending: return AscendingShown; case OrbitInfoType.Descending: return DescendingShown; case OrbitInfoType.Perigee: return PerigeeShown; case OrbitInfoType.Apogee: return ApogeeShown; case OrbitInfoType.AscendingLatitude: return AscendingLatitudeShown; case OrbitInfoType.DescendingLatitude: return DescendingLatitudeShown; case OrbitInfoType.PerigeeLatitude: return PerigeeLatitudeShown; case OrbitInfoType.ApogeeLatitude: return ApogeeLatitudeShown; case OrbitInfoType.AscendingVelocities: return AscendingVelocitiesShown; case OrbitInfoType.DescendingVelocities: return DescendingVelocitiesShown; case OrbitInfoType.PerigeeVelocities: return PerigeeVelocitiesShown; case OrbitInfoType.ApogeeVelocities: return ApogeeVelocitiesShown; default: throw new NotImplementedException(); } } set { switch(type) { //case OrbitInfoType.All: IsPlanetShown = value; break; case OrbitInfoType.Longitude: LatitudeShown = value; break; case OrbitInfoType.Latitude: LatitudeShown = value; break; case OrbitInfoType.Distance: DistanceShown = value; break; case OrbitInfoType.LongitudeVelocities: LongitudeVelocitiesShown = value; break; case OrbitInfoType.LatitudeVelocities: LatitudeVelocitiesShown = value; break; case OrbitInfoType.DistanceVelocities: DistanceVelocitiesShown = value; break; case OrbitInfoType.Ascending: AscendingShown = value; break; case OrbitInfoType.Descending: DescendingShown = value; break; case OrbitInfoType.Perigee: PerigeeShown = value; break; case OrbitInfoType.Apogee: ApogeeShown = value; break; case OrbitInfoType.AscendingLatitude: AscendingLatitudeShown = value; break; case OrbitInfoType.DescendingLatitude: DescendingLatitudeShown = value; break; case OrbitInfoType.PerigeeLatitude: PerigeeLatitudeShown = value; break; case OrbitInfoType.ApogeeLatitude: ApogeeLatitudeShown = value; break; case OrbitInfoType.AscendingVelocities: AscendingVelocitiesShown = value; break; case OrbitInfoType.DescendingVelocities: DescendingVelocitiesShown = value; break; case OrbitInfoType.PerigeeVelocities: PerigeeVelocitiesShown = value; break; case OrbitInfoType.ApogeeVelocities: ApogeeVelocitiesShown = value; break; default: throw new NotImplementedException(); } } } #endregion public PlanetManager(PlanetId star) { Star = star; manager = new BitVector32(); } #region INotifyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(OrbitInfoType info) { if (PropertyChanged != null) { PropertyChanged(Star, new PropertyChangedEventArgs(info.ToString())); } } #endregion } }
46.957447
164
0.57952
[ "MIT" ]
Cruisoring/Astroder
Astroder/EphemerisPresenter/PlanetManager.cs
17,662
C#
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; #if FEATURE_CORESYSTEM using System.Core; #endif using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography { /// <summary> /// Flag to indicate if we're doing encryption or decryption /// </summary> internal enum EncryptionMode { Encrypt, Decrypt } /// <summary> /// Implementation of a generic CAPI symmetric encryption algorithm. Concrete SymmetricAlgorithm classes /// which wrap CAPI implementations can use this class to perform the actual encryption work. /// </summary> internal sealed class CapiSymmetricAlgorithm : ICryptoTransform { private int m_blockSize; private byte[] m_depadBuffer; private EncryptionMode m_encryptionMode; [SecurityCritical] private SafeCapiKeyHandle m_key; private PaddingMode m_paddingMode; [SecurityCritical] private SafeCspHandle m_provider; [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode) { Contract.Requires(0 < blockSize && blockSize % 8 == 0); Contract.Requires(0 <= feedbackSize); Contract.Requires(provider != null && !provider.IsInvalid && !provider.IsClosed); Contract.Requires(key != null && !key.IsInvalid && !key.IsClosed); Contract.Ensures(m_provider != null && !m_provider.IsInvalid && !m_provider.IsClosed); m_blockSize = blockSize; m_encryptionMode = encryptionMode; m_paddingMode = paddingMode; m_provider = provider.Duplicate(); m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize); } public bool CanReuseTransform { get { return true; } } public bool CanTransformMultipleBlocks { get { return true; } } // // Note: both input and output block size are in bytes rather than bits // public int InputBlockSize { [Pure] get { return m_blockSize / 8; } } public int OutputBlockSize { get { return m_blockSize / 8; } } [SecuritySafeCritical] public void Dispose() { Contract.Ensures(m_key == null || m_key.IsClosed); Contract.Ensures(m_provider == null || m_provider.IsClosed); Contract.Ensures(m_depadBuffer == null); if (m_key != null) { m_key.Dispose(); } if (m_provider != null) { m_provider.Dispose(); } if (m_depadBuffer != null) { Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length); } return; } [SecuritySafeCritical] private int DecryptBlocks(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { Contract.Requires(m_key != null); Contract.Requires(inputBuffer != null && inputCount <= inputBuffer.Length - inputOffset); Contract.Requires(inputOffset >= 0); Contract.Requires(inputCount > 0 && inputCount % InputBlockSize == 0); Contract.Requires(outputBuffer != null && inputCount <= outputBuffer.Length - outputOffset); Contract.Requires(inputOffset >= 0); Contract.Requires(m_depadBuffer == null || (m_paddingMode != PaddingMode.None && m_paddingMode != PaddingMode.Zeros)); Contract.Ensures(Contract.Result<int>() >= 0); // // If we're decrypting, it's possible to be called with the last blocks of the data, and then // have TransformFinalBlock called with an empty array. Since we don't know if this is the case, // we won't decrypt the last block of the input until either TransformBlock or // TransformFinalBlock is next called. // // We don't need to do this for PaddingMode.None because there is no padding to strip, and // we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the // zeros at the end of a block are part of the plaintext or the padding. // int decryptedBytes = 0; if (m_paddingMode != PaddingMode.None && m_paddingMode != PaddingMode.Zeros) { // If we have data saved from a previous call, decrypt that into the output first if (m_depadBuffer != null) { int depadDecryptLength = RawDecryptBlocks(m_depadBuffer, 0, m_depadBuffer.Length); Buffer.BlockCopy(m_depadBuffer, 0, outputBuffer, outputOffset, depadDecryptLength); Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length); outputOffset += depadDecryptLength; decryptedBytes += depadDecryptLength; } else { m_depadBuffer = new byte[InputBlockSize]; } // Copy the last block of the input buffer into the depad buffer Debug.Assert(inputCount >= m_depadBuffer.Length, "inputCount >= m_depadBuffer.Length"); Buffer.BlockCopy(inputBuffer, inputOffset + inputCount - m_depadBuffer.Length, m_depadBuffer, 0, m_depadBuffer.Length); inputCount -= m_depadBuffer.Length; Debug.Assert(inputCount % InputBlockSize == 0, "Did not remove whole blocks for depadding"); } // CryptDecrypt operates in place, so if after reserving the depad buffer there's still data to decrypt, // make a copy of that in the output buffer to work on. if (inputCount > 0) { Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); decryptedBytes += RawDecryptBlocks(outputBuffer, outputOffset, inputCount); } return decryptedBytes; } /// <summary> /// Remove the padding from the last blocks being decrypted /// </summary> private byte[] DepadBlock(byte[] block, int offset, int count) { Contract.Requires(block != null && count >= block.Length - offset); Contract.Requires(0 <= offset); Contract.Requires(0 <= count); Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length <= block.Length); int padBytes = 0; // See code:System.Security.Cryptography.CapiSymmetricAlgorithm.PadBlock for a description of the // padding modes. switch (m_paddingMode) { case PaddingMode.ANSIX923: padBytes = block[offset + count - 1]; // Verify the amount of padding is reasonable if (padBytes <= 0 || padBytes > InputBlockSize) { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding)); } // Verify that all the padding bytes are 0s for (int i = offset + count - padBytes; i < offset + count - 1; i++) { if (block[i] != 0) { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding)); } } break; case PaddingMode.ISO10126: padBytes = block[offset + count - 1]; // Verify the amount of padding is reasonable if (padBytes <= 0 || padBytes > InputBlockSize) { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding)); } // Since the padding consists of random bytes, we cannot verify the actual pad bytes themselves break; case PaddingMode.PKCS7: padBytes = block[offset + count - 1]; // Verify the amount of padding is reasonable if (padBytes <= 0 || padBytes > InputBlockSize) { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding)); } // Verify all the padding bytes match the amount of padding for (int i = offset + count - padBytes; i < offset + count; i++) { if (block[i] != padBytes) { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding)); } } break; // We cannot remove Zeros padding because we don't know if the zeros at the end of the block // belong to the padding or the plaintext itself. case PaddingMode.Zeros: case PaddingMode.None: padBytes = 0; break; default: throw new CryptographicException(SR.GetString(SR.Cryptography_UnknownPaddingMode)); } // Copy everything but the padding to the output byte[] depadded = new byte[count - padBytes]; Buffer.BlockCopy(block, offset, depadded, 0, depadded.Length); return depadded; } /// <summary> /// Encrypt blocks of plaintext /// </summary> [SecurityCritical] private int EncryptBlocks(byte[] buffer, int offset, int count) { Contract.Requires(m_key != null); Contract.Requires(buffer != null && count <= buffer.Length - offset); Contract.Requires(offset >= 0); Contract.Requires(count > 0 && count % InputBlockSize == 0); Contract.Ensures(Contract.Result<int>() >= 0); // // Do the encryption. Note that CapiSymmetricAlgorithm will do all padding itself since the CLR // supports padding modes that CAPI does not, so we will always tell CAPI that we are not working // with the final block. // int dataLength = count; unsafe { fixed (byte* pData = &buffer[offset]) { if (!CapiNative.UnsafeNativeMethods.CryptEncrypt(m_key, SafeCapiHashHandle.InvalidHandle, false, 0, new IntPtr(pData), ref dataLength, buffer.Length - offset)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } } return dataLength; } /// <summary> /// Calculate the padding for a block of data /// </summary> [SecuritySafeCritical] private byte[] PadBlock(byte[] block, int offset, int count) { Contract.Requires(m_provider != null); Contract.Requires(block != null && count <= block.Length - offset); Contract.Requires(0 <= offset); Contract.Requires(0 <= count); Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length % InputBlockSize == 0); byte[] result = null; int padBytes = InputBlockSize - (count % InputBlockSize); switch (m_paddingMode) { // ANSI padding fills the blocks with zeros and adds the total number of padding bytes as // the last pad byte, adding an extra block if the last block is complete. // // x 00 00 00 00 00 00 07 case PaddingMode.ANSIX923: result = new byte[count + padBytes]; Buffer.BlockCopy(block, 0, result, 0, count); result[result.Length - 1] = (byte)padBytes; break; // ISO padding fills the blocks up with random bytes and adds the total number of padding // bytes as the last pad byte, adding an extra block if the last block is complete. // // xx rr rr rr rr rr rr 07 case PaddingMode.ISO10126: result = new byte[count + padBytes]; CapiNative.UnsafeNativeMethods.CryptGenRandom(m_provider, result.Length - 1, result); Buffer.BlockCopy(block, 0, result, 0, count); result[result.Length - 1] = (byte)padBytes; break; // No padding requires that the input already be a multiple of the block size case PaddingMode.None: if (count % InputBlockSize != 0) { throw new CryptographicException(SR.GetString(SR.Cryptography_PartialBlock)); } result = new byte[count]; Buffer.BlockCopy(block, offset, result, 0, result.Length); break; // PKCS padding fills the blocks up with bytes containing the total number of padding bytes // used, adding an extra block if the last block is complete. // // xx xx 06 06 06 06 06 06 case PaddingMode.PKCS7: result = new byte[count + padBytes]; Buffer.BlockCopy(block, offset, result, 0, count); for (int i = count; i < result.Length; i++) { result[i] = (byte)padBytes; } break; // Zeros padding fills the last partial block with zeros, and does not add a new block to // the end if the last block is already complete. // // xx 00 00 00 00 00 00 00 case PaddingMode.Zeros: if (padBytes == InputBlockSize) { padBytes = 0; } result = new byte[count + padBytes]; Buffer.BlockCopy(block, offset, result, 0, count); break; default: throw new CryptographicException(SR.GetString(SR.Cryptography_UnknownPaddingMode)); } return result; } /// <summary> /// Validate and transform the user's IV into one that we will pass on to CAPI /// /// If we have an IV, make a copy of it so that it doesn't get modified while we're using it. If /// not, and we're not in ECB mode then throw an error, since we cannot decrypt without the IV, and /// generating a random IV to encrypt with would lead to data which is not decryptable. /// /// For compatibility with v1.x, we accept IVs which are longer than the block size, and truncate /// them back. We will reject an IV which is smaller than the block size however. /// </summary> private static byte[] ProcessIV(byte[] iv, int blockSize, CipherMode cipherMode) { Contract.Requires(blockSize % 8 == 0); Contract.Ensures(cipherMode == CipherMode.ECB || (Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length == blockSize / 8)); byte[] realIV = null; if (iv != null) { if (blockSize / 8 <= iv.Length) { realIV = new byte[blockSize / 8]; Buffer.BlockCopy(iv, 0, realIV, 0, realIV.Length); } else { throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidIVSize)); } } else if (cipherMode != CipherMode.ECB) { throw new CryptographicException(SR.GetString(SR.Cryptography_MissingIV)); } return realIV; } /// <summary> /// Do a direct decryption of the ciphertext blocks. This method should not be called from anywhere /// but DecryptBlocks or TransformFinalBlock since it does not account for the depadding buffer and /// direct use could lead to incorrect decryption values. /// </summary> [SecurityCritical] private int RawDecryptBlocks(byte[] buffer, int offset, int count) { Contract.Requires(m_key != null); Contract.Requires(buffer != null && count <= buffer.Length - offset); Contract.Requires(offset >= 0); Contract.Requires(count > 0 && count % InputBlockSize == 0); Contract.Ensures(Contract.Result<int>() >= 0); // // Do the decryption. Note that CapiSymmetricAlgorithm will do all padding itself since the CLR // supports padding modes that CAPI does not, so we will always tell CAPI that we are not working // with the final block. // int dataLength = count; unsafe { fixed (byte* pData = &buffer[offset]) { if (!CapiNative.UnsafeNativeMethods.CryptDecrypt(m_key, SafeCapiHashHandle.InvalidHandle, false, 0, new IntPtr(pData), ref dataLength)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } } return dataLength; } /// <summary> /// Reset the state of the algorithm so that it can begin processing a new message /// </summary> [SecuritySafeCritical] private void Reset() { Contract.Requires(m_key != null); Contract.Ensures(m_depadBuffer == null); // // CryptEncrypt / CryptDecrypt must be called with the Final parameter set to true so that // their internal state is reset. Since we do all padding by hand, this isn't done by // TransformFinalBlock so is done on an empty buffer here. // byte[] buffer = new byte[OutputBlockSize]; int resetSize = 0; unsafe { fixed (byte* pBuffer = buffer) { if (m_encryptionMode == EncryptionMode.Encrypt) { CapiNative.UnsafeNativeMethods.CryptEncrypt(m_key, SafeCapiHashHandle.InvalidHandle, true, 0, new IntPtr(pBuffer), ref resetSize, buffer.Length); } else { CapiNative.UnsafeNativeMethods.CryptDecrypt(m_key, SafeCapiHashHandle.InvalidHandle, true, 0, new IntPtr(pBuffer), ref resetSize); } } } // Also erase the depadding buffer so we don't cross data from the previous message into this one if (m_depadBuffer != null) { Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length); m_depadBuffer = null; } } /// <summary> /// Encrypt or decrypt a single block of data /// </summary> [SecuritySafeCritical] public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { Contract.Ensures(Contract.Result<int>() >= 0); if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer"); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset"); } if (inputCount <= 0) { throw new ArgumentOutOfRangeException("inputCount"); } if (inputCount % InputBlockSize != 0) { throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_MustTransformWholeBlock)); } if (inputCount > inputBuffer.Length - inputOffset) { throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer)); } if (outputBuffer == null) { throw new ArgumentNullException("outputBuffer"); } if (inputCount > outputBuffer.Length - outputOffset) { throw new ArgumentOutOfRangeException("outputOffset", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer)); } if (m_encryptionMode == EncryptionMode.Encrypt) { // CryptEncrypt operates in place, so make a copy of the original data in the output buffer for // it to work on. Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); return EncryptBlocks(outputBuffer, outputOffset, inputCount); } else { return DecryptBlocks(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } } /// <summary> /// Encrypt or decrypt the last block of data in the current message /// </summary> [SecuritySafeCritical] public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { Contract.Ensures(Contract.Result<byte[]>() != null); if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer"); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset"); } if (inputCount < 0) { throw new ArgumentOutOfRangeException("inputCount"); } if (inputCount > inputBuffer.Length - inputOffset) { throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer)); } byte[] outputData = null; if (m_encryptionMode == EncryptionMode.Encrypt) { // If we're encrypting, we need to pad the last block before encrypting it outputData = PadBlock(inputBuffer, inputOffset, inputCount); if (outputData.Length > 0) { EncryptBlocks(outputData, 0, outputData.Length); } } else { // We can't complete decryption on a partial block if (inputCount % InputBlockSize != 0) { throw new CryptographicException(SR.GetString(SR.Cryptography_PartialBlock)); } // // If we have a depad buffer, copy that into the decryption buffer followed by the input data. // Otherwise the decryption buffer is just the input data. // byte[] ciphertext = null; if (m_depadBuffer == null) { ciphertext = new byte[inputCount]; Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, 0, inputCount); } else { ciphertext = new byte[m_depadBuffer.Length + inputCount]; Buffer.BlockCopy(m_depadBuffer, 0, ciphertext, 0, m_depadBuffer.Length); Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, m_depadBuffer.Length, inputCount); } // Decrypt the data, then strip the padding to get the final decrypted data. if (ciphertext.Length > 0) { int decryptedBytes = RawDecryptBlocks(ciphertext, 0, ciphertext.Length); outputData = DepadBlock(ciphertext, 0, decryptedBytes); } else { outputData = new byte[0]; } } Reset(); return outputData; } /// <summary> /// Prepare the cryptographic key for use in the encryption / decryption operation /// </summary> [System.Security.SecurityCritical] private static SafeCapiKeyHandle SetupKey(SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, int feedbackSize) { Contract.Requires(key != null); Contract.Requires(cipherMode == CipherMode.ECB || iv != null); Contract.Requires(0 <= feedbackSize); Contract.Ensures(Contract.Result<SafeCapiKeyHandle>() != null && !Contract.Result<SafeCapiKeyHandle>().IsInvalid && !Contract.Result<SafeCapiKeyHandle>().IsClosed); // Make a copy of the key so that we don't modify the properties of the caller's copy SafeCapiKeyHandle encryptionKey = key.Duplicate(); // Setup the cipher mode first CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.Mode, (int)cipherMode); // If we're not in ECB mode then setup the IV if (cipherMode != CipherMode.ECB) { CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.IV, iv); } // OFB and CFB require a feedback loop size if (cipherMode == CipherMode.CFB || cipherMode == CipherMode.OFB) { CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.ModeBits, feedbackSize); } return encryptionKey; } } }
46.006612
130
0.522562
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/Core/System/Security/Cryptography/CapiSymmetricAlgorithm.cs
27,834
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace MysqlAppModel { static class Program { /// <summary> /// Point d'entrée principal de l'application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Win_Bienvenue() ); } } }
22.695652
65
0.618774
[ "Unlicense" ]
Fab2bprog/Exemple-utilisation-csharp-avec-mysql
MysqlAppModel/Program.cs
525
C#
// Copyright © 2020 EPAM Systems, Inc. All Rights Reserved. All information contained herein is, and remains the // property of EPAM Systems, Inc. and/or its suppliers and is protected by international intellectual // property law. Dissemination of this information or reproduction of this material is strictly forbidden, // unless prior written permission is obtained from EPAM Systems, Inc using Epam.GraphQL.Configuration; using Epam.GraphQL.Loaders; using Epam.GraphQL.Savers; using GraphQL.Types; namespace Epam.GraphQL.Types { internal class SubmitOutputItemGraphType<TProjection, TEntity, TId, TExecutionContext> : ObjectGraphType<SaveResultItem<TEntity, TId>> where TProjection : Projection<TEntity, TExecutionContext>, new() where TEntity : class { public SubmitOutputItemGraphType(RelationRegistry<TExecutionContext> registry) { // TODO Type name should be taken from registry? Name = $"{typeof(TEntity).Name}SubmitOutput"; Field(registry.GenerateGraphType(typeof(TId)), "id", resolve: ctx => ctx.Source.Id); Field(registry.GetEntityGraphType<TProjection, TEntity>(), "payload", resolve: ctx => ctx.Source.Payload); } } }
47.5
138
0.729555
[ "MIT" ]
epam/epam-graphql
src/Epam.GraphQL/Types/SubmitOutputItemGraphType.cs
1,238
C#
using ReactNative.Bridge; using System; using System.Collections.Generic; using Windows.ApplicationModel.Core; using Windows.UI.Core; namespace Spruce.RNSpruce { /// <summary> /// A module that allows JS to share data. /// </summary> class RNSpruceModule : NativeModuleBase { /// <summary> /// Instantiates the <see cref="RNSpruceModule"/>. /// </summary> internal RNSpruceModule() { } /// <summary> /// The name of the native module. /// </summary> public override string Name { get { return "RNSpruce"; } } } }
20.235294
58
0.530523
[ "MIT" ]
devshine2015/ReactNative_Spruce
windows/RNSpruce/RNSpruceModule.cs
688
C#
using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Umbraco.Core.Models.Identity; namespace Umbraco.Core.Security { public class BackOfficeClaimsIdentityFactory<T> : ClaimsIdentityFactory<T, int> where T: BackOfficeIdentityUser { public BackOfficeClaimsIdentityFactory() { SecurityStampClaimType = Constants.Security.SessionIdClaimType; UserNameClaimType = ClaimTypes.Name; } /// <summary> /// Create a ClaimsIdentity from a user /// </summary> /// <param name="manager"/><param name="user"/><param name="authenticationType"/> /// <returns/> public override async Task<ClaimsIdentity> CreateAsync(UserManager<T, int> manager, T user, string authenticationType) { var baseIdentity = await base.CreateAsync(manager, user, authenticationType); var umbracoIdentity = new UmbracoBackOfficeIdentity(baseIdentity, user.Id, user.UserName, user.Name, user.CalculatedContentStartNodeIds, user.CalculatedMediaStartNodeIds, user.Culture, //NOTE - there is no session id assigned here, this is just creating the identity, a session id will be generated when the cookie is written Guid.NewGuid().ToString(), user.SecurityStamp, user.AllowedSections, user.Roles.Select(x => x.RoleId).ToArray()); return umbracoIdentity; } } public class BackOfficeClaimsIdentityFactory : BackOfficeClaimsIdentityFactory<BackOfficeIdentityUser> { } }
36.833333
156
0.635181
[ "MIT" ]
ismailmayat/Umbraco-CMS
src/Umbraco.Core/Security/BackOfficeClaimsIdentityFactory.cs
1,770
C#
namespace Instagraph.ModelsDto { public class UserFollowerDto { public string User { get; set; } public string Follower { get; set; } } }
18.555556
44
0.610778
[ "MIT" ]
sevdalin/Software-University-SoftUni
Db Advanced - EF Core/11. Exam Preparation/Instagraph.ModelsDto/UserFollowerDto.cs
169
C#
using System; namespace Xunit.DependencyInjection { [AttributeUsage(AttributeTargets.Assembly)] public sealed class StartupTypeAttribute : Attribute { public string TypeName { get; } public string? AssemblyName { get; } /// <summary> /// Initializes an instance of <see cref="StartupTypeAttribute" />. /// </summary> /// <param name="typeName">The fully qualified type name of the startup /// (f.e., 'Xunit.DependencyInjection.Test.Startup')</param> /// <param name="assemblyName">The name of the assembly that the startup type /// is located in, without file extension (f.e., 'Xunit.DependencyInjection.Test')</param> public StartupTypeAttribute(string typeName, string? assemblyName = null) { TypeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); AssemblyName = assemblyName; } /// <summary> /// Initializes an instance of <see cref="StartupTypeAttribute" />. /// </summary> /// <param name="startupType">The fully qualified type name of the startup type /// (f.e., 'Xunit.DependencyInjection.Test.Startup')</param> public StartupTypeAttribute(Type startupType) { if (startupType?.FullName == null) throw new ArgumentNullException(nameof(startupType)); TypeName = startupType.FullName; AssemblyName = startupType.Assembly.FullName; } } }
39.5
100
0.63491
[ "MIT" ]
En3Tho/Xunit.DependencyInjection
Xunit.DependencyInjection/StartupTypeAttribute.cs
1,503
C#
using System; namespace ProductRecommendation.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
25.216216
141
0.517685
[ "MIT" ]
sumitjangid/Demo-Angular-2-with-ASP.NET-Web-API
ProductRecommendation/ProductRecommendation/Areas/HelpPage/SampleGeneration/TextSample.cs
933
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("MobileNotification.DAL.Model")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MobileNotification.DAL.Model")] [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("3e95de41-1fa4-49d9-878f-7b82df574dd6")] // 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.621622
84
0.748076
[ "Apache-2.0" ]
berkaybasoz/Push-Sharp-Sample
MobileNotification.DAL.Model/Properties/AssemblyInfo.cs
1,432
C#
// <auto-generated /> using AspNetVideoCore.Data; using AspNetVideoCore.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace AspNetVideoCore.Migrations { [DbContext(typeof(VideoDbContext))] partial class VideoDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AspNetVideoCore.Entities.User", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("AspNetVideoCore.Entities.Video", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("Genre"); b.Property<string>("Title") .IsRequired() .HasMaxLength(80); b.HasKey("Id"); b.ToTable("Videos"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("AspNetVideoCore.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("AspNetVideoCore.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("AspNetVideoCore.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("AspNetVideoCore.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.352227
117
0.474023
[ "MIT" ]
csharpschool/AspNetVideoCore
AspNetVideoCore/Migrations/VideoDbContextModelSnapshot.cs
8,240
C#
namespace UniversitySystem.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
20
70
0.67
[ "MIT" ]
Nextttttt/ASP.NET-CourseWork
UniversitySystem/Models/ErrorViewModel.cs
200
C#
namespace CloudinaryDotNet.Actions { using System; using System.Collections.Generic; /// <summary> /// Parameters for deletion of resources. /// </summary> public class DelResParams : BaseParams { private List<string> m_publicIds = new List<string>(); private string m_prefix; private string m_tag; private bool m_all; /// <summary> /// Initializes a new instance of the <see cref="DelResParams"/> class. /// </summary> public DelResParams() { Type = "upload"; } /// <summary> /// Gets or sets the type of file to delete. Default: image. Optional. /// </summary> public ResourceType ResourceType { get; set; } /// <summary> /// Gets or sets the storage type: upload, private, authenticated, facebook, twitter, gplus, instagram_name, /// gravatar, youtube, hulu, vimeo, animoto, worldstarhiphop or dailymotion. Default: upload. Optional. /// </summary> public string Type { get; set; } /// <summary> /// Gets or sets a value indicating whether if true, delete only the derived images of the matching resources. /// </summary> public bool KeepOriginal { get; set; } /// <summary> /// Gets or sets a value indicating whether whether to invalidate CDN cache copies of a previously uploaded image that shares the same public ID. /// Default: false. /// </summary> public bool Invalidate { get; set; } /// <summary> /// Gets or sets whether to continue deletion from the given cursor. Notice that it doesn't have a lot of meaning unless the /// <see cref="KeepOriginal"/> flag is set to True. /// </summary> public string NextCursor { get; set; } /// <summary> /// Gets or sets whether to delete all resources with the given public IDs (array of up to 100 public_ids). /// </summary> public List<string> PublicIds { get { return m_publicIds; } set { m_publicIds = value; m_prefix = string.Empty; m_tag = string.Empty; m_all = false; } } /// <summary> /// Gets or sets whether to delete all resources, including derived resources, where the public ID starts with the given prefix /// (up to a maximum of 1000 original resources). /// </summary> public string Prefix { get { return m_prefix; } set { m_publicIds = null; m_tag = string.Empty; m_prefix = value; m_all = false; } } /// <summary> /// Gets or sets whether to delete all resources (and their derivatives) with the given tag name (up to a maximum of 1000 original /// resources). /// </summary> public string Tag { get { return m_tag; } set { m_publicIds = null; m_prefix = string.Empty; m_tag = value; m_all = false; } } /// <summary> /// Gets or sets a value indicating whether optional. Get or set whether to delete all resources (of the relevant resource type and type), including /// derived resources (up to a maximum of 1000 original resources). Default: false. /// </summary> public bool All { get { return m_all; } set { if (value) { m_publicIds = null; m_prefix = string.Empty; m_tag = string.Empty; m_all = value; } else { m_all = value; } } } /// <summary> /// Gets or sets a list of transformations. When provided, only derived resources matched by the transformations /// would be deleted. /// </summary> public List<Transformation> Transformations { get; set; } /// <summary> /// Validate object model. /// </summary> public override void Check() { if ((PublicIds == null || PublicIds.Count == 0) && string.IsNullOrEmpty(Prefix) && string.IsNullOrEmpty(Tag) && !All) { throw new ArgumentException("Either PublicIds or Prefix or Tag must be specified!"); } } /// <summary> /// Maps object model to dictionary of parameters in cloudinary notation. /// </summary> /// <returns>Sorted dictionary of parameters.</returns> public override SortedDictionary<string, object> ToParamsDictionary() { SortedDictionary<string, object> dict = base.ToParamsDictionary(); AddParam(dict, "invalidate", Invalidate); AddParam(dict, "next_cursor", NextCursor); if (Transformations != null && Transformations.Count > 0) { AddParam(dict, "transformations", string.Join("|", Transformations)); } AddParam(dict, "keep_original", KeepOriginal); if (!string.IsNullOrEmpty(Tag)) { return dict; } if (!string.IsNullOrEmpty(Prefix)) { dict.Add("prefix", Prefix); } else if (PublicIds != null && PublicIds.Count > 0) { dict.Add("public_ids", PublicIds); } if (m_all) { AddParam(dict, "all", true); } return dict; } } }
30.703518
156
0.498363
[ "MIT" ]
Ezeji/CloudinaryDotNet
CloudinaryDotNet/Actions/AssetsManagement/DelResParams.cs
6,112
C#
using System; using Forms.Core.Options; using Forms.Infrastructure; using Forms.Web.Middleware; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Forms.Web { public class Startup { public IConfiguration Configuration { get; } private bool IsDevelopment { get; } public Startup(IConfiguration configuration, IWebHostEnvironment appEnv) { Configuration = configuration; IsDevelopment = appEnv.IsDevelopment(); } public void ConfigureServices(IServiceCollection services) { // Auth services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x => { x.Cookie.HttpOnly = true; x.Cookie.SecurePolicy = CookieSecurePolicy.Always; x.LoginPath = "/"; x.SlidingExpiration = true; x.ExpireTimeSpan = TimeSpan.FromMinutes(30); }); services.AddControllersWithViews(x => { x.Filters.Add(new GlobalExceptionFilter()); }); services.AddHsts(options => { options.MaxAge = TimeSpan.FromDays(365); }); // Services services.AddHttpContextAccessor(); services.AddCoreServices(Configuration); // Infrastructure var redisConnectionFactory = services.AddCacheFramework(Configuration, IsDevelopment); services.AddEmailFramework(Configuration); // Data protection keys services.AddDataProtection().PersistKeysToStackExchangeRedis(redisConnectionFactory.GetDatabase().Multiplexer, "DataProtection-Keys"); // Options services.Configure<FormOptions>(Configuration.GetSection("Forms")); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseStatusCodePagesWithRedirects("~/StatusCode/{0}"); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
33.595745
146
0.58898
[ "Apache-2.0" ]
mod-veterans/digital-service-web-app
Forms.Web/Startup.cs
3,158
C#
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RecipeApplication.Data { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { } }
23.5
95
0.778116
[ "MIT" ]
AnzhelikaKravchuk/asp-dot-net-core-in-action-2e
Chapter14/B_RecipeApplication_LocalDb/RecipeApplication/Data/ApplicationUser.cs
331
C#
/**************************************************************** * * * Legacy version of the library maintained to support Nav 2018 * * * ****************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnZwDev.ALTools.Server.Nav2018.Contracts { public class GetSyntaxTreeSymbolRequest { public string path { get; set; } public int[] symbolPath { get; set; } } }
29.5
66
0.423729
[ "MIT" ]
hemisphera/az-al-dev-tools-server
AZALDevToolsServer/AnZwDev.ALTools.Server.Nav2018/Contracts/GetSyntaxTreeSymbolRequest.cs
651
C#
using Alachisoft.NCache.Common.Caching; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; namespace Alachisoft.NCache.Common { public class SeralizationHelper : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { Type typeToDeserialize = null; if(typeName == "Alachisoft.NCache.Caching.SmallUserBinaryObject") { return typeof(SmallUserBinaryObject); } if (typeName == "Alachisoft.NCache.Caching.LargeUserBinaryObject") { return typeof(LargeUserBinaryObject); } if(assemblyName.Contains("Alachisoft")) { var split = assemblyName.Split(new char[] { ' ' }); var currentSplit = Assembly.GetExecutingAssembly().FullName.Split(new char[] { ' ' }); split[1] = currentSplit[1]; assemblyName = string.Concat(split); } typeToDeserialize = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName)); return typeToDeserialize; } } }
29.785714
102
0.602718
[ "Apache-2.0" ]
Alachisoft/NCache
Src/NCCommon/Util/SeralizationHelper.cs
1,253
C#
using FreeSql.DataAnnotations; using FreeSql; using System; using System.Collections.Generic; using Xunit; using System.Linq; using Newtonsoft.Json.Linq; using NpgsqlTypes; using Npgsql.LegacyPostgis; using System.Linq.Expressions; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.Threading; using System.Data.SqlClient; using kwlib; using System.Diagnostics; using System.IO; using System.Text; using Newtonsoft.Json; using System.Net.NetworkInformation; using System.Net; using System.Collections; namespace FreeSql.Tests { public class UnitTest3 { public class Song23 { public long Id { get; set; } public string Name { get; set; } } public class Author23 { public long Id { get; set; } public long SongId { get; set; } public string Name { get; set; } } public class TestDbContext : DbContext { public TestDbContext(IFreeSql orm) : base(orm, null) { } public DbSet<Song23> Songs { get; set; } public DbSet<Author23> Authors { get; set; } } /// <summary> /// 父级 /// </summary> public class BaseModel { [Column(IsPrimary = true)] public string ID { get; set; } /// <summary> /// 创建人 /// </summary> public string UserID { get; set; } = "Admin"; /// <summary> /// 创建时间 /// </summary> [Column(ServerTime = DateTimeKind.Utc)] public DateTime CreateTime { get; set; } /// <summary> /// 备注 /// </summary> public string Description { get; set; } } public class Menu : BaseModel { public string SubNameID { get; set; } /// <summary> /// 菜单名称 /// </summary> public string Name { get; set; } /// <summary> /// 英文名称 /// </summary> public string EnName { get; set; } /// <summary> /// 链接地址 /// </summary> public string Url { get; set; } /// <summary> /// 父级菜单 一级为 0 /// </summary> public string ParentID { get; set; } /// <summary> /// 按钮操作 逗号分隔 /// </summary> public string OperationIds { get; set; } /// <summary> /// 导航属性 /// </summary> public virtual Menu Parent { get; set; } [Column(IsIgnore = true)] public string OperationNames { get; set; } [Column(IsIgnore = true)] public string SystemName { get; set; } } class SubSystem { public string Id { get; set; } public string Name { get; set; } } public interface EdiInterface { List<EdiItem> Children { get; set; } } [Table(Name = "EDI")] public class Edi : EdiInterface { [Column(Name = "EDI_ID")] public long Id { get; set; } public List<EdiItem> Children { get; set; } } [Table(Name = "EDI_ITEM")] public class EdiItem { [Column(Name = "EDII_ID")] public long Id { get; set; } [Column(Name = "EDII_EDI_ID")] public long EdiId { get; set; } } public class Song123 { public long Id { get; set; } protected Song123() { } public Song123(long id) => Id = id; } public class Author123 { public long Id { get; set; } public long SongId { get; set; } public Author123(long id, long songId) { Id = id; SongId = songId; } } class testInsertNullable { [Column(IsNullable = false, IsIdentity = true)] public long Id { get; set; } [Column(IsNullable = false)] public string str1 { get; set; } [Column(IsNullable = false)] public int? int1 { get; set; } [Column(IsNullable = true)] public int int2 { get; set; } [Column(Precision = 10, Scale = 5)] public decimal? price { get; set; } } class testUpdateNonePk { public string name { get; set; } } class tq01 { public Guid id { get; set; } } class t102 { public Guid id { get; set; } public bool isxx { get; set; } } public class tcate01 { [Column(IsIdentity = true)] public int? Id { get; set; } public string name { get; set; } [Navigate(nameof(tshop01.cateId))] public List<tshop01> tshops { get; set; } } public class tshop01 { public Guid Id { get; set; } public int cateId { get; set; } public tcate01 cate { get; set; } } [Fact] public void Test03() { g.sqlite.Delete<tcate01>().Where("1=1").ExecuteAffrows(); g.sqlite.Delete<tshop01>().Where("1=1").ExecuteAffrows(); var tshoprepo = g.sqlite.GetRepository<tcate01>(); tshoprepo.DbContextOptions.EnableAddOrUpdateNavigateList = true; tshoprepo.Insert(new tcate01[] { new tcate01 { name = "tcate1", tshops = new List<tshop01>{ new tshop01(), new tshop01(), new tshop01() } }, new tcate01 { name = "tcate1", tshops = new List<tshop01>{ new tshop01(), new tshop01(), new tshop01() } } }); var tshop01sql = g.sqlite.Select<tshop01>().Include(a => a.cate).ToSql(); var tshop02sql = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate").ToSql(); var tshop03sql = g.sqlite.Select<tshop01>().IncludeMany(a => a.cate.tshops).ToSql(); var tshop04sql = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate.tshops").ToSql(); var tshop01lst = g.sqlite.Select<tshop01>().Include(a => a.cate).ToList(); var tshop02lst = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate").ToList(); var tshop03lst = g.sqlite.Select<tshop01>().IncludeMany(a => a.cate.tshops).ToList(); var tshop04lst = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate.tshops").ToList(); var testisnullsql1 = g.sqlite.Select<t102>().Where(a => SqlExt.IsNull(a.isxx, false).Equals( true)).ToSql(); var testisnullsql2 = g.sqlite.Select<t102>().Where(a => SqlExt.IsNull(a.isxx, false).Equals(false)).ToSql(); var guid1 = Guid.NewGuid(); var guid2 = Guid.NewGuid(); var guid3 = Guid.NewGuid(); var tqsql = g.sqlite.Select<tq01, t102, t102>() .WithSql( g.sqlite.Select<tq01>().As("sub1").Where(a => a.id == guid1).ToSql(), g.sqlite.Select<t102>().As("sub2").Where(a => a.id == guid2).ToSql(), g.sqlite.Select<t102>().As("sub3").Where(a => a.id == guid3).ToSql() ) .LeftJoin((a, b, c) => a.id == b.id) .LeftJoin((a, b, c) => b.id == c.id) .ToSql(); var updateSql = g.sqlite.Update<object>() .AsType(typeof(testInsertNullable)) .SetDto(new { str1 = "xxx" }) .WhereDynamic(1) .ToSql(); var sqlextMax112 = g.sqlserver.Select<EdiItem>() .GroupBy(a => a.Id) .ToSql(a => new { Id = a.Key, EdiId1 = SqlExt.Max(a.Key).Over().PartitionBy(new { a.Value.EdiId, a.Value.Id }).OrderByDescending(new { a.Value.EdiId, a.Value.Id }).ToValue(), EdiId2 = SqlExt.Max(a.Key).Over().PartitionBy(a.Value.EdiId).OrderByDescending(a.Value.Id).ToValue(), EdiId3 = SqlExt.Sum(a.Key).ToValue(), EdiId4 = a.Sum(a.Key) }); Assert.Throws<ArgumentException>(() => g.sqlite.Update<testUpdateNonePk>().SetSource(new testUpdateNonePk()).ExecuteAffrows()); g.sqlite.Insert(new testInsertNullable()).NoneParameter().ExecuteAffrows(); g.sqlite.Select<testInsertNullable>().Select(a => a.Id).ToList(); var ddlsql = g.sqlite.CodeFirst.GetComparisonDDLStatements(typeof(testInsertNullable), "tb123123"); Assert.Equal(@"CREATE TABLE IF NOT EXISTS ""main"".""tb123123"" ( ""Id"" INTEGER PRIMARY KEY AUTOINCREMENT, ""str1"" NVARCHAR(255) NOT NULL, ""int1"" INTEGER NOT NULL, ""int2"" INTEGER , ""price"" DECIMAL(10,5) ) ; ", ddlsql); var select16Sql1 = g.sqlite.Select<userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo>() .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => b.userid == a.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => c.userid == b.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => d.userid == c.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => e.userid == d.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => f.userid == e.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => g.userid == f.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => h.userid == g.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => i.userid == h.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => j.userid == i.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => k.userid == j.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => l.userid == k.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => m.userid == l.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => n.userid == m.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => o.userid == n.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => p.userid == o.userid) .ToSql((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => p); Assert.Equal(@"SELECT p.""userid"" as1, p.""badgenumber"" as2, p.""ssn"" as3, p.""IDCardNo"" as4, p.""name"" as5, p.""title"" as6, p.""birthday"" as7, p.""hiredday"" as8, p.""hetongdate"" as9, p.""street"" as10, p.""zip"" as11, p.""ophone"" as12, p.""pager"" as13, p.""fphone"" as14, p.""CardNo"" as15, p.""email"" as16, p.""idcardvalidtime"" as17, p.""homeaddress"" as18, p.""minzu"" as19, p.""leavedate"" as20, p.""loginpass"" as21, p.""picurl"" as22, p.""managerid"" as23 FROM ""userinfo"" a INNER JOIN ""userinfo"" b ON b.""userid"" = a.""userid"" INNER JOIN ""userinfo"" c ON c.""userid"" = b.""userid"" INNER JOIN ""userinfo"" d ON d.""userid"" = c.""userid"" INNER JOIN ""userinfo"" e ON e.""userid"" = d.""userid"" INNER JOIN ""userinfo"" f ON f.""userid"" = e.""userid"" INNER JOIN ""userinfo"" g ON g.""userid"" = f.""userid"" INNER JOIN ""userinfo"" h ON h.""userid"" = g.""userid"" INNER JOIN ""userinfo"" i ON i.""userid"" = h.""userid"" INNER JOIN ""userinfo"" j ON j.""userid"" = i.""userid"" INNER JOIN ""userinfo"" k ON k.""userid"" = j.""userid"" INNER JOIN ""userinfo"" l ON l.""userid"" = k.""userid"" INNER JOIN ""userinfo"" m ON m.""userid"" = l.""userid"" INNER JOIN ""userinfo"" n ON n.""userid"" = m.""userid"" INNER JOIN ""userinfo"" o ON o.""userid"" = n.""userid"" INNER JOIN ""userinfo"" p ON p.""userid"" = o.""userid""", select16Sql1); var select16Sql2 = g.sqlite.Select<userinfo>() .From<userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo>( (s, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => s .InnerJoin(a => b.userid == a.userid) .InnerJoin(a => c.userid == b.userid) .InnerJoin(a => d.userid == c.userid) .InnerJoin(a => e.userid == d.userid) .InnerJoin(a => f.userid == e.userid) .InnerJoin(a => g.userid == f.userid) .InnerJoin(a => h.userid == g.userid) .InnerJoin(a => i.userid == h.userid) .InnerJoin(a => j.userid == i.userid) .InnerJoin(a => k.userid == j.userid) .InnerJoin(a => l.userid == k.userid) .InnerJoin(a => m.userid == l.userid) .InnerJoin(a => n.userid == m.userid) .InnerJoin(a => o.userid == n.userid) .InnerJoin(a => p.userid == o.userid) ) .ToSql((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => p); Assert.Equal(@"SELECT p.""userid"" as1, p.""badgenumber"" as2, p.""ssn"" as3, p.""IDCardNo"" as4, p.""name"" as5, p.""title"" as6, p.""birthday"" as7, p.""hiredday"" as8, p.""hetongdate"" as9, p.""street"" as10, p.""zip"" as11, p.""ophone"" as12, p.""pager"" as13, p.""fphone"" as14, p.""CardNo"" as15, p.""email"" as16, p.""idcardvalidtime"" as17, p.""homeaddress"" as18, p.""minzu"" as19, p.""leavedate"" as20, p.""loginpass"" as21, p.""picurl"" as22, p.""managerid"" as23 FROM ""userinfo"" a INNER JOIN ""userinfo"" b ON b.""userid"" = a.""userid"" INNER JOIN ""userinfo"" c ON c.""userid"" = b.""userid"" INNER JOIN ""userinfo"" d ON d.""userid"" = c.""userid"" INNER JOIN ""userinfo"" e ON e.""userid"" = d.""userid"" INNER JOIN ""userinfo"" f ON f.""userid"" = e.""userid"" INNER JOIN ""userinfo"" g ON g.""userid"" = f.""userid"" INNER JOIN ""userinfo"" h ON h.""userid"" = g.""userid"" INNER JOIN ""userinfo"" i ON i.""userid"" = h.""userid"" INNER JOIN ""userinfo"" j ON j.""userid"" = i.""userid"" INNER JOIN ""userinfo"" k ON k.""userid"" = j.""userid"" INNER JOIN ""userinfo"" l ON l.""userid"" = k.""userid"" INNER JOIN ""userinfo"" m ON m.""userid"" = l.""userid"" INNER JOIN ""userinfo"" n ON n.""userid"" = m.""userid"" INNER JOIN ""userinfo"" o ON o.""userid"" = n.""userid"" INNER JOIN ""userinfo"" p ON p.""userid"" = o.""userid""", select16Sql2); var sqlxx = g.pgsql.InsertOrUpdate<userinfo>().SetSource(new userinfo { userid = 10 }).UpdateColumns(a => new { a.birthday, a.CardNo }).ToSql(); var aff1 = g.sqlite.GetRepository<Edi, long>().Delete(10086); var aff2 = g.sqlite.Delete<Edi>(10086).ExecuteAffrows(); Assert.Equal(aff1, aff2); g.sqlserver.Delete<Edi>().Where("1=1").ExecuteAffrows(); g.sqlserver.Delete<EdiItem>().Where("1=1").ExecuteAffrows(); g.sqlserver.Insert(new[] { new Edi { Id = 1 }, new Edi { Id = 2 }, new Edi { Id = 3 }, new Edi { Id = 4 }, new Edi { Id = 5 } }).ExecuteAffrows(); g.sqlserver.Insert(new[] { new EdiItem { Id = 1, EdiId = 1 }, new EdiItem { Id = 2, EdiId = 1 }, new EdiItem { Id = 3, EdiId = 1 } , new EdiItem { Id = 4, EdiId = 2 }, new EdiItem { Id = 5, EdiId = 2 }, new EdiItem { Id = 6, EdiId = 3 }, new EdiItem { Id = 7, EdiId = 3 }, new EdiItem { Id = 8, EdiId = 4 }, new EdiItem { Id = 9, EdiId = 4 }, new EdiItem { Id = 10, EdiId = 5 }, new EdiItem { Id = 11, EdiId = 5 }, }).ExecuteAffrows(); var testStringFormat = g.sqlite.Select<Edi>().First(a => new { str = $"x{a.Id}_{DateTime.Now.ToString("yyyyMM")}z", str2 = string.Format("{0}x{0}_{1}z", a.Id, DateTime.Now.ToString("yyyyMM")) }); var sql123 = g.sqlserver.Select<Edi>() .WithSql( g.sqlserver.Select<Edi>().ToSql(a => new { a.Id }, FieldAliasOptions.AsProperty) + " UNION ALL " + g.sqlserver.Select<Edi>().ToSql(a => new { a.Id }, FieldAliasOptions.AsProperty)) .Page(1, 10).ToSql("Id"); var sqlextMax1 = g.sqlserver.Select<EdiItem>() .GroupBy(a => a.Id) .ToSql(a => new { Id = a.Key, EdiId1 = SqlExt.Max(a.Key).Over().PartitionBy(new { a.Value.EdiId, a.Value.Id }).OrderByDescending(new { a.Value.EdiId, a.Value.Id }).ToValue(), EdiId2 = SqlExt.Max(a.Key).Over().PartitionBy(a.Value.EdiId).OrderByDescending(a.Value.Id).ToValue(), EdiId3 = SqlExt.Sum(a.Key).ToValue(), EdiId4 = a.Sum(a.Key) }); var sqlextIsNull = g.sqlserver.Select<EdiItem>() .ToSql(a => new { nvl = SqlExt.IsNull(a.EdiId, 0) }); var sqlextGroupConcat = g.mysql.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), groupct1 = SqlExt.GroupConcat(a.Id).Distinct().OrderBy(b.EdiId).Separator("_").ToValue(), testb1 = b == null ? 1 : 0, testb2 = b != null ? 1 : 0, }); var sqlextGroupConcatToList = g.mysql.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToList((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), groupct1 = SqlExt.GroupConcat(a.Id).Distinct().OrderBy(b.EdiId).Separator("_").ToValue(), testb1 = b == null ? 1 : 0, testb2 = b != null ? 1 : 0, }); var sqlextCase = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue(), }); var sqlextCaseToList = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToList((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue(), }); var sqlextCaseGroupBy1 = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .GroupBy((a, b) => new { aid = a.Id, bid = b.Id }) .ToDictionary(a => new { sum = a.Sum(a.Value.Item2.EdiId), testb1 = a.Value.Item2 == null ? 1 : 0, testb2 = a.Value.Item2 != null ? 1 : 0, }); var sqlextCaseGroupBy2 = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .GroupBy((a, b) => new { aid = a.Id, bid = b.Id }) .ToList(a => new { a.Key, sum = a.Sum(a.Value.Item2.EdiId), testb1 = a.Value.Item2 == null ? 1 : 0, testb2 = a.Value.Item2 != null ? 1 : 0, }); var sqlextOver = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id, over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue() }); var sqlextOverToList = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToList((a, b) => new { Id = a.Id, EdiId = b.Id, over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue() }); var tttrule = 8; var tttid = new long[] { 18, 19, 4017 }; g.sqlserver.Update<Author123>().Set(it => it.SongId == (short)(it.SongId & ~tttrule)).Where(it => (it.SongId & tttrule) == tttrule && !tttid.Contains(it.Id)).ExecuteAffrows(); g.sqlite.Delete<Song123>().Where("1=1").ExecuteAffrows(); g.sqlite.Delete<Author123>().Where("1=1").ExecuteAffrows(); g.sqlite.Insert(new Song123(1)).ExecuteAffrows(); g.sqlite.Insert(new Author123(11, 1)).ExecuteAffrows(); var song = g.sqlite.Select<Song123>() .From<Author123>((a, b) => a.InnerJoin(a1 => a1.Id == b.SongId)) .First((a, b) => a); // throw error Console.WriteLine(song == null); g.sqlite.Select<Edi>().ToList(); var itemId2 = 2; var itemId = 1; var edi = g.sqlite.Select<Edi>() .Where(a => a.Id == itemId2 && g.sqlite.Select<EdiItem>().Where(b => b.Id == itemId).Any()) .First(a => a); //#231 var lksdjkg1 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).Where(a => a.Id == 1).ToList(); var lksdjkg11 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).Where(a => a.Id == 1).Any(); var lksdjkg2 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).First(); var lksdjkg3 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).FirstOrDefault(); var sql222efe = g.sqlite.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == g.sqlite.Select<EdiItem>().As("c").Where(c => c.EdiId == a.Id).OrderBy(c => c.Id).ToOne(c => c.Id)) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id }); var subSyetemId = "xxx"; var list = g.sqlite.Select<Menu, SubSystem>() .LeftJoin((a,b) => a.SubNameID == b.Id) .WhereIf(!string.IsNullOrEmpty(subSyetemId), (a, s) => a.SubNameID == subSyetemId) .ToList((a, s) => new Menu { ID = a.ID, SystemName = s.Name, SubNameID = s.Id, CreateTime = a.CreateTime, Description = a.Description, EnName = a.EnName, Name = a.Name, OperationIds = a.OperationIds, Parent = a.Parent, ParentID = a.ParentID, Url = a.Url, UserID = a.UserID }); var context = new TestDbContext(g.sqlite); var sql = context.Songs .Where(a => context.Authors //.Select //加上这句就不报错,不加上报 variable 'a' of type 'Song' referenced from scope '', but it is not defined .Where(b => b.SongId == a.Id) .Any()) .ToSql(a => a.Name); sql = context.Songs .Where(a => context.Authors .Select //加上这句就不报错,不加上报 variable 'a' of type 'Song' referenced from scope '', but it is not defined .Where(b => b.SongId == a.Id) .Any()) .ToSql(a => a.Name); //using (var conn = new SqlConnection("Data Source=.;Integrated Security=True;Initial Catalog=webchat-abc;Pooling=true;Max Pool Size=13")) //{ // conn.Open(); // conn.Close(); //} //using (var fsql = new FreeSql.FreeSqlBuilder() // .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=webchat-abc;Pooling=true;Max Pool Size=13") // .UseAutoSyncStructure(true) // //.UseGenerateCommandParameterWithLambda(true) // .UseMonitorCommand( // cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText) //监听SQL命令对象,在执行前 // //, (cmd, traceLog) => Console.WriteLine(traceLog) // ) // .UseLazyLoading(true) // .Build()) //{ // fsql.Select<ut3_t1>().ToList(); //} //var testByte = new TestByte { pic = File.ReadAllBytes(@"C:\Users\28810\Desktop\71500003-0ad69400-289e-11ea-85cb-36a54f52ebc0.png") }; //var sql = g.sqlserver.Insert(testByte).NoneParameter().ToSql(); //g.sqlserver.Insert(testByte).NoneParameter().ExecuteAffrows(); //var getTestByte = g.sqlserver.Select<TestByte>(testByte).First(); //File.WriteAllBytes(@"C:\Users\28810\Desktop\71500003-0ad69400-289e-11ea-85cb-36a54f52ebc0_write.png", getTestByte.pic); var ib = new IdleBus<IFreeSql>(TimeSpan.FromMinutes(10)); ib.Notice += (_, e2) => Trace.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e2.Log}"); ib.Register("db1", () => new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=3") .UseAutoSyncStructure(true) .UseGenerateCommandParameterWithLambda(true) .UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText)) .UseLazyLoading(true) .Build()); ib.Register("db2", () => new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=3") .UseAutoSyncStructure(true) .UseGenerateCommandParameterWithLambda(true) .UseLazyLoading(true) .UseNameConvert(FreeSql.Internal.NameConvertType.ToUpper) .UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText)) .Build()); ib.Register("db3", () => new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=3") .UseAutoSyncStructure(true) .UseGenerateCommandParameterWithLambda(true) .UseLazyLoading(true) .UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText)) .Build()); //...注入很多个 var fsql = ib.Get("db1"); //使用的时候用 Get 方法,不要存其引用关系 var sqlparamId = 100; fsql.Select<ut3_t1>().Limit(10).Where(a => a.id == sqlparamId).ToList(); fsql = ib.Get("db2"); fsql.Select<ut3_t1>().Limit(10).Where(a => a.id == sqlparamId).ToList(); fsql = ib.Get("db3"); fsql.Select<ut3_t1>().Limit(10).Where(a => a.id == sqlparamId).ToList(); fsql = g.sqlserver; fsql.Insert<OrderMain>(new OrderMain { OrderNo = "1001", OrderTime = new DateTime(2019, 12, 01) }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1001", ItemNo = "I001", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1001", ItemNo = "I002", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1001", ItemNo = "I003", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderMain>(new OrderMain { OrderNo = "1002", OrderTime = new DateTime(2019, 12, 02) }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1002", ItemNo = "I011", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1002", ItemNo = "I012", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1002", ItemNo = "I013", Qty = 1 }).ExecuteAffrows(); fsql.Ado.Query<object>("select * from orderdetail left join ordermain on orderdetail.orderno=ordermain.orderno where ordermain.orderno='1001'"); g.oracle.Delete<SendInfo>().Where("1=1").ExecuteAffrows(); g.oracle.Insert(new[] { new SendInfo{ Code = "001", Binary = Encoding.UTF8.GetBytes("我是中国人") }, new SendInfo{ Code = "002", Binary = Encoding.UTF8.GetBytes("我是地球人") }, new SendInfo{ Code = "003", Binary = Encoding.UTF8.GetBytes("我是.net")}, new SendInfo{ Code = "004", Binary = Encoding.UTF8.GetBytes("我是freesql") }, new SendInfo{ Code = "005", Binary = Encoding.UTF8.GetBytes("我是freesql233") }, }) .NoneParameter() .BatchOptions(3, 200) .BatchProgress(a => Trace.WriteLine($"{a.Current}/{a.Total}")) .ExecuteAffrows(); var slslsl = g.oracle.Select<SendInfo>().ToList(); var slsls1Ids = slslsl.Select(a => a.ID).ToArray(); var slslss2 = g.oracle.Select<SendInfo>().Where(a => slsls1Ids.Contains(a.ID)).ToList(); var mt_codeId = Guid.Parse("2f48c5ca-7257-43c8-9ee2-0e16fa990253"); Assert.Equal(1, g.oracle.Insert(new SendInfo { ID = mt_codeId, Code = "mt_code", Binary = Encoding.UTF8.GetBytes("我是mt_code") }) .ExecuteAffrows()); var mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == mt_codeId).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code", mt_code.Code); mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == Guid.Parse("2f48c5ca725743c89ee20e16fa990253".ToUpper())).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code", mt_code.Code); mt_codeId = Guid.Parse("2f48c5ca-7257-43c8-9ee2-0e16fa990251"); Assert.Equal(1, g.oracle.Insert(new SendInfo { ID = mt_codeId, Code = "mt_code2", Binary = Encoding.UTF8.GetBytes("我是mt_code2") }) .NoneParameter() .ExecuteAffrows()); mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == mt_codeId).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code2", mt_code.Code); mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == Guid.Parse("2f48c5ca725743c89ee20e16fa990251".ToUpper())).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code2", mt_code.Code); var id = g.oracle.Insert(new TestORC12()).ExecuteIdentity(); } class TestORC12 { [Column(IsIdentity = true, InsertValueSql = "\"TAG_SEQ_ID\".nextval")] public int Id { get; set; } } [Table(Name = "t_text")] public class SendInfo { [Column(IsPrimary = true, DbType = "raw(16)", MapType = typeof(byte[]))] public Guid ID { get; set; } [Column(Name = "YPID5")] public string Code { get; set; } public byte[] Binary { get; set; } [Column(ServerTime = DateTimeKind.Utc, CanUpdate = false)] public DateTime 创建时间 { get; set; } [Column(ServerTime = DateTimeKind.Utc)] public DateTime 更新时间 { get; set; } [Column(InsertValueSql = "'123'")] public string InsertValue2 { get; set; } } class TestByte { public Guid id { get; set; } [Column(DbType = "varbinary(max)")] public byte[] pic { get; set; } } class ut3_t1 { [Column(IsIdentity = true)] public int id { get; set; } public string name { get; set; } } class ut3_t2 { [Column(IsIdentity = true)] public int id { get; set; } public string name { get; set; } } public class OrderMain { public string OrderNo { get; set; } public DateTime OrderTime { get; set; } public decimal Amount { get; set; } } public class OrderDetail { public string OrderNo { get; set; } public string ItemNo { get; set; } public decimal Qty { get; set; } } } }
44.540609
487
0.495612
[ "MIT" ]
5653325/FreeSql
FreeSql.Tests/FreeSql.Tests/UnitTest3.cs
35,380
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SimpleWorkflow.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations { /// <summary> /// RequestCancelWorkflowExecution Request Marshaller /// </summary> public class RequestCancelWorkflowExecutionRequestMarshaller : IMarshaller<IRequest, RequestCancelWorkflowExecutionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((RequestCancelWorkflowExecutionRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(RequestCancelWorkflowExecutionRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleWorkflow"); string target = "SimpleWorkflowService.RequestCancelWorkflowExecution"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.0"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-01-25"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetDomain()) { context.Writer.WritePropertyName("domain"); context.Writer.Write(publicRequest.Domain); } if(publicRequest.IsSetRunId()) { context.Writer.WritePropertyName("runId"); context.Writer.Write(publicRequest.RunId); } if(publicRequest.IsSetWorkflowId()) { context.Writer.WritePropertyName("workflowId"); context.Writer.Write(publicRequest.WorkflowId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static RequestCancelWorkflowExecutionRequestMarshaller _instance = new RequestCancelWorkflowExecutionRequestMarshaller(); internal static RequestCancelWorkflowExecutionRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static RequestCancelWorkflowExecutionRequestMarshaller Instance { get { return _instance; } } } }
36.726496
175
0.628811
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/SimpleWorkflow/Generated/Model/Internal/MarshallTransformations/RequestCancelWorkflowExecutionRequestMarshaller.cs
4,297
C#
/* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg.Font; using MatterHackers.Agg.VertexSource; using MatterHackers.VectorMath; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; namespace MatterHackers.Agg.UI { public class InternalTextEditWidget : GuiWidget { private static ReadOnlyCollection<char> defaultWordBreakChars; private static ReadOnlyCollection<char> DefaultWordBreakChars { get { if (defaultWordBreakChars == null) { char[] defaultList = new char[] { ' ', '\n', '(', ')' }; defaultWordBreakChars = new ReadOnlyCollection<char>(defaultList); } return defaultWordBreakChars; } } public IList<char> WordBreakChars; public event KeyEventHandler EnterPressed; public event EventHandler AllSelected; private UndoBuffer undoBuffer = new UndoBuffer(); private bool mouseIsDown = false; private bool selecting; public bool Selecting { get { return selecting; } set { if (selecting != value) { selecting = value; Invalidate(); } } } private int selectionIndexToStartBefore; public int SelectionIndexToStartBefore { get { return selectionIndexToStartBefore; } set { selectionIndexToStartBefore = value; } } private int _charIndexToInsertBefore; public int CharIndexToInsertBefore { get { if (!String.IsNullOrEmpty(this.Text)) { _charIndexToInsertBefore = Math.Min(this.Text.Length, _charIndexToInsertBefore); } else { _charIndexToInsertBefore = 0; } return _charIndexToInsertBefore; } set { _charIndexToInsertBefore = value; } } private int charIndexToAcceptAsMerging; private double desiredBarX; private TextWidget internalTextWidget; private bool isMultiLine = true; public bool MergeTypingDuringUndo { get; set; } public event EventHandler InsertBarPositionChanged; /// <summary> /// This event fires when the user has finished editing the control. /// Fired on leave event after editing, or on enter key for non-multi line controls. /// </summary> public event EventHandler EditComplete; private Vector2 insertBarPosition; public new bool DoubleBuffer { get { return internalTextWidget.DoubleBuffer; } set { internalTextWidget.DoubleBuffer = value; } } public Vector2 InsertBarPosition { get { return insertBarPosition; } set { if (insertBarPosition != value) { insertBarPosition = value; OnInsertBarPositionChanged(null); } } } public TypeFacePrinter Printer { get { return internalTextWidget.Printer; } } /// <summary> /// This is called when the user has modified the text control. It will /// be triggered when the control looses focus or enter is pressed on non-multi-line control. /// </summary> public virtual void OnEditComplete(EventArgs e) { EditComplete?.Invoke(this, e); textWhenGotFocus = Text; } private void OnInsertBarPositionChanged(EventArgs e) { InsertBarPositionChanged?.Invoke(this, e); } public string Selection { get { if (Selecting) { if (CharIndexToInsertBefore < SelectionIndexToStartBefore) { return Text.Substring(CharIndexToInsertBefore, (SelectionIndexToStartBefore - CharIndexToInsertBefore)); } else { return Text.Substring(SelectionIndexToStartBefore, (CharIndexToInsertBefore - SelectionIndexToStartBefore)); } } return ""; } } public override String Text { get { return internalTextWidget.Text; } set { if (internalTextWidget.Text != value) { CharIndexToInsertBefore = 0; internalTextWidget.Text = value; OnTextChanged(null); Invalidate(); } } } public InternalTextEditWidget(string text, double pointSize, bool multiLine, int tabIndex, TypeFace typeFace = null) { TabIndex = tabIndex; TabStop = true; WordBreakChars = DefaultWordBreakChars; MergeTypingDuringUndo = true; internalTextWidget = new TextWidget(text, pointSize: pointSize, ellipsisIfClipped: false, textColor: textColor, typeFace: typeFace); internalTextWidget.Selectable = false; internalTextWidget.AutoExpandBoundsToText = true; AddChild(internalTextWidget); UpdateLocalBounds(); Multiline = multiLine; FixBarPosition(DesiredXPositionOnLine.Set); TextWidgetUndoCommand newUndoData = new TextWidgetUndoCommand(this); undoBuffer.Add(newUndoData); Cursor = Cursors.IBeam; internalTextWidget.TextChanged += new EventHandler(internalTextWidget_TextChanged); internalTextWidget.BoundsChanged += new EventHandler(internalTextWidget_BoundsChanged); } private void UpdateLocalBounds() { //double padding = 5; double width = Math.Max(internalTextWidget.Width + 2, 3); double height = Math.Max(internalTextWidget.Height, internalTextWidget.Printer.TypeFaceStyle.EmSizeInPixels); //LocalBounds = new RectangleDouble(this.BorderWidth - padding, this.BorderWidth - padding, width + this.BorderWidth + padding, height + this.BorderWidth + padding); LocalBounds = new RectangleDouble(-1, 0, width, height); // TODO: text widget should have some padding rather than the 1 on the x below. LBB 2013/02/03 internalTextWidget.OriginRelativeParent = new Vector2(1, -internalTextWidget.LocalBounds.Bottom); } private void internalTextWidget_BoundsChanged(object sender, EventArgs e) { UpdateLocalBounds(); } private void internalTextWidget_TextChanged(object sender, EventArgs e) { OnTextChanged(e); } public bool Multiline { get { return isMultiLine; } set { isMultiLine = value; } } private Stopwatch timeSinceTurnOn = new Stopwatch(); private double barOnTime = .6; private double barOffTime = .6; private bool BarIsShowing { get { return timeSinceTurnOn.ElapsedMilliseconds < barOnTime * 1000; } } public void OnIdle() { if (this.Focused && timeSinceTurnOn.ElapsedMilliseconds >= barOnTime * 950 && !HasBeenClosed) { if (timeSinceTurnOn.ElapsedMilliseconds >= (barOnTime + barOffTime) * 950) { RestartBarFlash(); } else { UiThread.RunOnIdle(OnIdle, barOffTime); Invalidate(); } } else { timeSinceTurnOn.Stop(); } } private void RestartBarFlash() { timeSinceTurnOn.Restart(); UiThread.RunOnIdle(OnIdle, barOnTime); Invalidate(); } public bool SelectAllOnFocus { get; set; } private bool selectAllOnMouseUpIfNoSelection = false; private string textWhenGotFocus; public override void OnFocusChanged(EventArgs e) { if (Focused) { RestartBarFlash(); textWhenGotFocus = Text; timeSinceTurnOn.Restart(); if (SelectAllOnFocus) { selectAllOnMouseUpIfNoSelection = true; } } else { Selecting = false; Invalidate(); if (TextHasChanged()) { OnEditComplete(e); } } base.OnFocusChanged(e); } public void MarkAsStartingState() { textWhenGotFocus = Text; } public bool TextHasChanged() { return textWhenGotFocus != Text; } public Color cursorColor = Color.DarkGray; public Color highlightColor = Color.Gray; public Color borderColor = Color.White; public Color textColor = Color.Black; public int borderWidth = 0; public int borderRadius = 0; public int BorderWidth { get { return this.borderWidth; } set { this.borderWidth = value; UpdateLocalBounds(); } } public Color TextColor { get { return textColor; } set { this.textColor = value; internalTextWidget.TextColor = this.textColor; } } public bool ReadOnly { get; set; } public override void OnDraw(Graphics2D graphics2D) { double fontHeight = internalTextWidget.Printer.TypeFaceStyle.EmSizeInPixels; if (Selecting && SelectionIndexToStartBefore != CharIndexToInsertBefore) { Vector2 selectPosition = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(SelectionIndexToStartBefore); // for each selected line draw a rect for the chars of that line if (selectPosition.Y == InsertBarPosition.Y) { RectangleDouble bar = new RectangleDouble(Math.Ceiling(selectPosition.X), Math.Ceiling(internalTextWidget.Height + selectPosition.Y), Math.Ceiling(InsertBarPosition.X + 1), Math.Ceiling(internalTextWidget.Height + InsertBarPosition.Y - fontHeight)); RoundedRect selectCursorRect = new RoundedRect(bar, 0); graphics2D.Render(selectCursorRect, this.highlightColor); } else { int firstCharToHighlight = Math.Min(CharIndexToInsertBefore, SelectionIndexToStartBefore); int lastCharToHighlight = Math.Max(CharIndexToInsertBefore, SelectionIndexToStartBefore); int lineStart = firstCharToHighlight; Vector2 lineStartPos = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(lineStart); int lineEnd = lineStart + 1; Vector2 lineEndPos = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(lineEnd); if (lineEndPos.Y != lineStartPos.Y) { // we are starting on a '\n', adjust so we will show the cr at the end of the line lineEndPos = lineStartPos; } bool firstCharOfLine = false; for (int i = lineEnd; i < lastCharToHighlight + 1; i++) { Vector2 nextPos = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(i); if (firstCharOfLine) { if (lineEndPos.Y != lineStartPos.Y) { // we are starting on a '\n', adjust so we will show the cr at the end of the line lineEndPos = lineStartPos; } firstCharOfLine = false; } if (nextPos.Y != lineStartPos.Y) { if (lineEndPos.X == lineStartPos.X) { lineEndPos.X += Printer.TypeFaceStyle.GetAdvanceForCharacter(' '); } RectangleDouble bar = new RectangleDouble(Math.Ceiling(lineStartPos.X), Math.Ceiling(internalTextWidget.Height + lineStartPos.Y), Math.Ceiling(lineEndPos.X + 1), Math.Ceiling(internalTextWidget.Height + lineEndPos.Y - fontHeight)); RoundedRect selectCursorRect = new RoundedRect(bar, 0); graphics2D.Render(selectCursorRect, this.highlightColor); lineStartPos = nextPos; firstCharOfLine = true; } else { lineEndPos = nextPos; } } if (lineEndPos.X != lineStartPos.X) { RectangleDouble bar = new RectangleDouble(Math.Ceiling(lineStartPos.X), Math.Ceiling(internalTextWidget.Height + lineStartPos.Y), Math.Ceiling(lineEndPos.X + 1), Math.Ceiling(internalTextWidget.Height + lineEndPos.Y - fontHeight)); RoundedRect selectCursorRect = new RoundedRect(bar, 0); graphics2D.Render(selectCursorRect, this.highlightColor); } } } if (this.Focused && BarIsShowing) { double xFraction = graphics2D.GetTransform().tx; xFraction = xFraction - (int)xFraction; RectangleDouble bar2 = new RectangleDouble(Math.Ceiling(InsertBarPosition.X) - xFraction, Math.Ceiling(internalTextWidget.Height + InsertBarPosition.Y - fontHeight), Math.Ceiling(InsertBarPosition.X + 1) - xFraction, Math.Ceiling(internalTextWidget.Height + InsertBarPosition.Y)); RoundedRect cursorRect = new RoundedRect(bar2, 0); graphics2D.Render(cursorRect, this.cursorColor); } RectangleDouble boundsPlusPoint5 = LocalBounds; boundsPlusPoint5.Inflate(-.5); RoundedRect borderRect = new RoundedRect(boundsPlusPoint5, 0); Stroke borderLine = new Stroke(borderRect); base.OnDraw(graphics2D); } public override void OnMouseDown(MouseEventArgs mouseEvent) { CharIndexToInsertBefore = internalTextWidget.Printer.GetCharacterIndexToStartBefore(new Vector2(mouseEvent.X, mouseEvent.Y)); if (mouseEvent.Clicks < 2) { if (CharIndexToInsertBefore == -1) { // we could not find any characters when looking for mouse click position CharIndexToInsertBefore = 0; } SelectionIndexToStartBefore = CharIndexToInsertBefore; Selecting = false; mouseIsDown = true; } else if (IsDoubleClick(mouseEvent)) { while (CharIndexToInsertBefore >= Text.Length || (CharIndexToInsertBefore > -1 && !WordBreakChars.Contains(Text[CharIndexToInsertBefore]))) { CharIndexToInsertBefore--; } CharIndexToInsertBefore++; SelectionIndexToStartBefore = CharIndexToInsertBefore + 1; while (SelectionIndexToStartBefore < Text.Length && !WordBreakChars.Contains(Text[SelectionIndexToStartBefore])) { SelectionIndexToStartBefore++; } Selecting = true; } RestartBarFlash(); FixBarPosition(DesiredXPositionOnLine.Set); base.OnMouseDown(mouseEvent); } public override void OnMouseMove(MouseEventArgs mouseEvent) { if (mouseIsDown) { StartSelectionIfRequired(null); CharIndexToInsertBefore = internalTextWidget.Printer.GetCharacterIndexToStartBefore(new Vector2(mouseEvent.X, mouseEvent.Y)); if (CharIndexToInsertBefore < 0) { CharIndexToInsertBefore = 0; } if (CharIndexToInsertBefore != SelectionIndexToStartBefore) { Selecting = true; } Invalidate(); FixBarPosition(DesiredXPositionOnLine.Set); } base.OnMouseMove(mouseEvent); } public override void OnMouseUp(MouseEventArgs mouseEvent) { mouseIsDown = false; if (SelectAllOnFocus && selectAllOnMouseUpIfNoSelection && Selecting == false) { SelectAll(); } selectAllOnMouseUpIfNoSelection = false; base.OnMouseUp(mouseEvent); } public override string ToString() { return internalTextWidget.Text; } protected enum DesiredXPositionOnLine { Maintain, Set }; protected void FixBarPosition(DesiredXPositionOnLine desiredXPositionOnLine) { InsertBarPosition = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(CharIndexToInsertBefore); if (desiredXPositionOnLine == DesiredXPositionOnLine.Set) { desiredBarX = InsertBarPosition.X; } Invalidate(); } private void DeleteIndex(int startIndexInclusive) { DeleteIndexRange(startIndexInclusive, startIndexInclusive); } private void DeleteIndexRange(int startIndexInclusive, int endIndexInclusive) { // first make sure we are deleting something that exists startIndexInclusive = Math.Max(0, Math.Min(startIndexInclusive, internalTextWidget.Text.Length)); endIndexInclusive = Math.Max(startIndexInclusive, Math.Min(endIndexInclusive, internalTextWidget.Text.Length)); int LengthToDelete = (endIndexInclusive + 1) - startIndexInclusive; if (LengthToDelete > 0 && internalTextWidget.Text.Length - startIndexInclusive >= LengthToDelete) { StringBuilder stringBuilder = new StringBuilder(internalTextWidget.Text); stringBuilder.Remove(startIndexInclusive, LengthToDelete); internalTextWidget.Text = stringBuilder.ToString(); } } private void DeleteSelection(bool createUndoMarker = true) { if (ReadOnly) { return; } if (Selecting) { if (CharIndexToInsertBefore < SelectionIndexToStartBefore) { DeleteIndexRange(CharIndexToInsertBefore, SelectionIndexToStartBefore - 1); } else { DeleteIndexRange(SelectionIndexToStartBefore, CharIndexToInsertBefore - 1); CharIndexToInsertBefore = SelectionIndexToStartBefore; } if (createUndoMarker) { TextWidgetUndoCommand newUndoDeleteData = new TextWidgetUndoCommand(this); undoBuffer.Add(newUndoDeleteData); } Selecting = false; } } public void SetSelection(int firstIndexSelected, int lastIndexSelected) { firstIndexSelected = Math.Max(0, Math.Min(firstIndexSelected, Text.Length - 1)); lastIndexSelected = Math.Max(0, Math.Min(lastIndexSelected, Text.Length)); SelectionIndexToStartBefore = firstIndexSelected; CharIndexToInsertBefore = lastIndexSelected + 1; Selecting = true; FixBarPosition(DesiredXPositionOnLine.Set); } private void StartSelectionIfRequired(KeyEventArgs keyEvent) { if (!Selecting && ShiftKeyIsDown(keyEvent)) { Selecting = true; SelectionIndexToStartBefore = CharIndexToInsertBefore; } } private bool ShiftKeyIsDown(KeyEventArgs keyEvent) { return Keyboard.IsKeyDown(Keys.Shift) || (keyEvent != null && keyEvent.Shift); } public override void OnKeyDown(KeyEventArgs keyEvent) { // this must be called first to ensure we get the correct Handled state base.OnKeyDown(keyEvent); if (!keyEvent.Handled) { RestartBarFlash(); bool SetDesiredBarPosition = true; bool turnOffSelection = false; if (!ShiftKeyIsDown(keyEvent)) { if (keyEvent.Control) { // don't let control keys get into the stream keyEvent.Handled = true; } else if (Selecting) { turnOffSelection = true; } } switch (keyEvent.KeyCode) { case Keys.Escape: if (Selecting) { turnOffSelection = true; keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; } break; case Keys.Left: StartSelectionIfRequired(keyEvent); if (keyEvent.Control) { GotoBeginingOfPreviousToken(); } else if (CharIndexToInsertBefore > 0) { if (turnOffSelection) { CharIndexToInsertBefore = Math.Min(CharIndexToInsertBefore, SelectionIndexToStartBefore); } else { CharIndexToInsertBefore--; } } keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; break; case Keys.Right: StartSelectionIfRequired(keyEvent); if (keyEvent.Control) { GotoBeginingOfNextToken(); } else if (CharIndexToInsertBefore < internalTextWidget.Text.Length) { if (turnOffSelection) { CharIndexToInsertBefore = Math.Max(CharIndexToInsertBefore, SelectionIndexToStartBefore); } else { CharIndexToInsertBefore++; } } keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; break; case Keys.Up: StartSelectionIfRequired(keyEvent); if (turnOffSelection) { CharIndexToInsertBefore = Math.Min(CharIndexToInsertBefore, SelectionIndexToStartBefore); } GotoLineAbove(); SetDesiredBarPosition = false; keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; break; case Keys.Down: StartSelectionIfRequired(keyEvent); if (turnOffSelection) { CharIndexToInsertBefore = Math.Max(CharIndexToInsertBefore, SelectionIndexToStartBefore); } GotoLineBelow(); SetDesiredBarPosition = false; keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; break; case Keys.Space: keyEvent.Handled = true; break; case Keys.End: StartSelectionIfRequired(keyEvent); if (keyEvent.Control) { CharIndexToInsertBefore = internalTextWidget.Text.Length; } else { GotoEndOfCurrentLine(); } keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; break; case Keys.Home: StartSelectionIfRequired(keyEvent); if (keyEvent.Control) { CharIndexToInsertBefore = 0; } else { GotoStartOfCurrentLine(); } keyEvent.SuppressKeyPress = true; keyEvent.Handled = true; break; case Keys.Back: if (!Selecting && CharIndexToInsertBefore > 0) { SelectionIndexToStartBefore = CharIndexToInsertBefore - 1; Selecting = true; } DeleteSelection(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; break; case Keys.Delete: if (ShiftKeyIsDown(keyEvent)) { CopySelection(); DeleteSelection(); keyEvent.SuppressKeyPress = true; } else { if (!Selecting && CharIndexToInsertBefore < internalTextWidget.Text.Length) { SelectionIndexToStartBefore = CharIndexToInsertBefore + 1; Selecting = true; } DeleteSelection(); } turnOffSelection = true; keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; break; case Keys.Enter: if (!Multiline) { // TODO: do the right thing. keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; if (EnterPressed != null) { EnterPressed(this, keyEvent); } if (TextHasChanged()) { OnEditComplete(keyEvent); } } break; case Keys.Insert: if (ShiftKeyIsDown(keyEvent)) { turnOffSelection = true; PasteFromClipboard(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } if (keyEvent.Control) { turnOffSelection = false; CopySelection(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; case Keys.A: if (keyEvent.Control) { SelectAll(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; case Keys.X: if (keyEvent.Control) { CopySelection(); DeleteSelection(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; case Keys.C: if (keyEvent.Control) { turnOffSelection = false; CopySelection(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; case Keys.V: if (keyEvent.Control) { PasteFromClipboard(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; case Keys.Z: if (keyEvent.Control) { Undo(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; case Keys.Y: if (keyEvent.Control) { undoBuffer.Redo(); keyEvent.Handled = true; keyEvent.SuppressKeyPress = true; } break; } if (SetDesiredBarPosition) { FixBarPosition(DesiredXPositionOnLine.Set); } else { FixBarPosition(DesiredXPositionOnLine.Maintain); } // if we are not going to type a character, and therefore replace the selection, turn off the selection now if needed. if (keyEvent.SuppressKeyPress && turnOffSelection) { Selecting = false; } Invalidate(); } } public void Undo() { undoBuffer.Undo(); FixBarPosition(DesiredXPositionOnLine.Set); } private void CopySelection() { if (Selecting) { if (CharIndexToInsertBefore < SelectionIndexToStartBefore) { #if SILVERLIGHT throw new NotImplementedException(); #else Clipboard.Instance.SetText(internalTextWidget.Text.Substring(CharIndexToInsertBefore, SelectionIndexToStartBefore - CharIndexToInsertBefore)); #endif } else { #if SILVERLIGHT throw new NotImplementedException(); #else Clipboard.Instance.SetText(internalTextWidget.Text.Substring(SelectionIndexToStartBefore, CharIndexToInsertBefore - SelectionIndexToStartBefore)); #endif } } else if (Multiline) { // copy the line? } } private void PasteFromClipboard() { if (ReadOnly) { return; } if (Clipboard.Instance.ContainsText) { if (Selecting) { DeleteSelection(false); } StringBuilder stringBuilder = new StringBuilder(internalTextWidget.Text); String stringOnClipboard = Clipboard.Instance.GetText(); if(!Multiline) { stringOnClipboard = Regex.Replace(stringOnClipboard, @"\r\n?|\n", " "); } stringBuilder.Insert(CharIndexToInsertBefore, stringOnClipboard); CharIndexToInsertBefore += stringOnClipboard.Length; internalTextWidget.Text = stringBuilder.ToString(); TextWidgetUndoCommand newUndoCommand = new TextWidgetUndoCommand(this); undoBuffer.Add(newUndoCommand); } } public override void OnKeyPress(KeyPressEventArgs keyPressEvent) { // this must be called first to ensure we get the correct Handled state base.OnKeyPress(keyPressEvent); if (!keyPressEvent.Handled) { if (keyPressEvent.KeyChar < 32 && keyPressEvent.KeyChar != 13 && keyPressEvent.KeyChar != 9) { return; } if(ReadOnly) { return; } if (Selecting) { DeleteSelection(); Selecting = false; } StringBuilder tempString = new StringBuilder(internalTextWidget.Text); if (keyPressEvent.KeyChar == '\r') { tempString.Insert(CharIndexToInsertBefore, "\n"); } else { tempString.Insert(CharIndexToInsertBefore, keyPressEvent.KeyChar.ToString()); } keyPressEvent.Handled = true; CharIndexToInsertBefore++; internalTextWidget.Text = tempString.ToString(); FixBarPosition(DesiredXPositionOnLine.Set); TextWidgetUndoCommand newUndoData = new TextWidgetUndoCommand(this); if (MergeTypingDuringUndo && charIndexToAcceptAsMerging == CharIndexToInsertBefore - 1 && keyPressEvent.KeyChar != '\n' && keyPressEvent.KeyChar != '\r') { undoBuffer.Add(newUndoData); } else { undoBuffer.Add(newUndoData); } charIndexToAcceptAsMerging = CharIndexToInsertBefore; } } private int GetIndexOffset(int CharacterStartIndexInclusive, int MaxCharacterEndIndexInclusive, double DesiredPixelOffset) { int OffsetIndex = 0; int EndOffsetIndex = MaxCharacterEndIndexInclusive - CharacterStartIndexInclusive; Vector2 offset = new Vector2(); Vector2 lastOffset = new Vector2(); while (true) { internalTextWidget.Printer.GetOffset(CharacterStartIndexInclusive, CharacterStartIndexInclusive + OffsetIndex, out offset); OffsetIndex++; if (offset.X >= DesiredPixelOffset || OffsetIndex >= EndOffsetIndex) { if (Math.Abs(offset.Y) < .01 && Math.Abs(lastOffset.X - DesiredPixelOffset) < Math.Abs(offset.X - DesiredPixelOffset)) { OffsetIndex--; } break; } lastOffset = offset; } int MaxLength = Math.Min(MaxCharacterEndIndexInclusive - CharacterStartIndexInclusive, OffsetIndex); return CharacterStartIndexInclusive + MaxLength; } // the '\n' is always considered to be the end of the line. // if startIndexInclusive == endIndexInclusive, the line is empty (other than the return) private void GetStartAndEndIndexForLineContainingChar(int charToFindLineContaining, out int startIndexOfLineInclusive, out int endIndexOfLineInclusive) { startIndexOfLineInclusive = 0; endIndexOfLineInclusive = internalTextWidget.Text.Length; if (endIndexOfLineInclusive == 0) { return; } charToFindLineContaining = Math.Max(Math.Min(charToFindLineContaining, internalTextWidget.Text.Length), 0); // first lets find the end of the line. Check if we are on a '\n' if (charToFindLineContaining == internalTextWidget.Text.Length || internalTextWidget.Text[charToFindLineContaining] == '\n') { // we are on the end of the line endIndexOfLineInclusive = charToFindLineContaining; } else { int endReturn = internalTextWidget.Text.IndexOf('\n', charToFindLineContaining + 1); if (endReturn != -1) { endIndexOfLineInclusive = endReturn; } } // check if the line is empty (the character to our left is the '\n' on the previous line bool isIndex0AndNL = endIndexOfLineInclusive == 0 && internalTextWidget.Text[endIndexOfLineInclusive] == '\n'; if (isIndex0AndNL || internalTextWidget.Text[endIndexOfLineInclusive - 1] == '\n') { // the line is empty the start = the end. startIndexOfLineInclusive = endIndexOfLineInclusive; } else { int returnAtStartOfCurrentLine = internalTextWidget.Text.LastIndexOf('\n', endIndexOfLineInclusive - 1); if (returnAtStartOfCurrentLine != -1) { startIndexOfLineInclusive = returnAtStartOfCurrentLine + 1; } } } private void GotoLineAbove() { int startIndexInclusive; int endIndexInclusive; GetStartAndEndIndexForLineContainingChar(CharIndexToInsertBefore, out startIndexInclusive, out endIndexInclusive); int prevStartIndexInclusive; int prevEndIndexInclusive; GetStartAndEndIndexForLineContainingChar(startIndexInclusive - 1, out prevStartIndexInclusive, out prevEndIndexInclusive); // we found the extents of the line above now put the cursor in the right place. CharIndexToInsertBefore = GetIndexOffset(prevStartIndexInclusive, prevEndIndexInclusive, desiredBarX); } private void GotoLineBelow() { int startIndexInclusive; int endIndexInclusive; GetStartAndEndIndexForLineContainingChar(CharIndexToInsertBefore, out startIndexInclusive, out endIndexInclusive); int nextStartIndexInclusive; int nextEndIndexInclusive; GetStartAndEndIndexForLineContainingChar(endIndexInclusive + 1, out nextStartIndexInclusive, out nextEndIndexInclusive); // we found the extents of the line above now put the cursor in the right place. CharIndexToInsertBefore = GetIndexOffset(nextStartIndexInclusive, nextEndIndexInclusive, desiredBarX); } private void GotoBeginingOfNextToken() { if (CharIndexToInsertBefore == internalTextWidget.Text.Length) { return; } bool SkippedWiteSpace = false; if (internalTextWidget.Text[CharIndexToInsertBefore] == '\n') { CharIndexToInsertBefore++; SkippedWiteSpace = true; } else { Regex firstWhiteSpaceRegex = new Regex("\\s"); Match firstWhiteSpace = firstWhiteSpaceRegex.Match(internalTextWidget.Text, CharIndexToInsertBefore); if (firstWhiteSpace.Success) { SkippedWiteSpace = true; CharIndexToInsertBefore = firstWhiteSpace.Index; } } if (SkippedWiteSpace) { Regex firstNonWhiteSpaceRegex = new Regex("[^\\t ]"); Match firstNonWhiteSpace = firstNonWhiteSpaceRegex.Match(internalTextWidget.Text, CharIndexToInsertBefore); if (firstNonWhiteSpace.Success) { CharIndexToInsertBefore = firstNonWhiteSpace.Index; } } else { GotoEndOfCurrentLine(); } } private void GotoBeginingOfPreviousToken() { if (CharIndexToInsertBefore == 0) { return; } Regex firstNonWhiteSpaceRegex = new Regex("[^\\t ]", RegexOptions.RightToLeft); Match firstNonWhiteSpace = firstNonWhiteSpaceRegex.Match(internalTextWidget.Text, CharIndexToInsertBefore); if (firstNonWhiteSpace.Success) { if (internalTextWidget.Text[firstNonWhiteSpace.Index] == '\n') { if (firstNonWhiteSpace.Index < CharIndexToInsertBefore - 1) { CharIndexToInsertBefore = firstNonWhiteSpace.Index; return; } else { firstNonWhiteSpaceRegex = new Regex("[^\\t\\n ]", RegexOptions.RightToLeft); firstNonWhiteSpace = firstNonWhiteSpaceRegex.Match(internalTextWidget.Text, CharIndexToInsertBefore); if (firstNonWhiteSpace.Success) { CharIndexToInsertBefore = firstNonWhiteSpace.Index; } } } else { CharIndexToInsertBefore = firstNonWhiteSpace.Index; } Regex firstWhiteSpaceRegex = new Regex("\\s", RegexOptions.RightToLeft); Match firstWhiteSpace = firstWhiteSpaceRegex.Match(internalTextWidget.Text, CharIndexToInsertBefore); if (firstWhiteSpace.Success) { CharIndexToInsertBefore = firstWhiteSpace.Index + 1; } else { GotoStartOfCurrentLine(); } } } public void SelectAll() { CharIndexToInsertBefore = internalTextWidget.Text.Length; SelectionIndexToStartBefore = 0; Selecting = true; FixBarPosition(DesiredXPositionOnLine.Set); if (AllSelected != null) { AllSelected(this, null); } } internal void GotoEndOfCurrentLine() { int indexOfReturn = internalTextWidget.Text.IndexOf('\n', CharIndexToInsertBefore); if (indexOfReturn == -1) { CharIndexToInsertBefore = internalTextWidget.Text.Length; } else { CharIndexToInsertBefore = indexOfReturn; } FixBarPosition(DesiredXPositionOnLine.Set); } internal void GotoStartOfCurrentLine() { if (CharIndexToInsertBefore > 0) { int indexOfReturn = internalTextWidget.Text.LastIndexOf('\n', CharIndexToInsertBefore - 1); if (indexOfReturn == -1) { CharIndexToInsertBefore = 0; } else { Regex firstNonWhiteSpaceRegex = new Regex("[^\\t ]"); Match firstNonWhiteSpace = firstNonWhiteSpaceRegex.Match(internalTextWidget.Text, indexOfReturn + 1); if (firstNonWhiteSpace.Success) { if (firstNonWhiteSpace.Index < CharIndexToInsertBefore || internalTextWidget.Text[CharIndexToInsertBefore - 1] == '\n') { CharIndexToInsertBefore = firstNonWhiteSpace.Index; return; } } CharIndexToInsertBefore = indexOfReturn + 1; } } } public void ClearUndoHistory() { undoBuffer.ClearHistory(); TextWidgetUndoCommand newUndoData = new TextWidgetUndoCommand(this); undoBuffer.Add(newUndoData); } } }
26.883488
168
0.689934
[ "Apache-2.0" ]
ucswift/PrinterQuotationEngine
References/agg-sharp/Gui/TextWidgets/InternalTextEditWidget.cs
34,843
C#
namespace Schema.NET { using System; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// A &lt;a class="localLink" href="http://schema.org/CampingPitch"&gt;CampingPitch&lt;/a&gt; is an individual place for overnight stay in the outdoors, typically being part of a larger camping site, or &lt;a class="localLink" href="http://schema.org/Campground"&gt;Campground&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt; /// In British English a campsite, or campground, is an area, usually divided into a number of pitches, where people can camp overnight using tents or camper vans or caravans; this British English use of the word is synonymous with the American English expression campground. In American English the term campsite generally means an area where an individual, family, group, or military unit can pitch a tent or park a camper; a campground may contain many campsites. /// (Source: Wikipedia see &lt;a href="https://en.wikipedia.org/wiki/Campsite"&gt;https://en.wikipedia.org/wiki/Campsite&lt;/a&gt;).&lt;br/&gt;&lt;br/&gt; /// See also the dedicated &lt;a href="/docs/hotels.html"&gt;document on the use of schema.org for marking up hotels and other forms of accommodations&lt;/a&gt;. /// </summary> public partial interface ICampingPitch : IAccommodation { } /// <summary> /// A &lt;a class="localLink" href="http://schema.org/CampingPitch"&gt;CampingPitch&lt;/a&gt; is an individual place for overnight stay in the outdoors, typically being part of a larger camping site, or &lt;a class="localLink" href="http://schema.org/Campground"&gt;Campground&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt; /// In British English a campsite, or campground, is an area, usually divided into a number of pitches, where people can camp overnight using tents or camper vans or caravans; this British English use of the word is synonymous with the American English expression campground. In American English the term campsite generally means an area where an individual, family, group, or military unit can pitch a tent or park a camper; a campground may contain many campsites. /// (Source: Wikipedia see &lt;a href="https://en.wikipedia.org/wiki/Campsite"&gt;https://en.wikipedia.org/wiki/Campsite&lt;/a&gt;).&lt;br/&gt;&lt;br/&gt; /// See also the dedicated &lt;a href="/docs/hotels.html"&gt;document on the use of schema.org for marking up hotels and other forms of accommodations&lt;/a&gt;. /// </summary> [DataContract] public partial class CampingPitch : Accommodation, ICampingPitch { /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "CampingPitch"; } }
85.424242
470
0.709471
[ "MIT" ]
candela-software/Schema.NET
Source/Schema.NET/core/CampingPitch.cs
2,821
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; namespace Amazon.PowerShell.Cmdlets.IAM { /// <summary> /// Lists the IAM groups that the specified IAM user belongs to. /// /// /// <para> /// You can paginate the results using the <code>MaxItems</code> and <code>Marker</code> /// parameters. /// </para><br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "IAMGroupForUser")] [OutputType("Amazon.IdentityManagement.Model.Group")] [AWSCmdlet("Calls the AWS Identity and Access Management ListGroupsForUser API operation.", Operation = new[] {"ListGroupsForUser"}, SelectReturnType = typeof(Amazon.IdentityManagement.Model.ListGroupsForUserResponse))] [AWSCmdletOutput("Amazon.IdentityManagement.Model.Group or Amazon.IdentityManagement.Model.ListGroupsForUserResponse", "This cmdlet returns a collection of Amazon.IdentityManagement.Model.Group objects.", "The service call response (type Amazon.IdentityManagement.Model.ListGroupsForUserResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetIAMGroupForUserCmdlet : AmazonIdentityManagementServiceClientCmdlet, IExecutor { #region Parameter UserName /// <summary> /// <para> /// <para>The name of the user to list groups for.</para><para>This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex /// pattern</a>) a string of characters consisting of upper and lowercase alphanumeric /// characters with no spaces. You can also include any of the following characters: _+=,.@-</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String UserName { get; set; } #endregion #region Parameter Marker /// <summary> /// <para> /// <para>Use this parameter only when paginating results and only after you receive a response /// indicating that the results are truncated. Set it to the value of the <code>Marker</code> /// element in the response that you received to indicate where the next call should start.</para> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-Marker $null' for the first call and '-Marker $AWSHistory.LastServiceResponse.Marker' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("NextToken")] public System.String Marker { get; set; } #endregion #region Parameter MaxItem /// <summary> /// <para> /// <para>Use this only when paginating results to indicate the maximum number of items you /// want in the response. If additional items exist beyond the maximum you specify, the /// <code>IsTruncated</code> response element is <code>true</code>.</para><para>If you do not include this parameter, the number of items defaults to 100. Note that /// IAM might return fewer results, even when there are more results available. In that /// case, the <code>IsTruncated</code> response element returns <code>true</code>, and /// <code>Marker</code> contains a value to include in the subsequent call that tells /// the service where to continue from.</para> /// </para> /// <para> /// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet. /// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call. /// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxItems")] public int? MaxItem { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Groups'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.IdentityManagement.Model.ListGroupsForUserResponse). /// Specifying the name of a property of type Amazon.IdentityManagement.Model.ListGroupsForUserResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "Groups"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the UserName parameter. /// The -PassThru parameter is deprecated, use -Select '^UserName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^UserName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of Marker /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.IdentityManagement.Model.ListGroupsForUserResponse, GetIAMGroupForUserCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.UserName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.Marker = this.Marker; context.MaxItem = this.MaxItem; #if !MODULAR if (ParameterWasBound(nameof(this.MaxItem)) && this.MaxItem.HasValue) { WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxItem parameter to limit the total number of items returned by the cmdlet." + " This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" + " retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxItem" + " to the service to specify how many items should be returned by each service call."); } #endif context.UserName = this.UserName; #if MODULAR if (this.UserName == null && ParameterWasBound(nameof(this.UserName))) { WriteWarning("You are passing $null as a value for parameter UserName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members #if MODULAR public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.IdentityManagement.Model.ListGroupsForUserRequest(); if (cmdletContext.MaxItem != null) { request.MaxItems = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxItem.Value); } if (cmdletContext.UserName != null) { request.UserName = cmdletContext.UserName; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.Marker; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.Marker)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.Marker = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.Marker; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #else public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; // create request and set iteration invariants var request = new Amazon.IdentityManagement.Model.ListGroupsForUserRequest(); if (cmdletContext.UserName != null) { request.UserName = cmdletContext.UserName; } // Initialize loop variants and commence piping System.String _nextToken = null; int? _emitLimit = null; int _retrievedSoFar = 0; if (AutoIterationHelpers.HasValue(cmdletContext.Marker)) { _nextToken = cmdletContext.Marker; } if (AutoIterationHelpers.HasValue(cmdletContext.MaxItem)) { // The service has a maximum page size of 1000. If the user has // asked for more items than page max, and there is no page size // configured, we rely on the service ignoring the set maximum // and giving us 1000 items back. If a page size is set, that will // be used to configure the pagination. // We'll make further calls to satisfy the user's request. _emitLimit = cmdletContext.MaxItem; } var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.Marker)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.Marker = _nextToken; if (_emitLimit.HasValue) { int correctPageSize = AutoIterationHelpers.Min(1000, _emitLimit.Value); request.MaxItems = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize); } CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; int _receivedThisCall = response.Groups.Count; _nextToken = response.Marker; _retrievedSoFar += _receivedThisCall; if (_emitLimit.HasValue) { _emitLimit -= _receivedThisCall; } } catch (Exception e) { if (_retrievedSoFar == 0 || !_emitLimit.HasValue) { output = new CmdletOutput { ErrorResponse = e }; } else { break; } } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } #endif public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.IdentityManagement.Model.ListGroupsForUserResponse CallAWSServiceOperation(IAmazonIdentityManagementService client, Amazon.IdentityManagement.Model.ListGroupsForUserRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Identity and Access Management", "ListGroupsForUser"); try { #if DESKTOP return client.ListGroupsForUser(request); #elif CORECLR return client.ListGroupsForUserAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String Marker { get; set; } public int? MaxItem { get; set; } public System.String UserName { get; set; } public System.Func<Amazon.IdentityManagement.Model.ListGroupsForUserResponse, GetIAMGroupForUserCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Groups; } } }
48.022727
279
0.58942
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/IdentityManagement/Basic/Get-IAMGroupForUser-Cmdlet.cs
19,017
C#
// Copyright (c) Robin Boerdijk - All rights reserved - See LICENSE file for license terms using MDSDK.Dicom.PixelData.PixelDataDecoders; using MDSDK.Dicom.Serialization; using System; using System.Collections.Generic; namespace MDSDK.Dicom.PixelData { /// <summary>Base class for DICOM pixel data decoders</summary> public abstract class DicomPixelDataDecoder { /// <summary>Returns the positions of the individual pixel data frames in the DICOM input stream</summary> public abstract long[] GetPixelDataFramePositions(DicomStreamReader dicomStreamReader, DicomImagePixelDescription desc, int numberOfFrames); /// <summary>Decodes the pixel data frame that starts at the current position of the DICOM input stream</summary> public abstract void DecodePixelDataFrame(DicomStreamReader dicomStreamReader, DicomImagePixelDescription desc, Memory<byte> output); private static readonly Dictionary<DicomUID, DicomPixelDataDecoder> TransferSyntaxPixelDataDecoders = new() { { DicomUID.TransferSyntax.ImplicitVRLittleEndian, UncompressedPixelDataDecoder.Instance }, { DicomUID.TransferSyntax.ExplicitVRLittleEndian, UncompressedPixelDataDecoder.Instance }, { DicomUID.TransferSyntax.JPEGLossless, JPEGLosslessNonDifferentialHuffman1PixelDataDecoder.Instance }, { DicomUID.TransferSyntax.JPEG2000, JPEG2000PixelDataDecoder.Instance }, { DicomUID.TransferSyntax.JPEG2000Lossless, JPEG2000PixelDataDecoder.Instance }, { DicomUID.TransferSyntax.RLELossless, RunLengthPixelDataDecoder.Instance }, }; /// <summary>Tries to return a pixel data decoder for the given transfer syntax</summary> public static bool TryGet(DicomUID transferSyntaxUID, out DicomPixelDataDecoder pixelDataDecoder) { return TransferSyntaxPixelDataDecoders.TryGetValue(transferSyntaxUID, out pixelDataDecoder); } } }
53.621622
141
0.753528
[ "MIT" ]
mdsdk/MDSDK.Dicom.PixelData
MDSDK.Dicom.PixelData/DicomPixelDataDecoder.cs
1,986
C#
using System; using System.Threading.Tasks; using Volo.Abp.Account; using Volo.Abp.DependencyInjection; namespace RatTracker.HttpApi.Client.ConsoleTestApp { public class ClientDemoService : ITransientDependency { private readonly IProfileAppService _profileAppService; public ClientDemoService(IProfileAppService profileAppService) { _profileAppService = profileAppService; } public async Task RunAsync() { var output = await _profileAppService.GetAsync(); Console.WriteLine($"UserName : {output.UserName}"); Console.WriteLine($"Email : {output.Email}"); Console.WriteLine($"Name : {output.Name}"); Console.WriteLine($"Surname : {output.Surname}"); } } }
31
70
0.648883
[ "MIT" ]
kfrancis/ratTracker
test/RatTracker.HttpApi.Client.ConsoleTestApp/ClientDemoService.cs
808
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LogicAppsExceptionManagementApi { public static class Utility { public static double ConvertToTimestamp(DateTime value) { //create Timespan by subtracting the value provided from //the Unix Epoch var span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()); //return the total seconds (which is a UNIX timestamp) return span.TotalSeconds; } } }
22.5
84
0.641026
[ "MIT" ]
HEDIDIN/LogicAppsExceptionManagementApi
LogicAppsExceptionManagementApi/Utility.cs
587
C#
using BookShare.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookShare.Domain.Entities { public class Editora { public int EditoraId { get; set; } public string Nome { get; set; } public virtual IEnumerable<Livro> Livros { get; set; } } }
22.058824
62
0.693333
[ "MIT" ]
marqueslu/bookshare
BookShare.Domain/Entities/Editora.cs
377
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace System.Extensions.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Extensions.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Appearance. /// </summary> internal static string Category_Appearance { get { return ResourceManager.GetString("Category_Appearance", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Asynchronous. /// </summary> internal static string Category_Asynchronous { get { return ResourceManager.GetString("Category_Asynchronous", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Behavior. /// </summary> internal static string Category_Behavior { get { return ResourceManager.GetString("Category_Behavior", resourceCulture); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap CommandLink_RestingArrow { get { object obj = ResourceManager.GetObject("CommandLink_RestingArrow", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap CommandLink_SelectedArrow { get { object obj = ResourceManager.GetObject("CommandLink_SelectedArrow", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized string similar to Executes an operation on a separate thread while showing a progress dialog.. /// </summary> internal static string ProgressDialog_Description { get { return ResourceManager.GetString("ProgressDialog_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Event handler to be run on a different thread when the operation begins.. /// </summary> internal static string ProgressDialog_DoWork { get { return ResourceManager.GetString("ProgressDialog_DoWork", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The header text that indicates what general action is occurring.. /// </summary> internal static string ProgressDialog_HeaderText { get { return ResourceManager.GetString("ProgressDialog_HeaderText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The small text to show that can provide progress status.. /// </summary> internal static string ProgressDialog_MessageText { get { return ResourceManager.GetString("ProgressDialog_MessageText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Raised when the worker thread indicates that some progress has been made.. /// </summary> internal static string ProgressDialog_ProgressChanged { get { return ResourceManager.GetString("ProgressDialog_ProgressChanged", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Raised when the worker has completed (either through success, failure, or cancellation).. /// </summary> internal static string ProgressDialog_RunWorkerCompleted { get { return ResourceManager.GetString("ProgressDialog_RunWorkerCompleted", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The title text that will show in the window title bar.. /// </summary> internal static string ProgressDialog_TitleText { get { return ResourceManager.GetString("ProgressDialog_TitleText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Whether the worker will report progress.. /// </summary> internal static string ProgressDialog_WorkerReportsProgress { get { return ResourceManager.GetString("ProgressDialog_WorkerReportsProgress", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Whether the worker supports cancellation.. /// </summary> internal static string ProgressDialog_WorkerSupportsCancellation { get { return ResourceManager.GetString("ProgressDialog_WorkerSupportsCancellation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to SafeDataReader cannot wrap an object of the same Type.. /// </summary> internal static string SafeDataReader_NoRewrap { get { return ResourceManager.GetString("SafeDataReader_NoRewrap", resourceCulture); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap Shield { get { object obj = ResourceManager.GetObject("Shield", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized string similar to Specifies the text to display when the control is empty.. /// </summary> internal static string TextBox_CueBannerDescription { get { return ResourceManager.GetString("TextBox_CueBannerDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Specifies whether to show the cue banner when the control has focus.. /// </summary> internal static string TextBox_ShowCueWhenFocusedDescription { get { return ResourceManager.GetString("TextBox_ShowCueWhenFocusedDescription", resourceCulture); } } } }
40.995633
183
0.588517
[ "MIT" ]
Plankankul/Framework-w-WebApp
Original/Runtime/Properties/Resources.Designer.cs
9,390
C#
 using Unity.Tests.TestDoubles; namespace Unity.Tests.TestObjects { internal class OptionalLogger { private string logFile; public OptionalLogger([Dependency] string logFile) { this.logFile = logFile; } public string LogFile { get { return logFile; } } } }
16.809524
58
0.563739
[ "Apache-2.0" ]
danielp37/container
tests/Unity.Tests/TestObjects/OptionalLogger.cs
355
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 Internal.IL.Stubs; using Internal.IL; using Debug = System.Diagnostics.Debug; using ILLocalVariable = Internal.IL.Stubs.ILLocalVariable; namespace Internal.TypeSystem.Interop { public enum MarshalDirection { Forward, // safe-to-unsafe / managed-to-native Reverse, // unsafe-to-safe / native-to-managed } // Each type of marshaller knows how to generate the marshalling code for the argument it marshals. // Marshallers contain method related marshalling information (which is common to all the Marshallers) // and also argument specific marshalling information. abstract partial class Marshaller { #region Instance state information public TypeSystemContext Context; #if !READYTORUN public InteropStateManager InteropStateManager; #endif public MarshallerKind MarshallerKind; public MarshallerType MarshallerType; public MarshalAsDescriptor MarshalAsDescriptor; public MarshallerKind ElementMarshallerKind; public int Index; public TypeDesc ManagedType; public TypeDesc ManagedParameterType; public PInvokeFlags PInvokeFlags; protected Marshaller[] Marshallers; private TypeDesc _nativeType; private TypeDesc _nativeParamType; /// <summary> /// Native Type of the value being marshalled /// For by-ref scenarios (ref T), Native Type is T /// </summary> public TypeDesc NativeType { get { if (_nativeType == null) { _nativeType = MarshalHelpers.GetNativeTypeFromMarshallerKind( ManagedType, MarshallerKind, ElementMarshallerKind, #if !READYTORUN InteropStateManager, #endif MarshalAsDescriptor); Debug.Assert(_nativeType != null); } return _nativeType; } } /// <summary> /// NativeType appears in function parameters /// For by-ref scenarios (ref T), NativeParameterType is T* /// </summary> public TypeDesc NativeParameterType { get { if (_nativeParamType == null) { TypeDesc nativeParamType = NativeType; if (IsNativeByRef) nativeParamType = nativeParamType.MakePointerType(); _nativeParamType = nativeParamType; } return _nativeParamType; } } /// <summary> /// Indicates whether cleanup is necessay if this marshaller is used /// as an element of an array marshaller /// </summary> internal virtual bool CleanupRequired { get { return false; } } internal bool IsHRSwappedRetVal => Index == 0 && !Return; public bool In; public bool Out; public bool Return; public bool IsManagedByRef; // Whether managed argument is passed by ref public bool IsNativeByRef; // Whether native argument is passed by byref // There are special cases (such as LpStruct, and class) that // isNativeByRef != IsManagedByRef public MarshalDirection MarshalDirection; protected PInvokeILCodeStreams _ilCodeStreams; protected Home _managedHome; protected Home _nativeHome; #endregion enum HomeType { Arg, Local, ByRefArg, ByRefLocal } /// <summary> /// Abstraction for handling by-ref and non-by-ref locals/arguments /// </summary> internal class Home { public Home(ILLocalVariable var, TypeDesc type, bool isByRef) { _homeType = isByRef ? HomeType.ByRefLocal : HomeType.Local; _type = type; _var = var; } public Home(int argIndex, TypeDesc type, bool isByRef) { _homeType = isByRef ? HomeType.ByRefArg : HomeType.Arg; _type = type; _argIndex = argIndex; } public void LoadValue(ILCodeStream stream) { switch (_homeType) { case HomeType.Arg: stream.EmitLdArg(_argIndex); break; case HomeType.ByRefArg: stream.EmitLdArg(_argIndex); stream.EmitLdInd(_type); break; case HomeType.Local: stream.EmitLdLoc(_var); break; case HomeType.ByRefLocal: stream.EmitLdLoc(_var); stream.EmitLdInd(_type); break; default: Debug.Assert(false); break; } } public void LoadAddr(ILCodeStream stream) { switch (_homeType) { case HomeType.Arg: stream.EmitLdArga(_argIndex); break; case HomeType.ByRefArg: stream.EmitLdArg(_argIndex); break; case HomeType.Local: stream.EmitLdLoca(_var); break; case HomeType.ByRefLocal: stream.EmitLdLoc(_var); break; default: Debug.Assert(false); break; } } public void StoreValue(ILCodeStream stream) { switch (_homeType) { case HomeType.Arg: Debug.Fail("Unexpectting setting value on non-byref arg"); break; case HomeType.Local: stream.EmitStLoc(_var); break; default: // Storing by-ref arg/local is not supported because StInd require // address to be pushed first. Instead we need to introduce a non-byref // local and propagate value as needed for by-ref arguments Debug.Assert(false); break; } } HomeType _homeType; TypeDesc _type; ILLocalVariable _var; int _argIndex; } #region Creation of marshallers /// <summary> /// Protected ctor /// Only Marshaller.CreateMarshaller can create a marshaller /// </summary> protected Marshaller() { } /// <summary> /// Create a marshaller /// </summary> /// <param name="parameterType">type of the parameter to marshal</param> /// <returns>The created Marshaller</returns> public static Marshaller CreateMarshaller(TypeDesc parameterType, int? parameterIndex, EmbeddedSignatureData[] customModifierData, MarshallerType marshallerType, MarshalAsDescriptor marshalAs, MarshalDirection direction, Marshaller[] marshallers, #if !READYTORUN InteropStateManager interopStateManager, #endif int index, PInvokeFlags flags, bool isIn, bool isOut, bool isReturn) { bool isAnsi = flags.CharSet switch { CharSet.Ansi => true, CharSet.Unicode => false, CharSet.Auto => !parameterType.Context.Target.IsWindows, _ => true }; MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(parameterType, parameterIndex, customModifierData, marshalAs, isReturn, isAnsi, marshallerType, out MarshallerKind elementMarshallerKind); TypeSystemContext context = parameterType.Context; // Create the marshaller based on MarshallerKind Marshaller marshaller = CreateMarshaller(marshallerKind); marshaller.Context = context; #if !READYTORUN marshaller.InteropStateManager = interopStateManager; #endif marshaller.MarshallerKind = marshallerKind; marshaller.MarshallerType = marshallerType; marshaller.ElementMarshallerKind = elementMarshallerKind; marshaller.ManagedParameterType = parameterType; marshaller.ManagedType = parameterType.IsByRef ? parameterType.GetParameterType() : parameterType; marshaller.Return = isReturn; marshaller.IsManagedByRef = parameterType.IsByRef; marshaller.IsNativeByRef = marshaller.IsManagedByRef /* || isRetVal || LpStruct /etc */; marshaller.In = isIn; marshaller.MarshalDirection = direction; marshaller.MarshalAsDescriptor = marshalAs; marshaller.Marshallers = marshallers; marshaller.Index = index; marshaller.PInvokeFlags = flags; // // Desktop ignores [Out] on marshaling scenarios where they don't make sense // if (isOut) { // Passing as [Out] by ref is always valid. if (!marshaller.IsManagedByRef) { // Ignore [Out] for ValueType, string and pointers if (parameterType.IsValueType || parameterType.IsString || parameterType.IsPointer || parameterType.IsFunctionPointer) { isOut = false; } } } marshaller.Out = isOut; if (!marshaller.In && !marshaller.Out) { // // Rules for in/out // 1. ByRef args: [in]/[out] implied by default // 2. StringBuilder: [in, out] by default // 3. non-ByRef args: [In] is implied if no [In]/[Out] is specified // if (marshaller.IsManagedByRef) { marshaller.In = true; marshaller.Out = true; } else if (InteropTypes.IsStringBuilder(context, parameterType)) { marshaller.In = true; marshaller.Out = true; } else { marshaller.In = true; } } // For unicodestring/ansistring, ignore out when it's in if (!marshaller.IsManagedByRef && marshaller.In) { if (marshaller.MarshallerKind == MarshallerKind.AnsiString || marshaller.MarshallerKind == MarshallerKind.UnicodeString) marshaller.Out = false; } return marshaller; } /// <summary> /// Create a marshaller /// </summary> /// <param name="parameterType">type of the parameter to marshal</param> /// <returns>The created Marshaller</returns> public static Marshaller CreateDisabledMarshaller(TypeDesc parameterType, int? parameterIndex, MarshallerType marshallerType, MarshalDirection direction, Marshaller[] marshallers, int index, PInvokeFlags flags, bool isReturn) { MarshallerKind marshallerKind = MarshalHelpers.GetDisabledMarshallerKind(parameterType); TypeSystemContext context = parameterType.Context; // Create the marshaller based on MarshallerKind Marshaller marshaller = CreateMarshaller(marshallerKind); marshaller.Context = context; marshaller.MarshallerKind = marshallerKind; marshaller.MarshallerType = marshallerType; marshaller.ElementMarshallerKind = MarshallerKind.Unknown; marshaller.ManagedParameterType = parameterType; marshaller.ManagedType = parameterType; marshaller.Return = isReturn; marshaller.IsManagedByRef = false; marshaller.IsNativeByRef = false; marshaller.MarshalDirection = direction; marshaller.MarshalAsDescriptor = null; marshaller.Marshallers = marshallers; marshaller.Index = index; marshaller.PInvokeFlags = flags; marshaller.In = true; marshaller.Out = false; return marshaller; } #endregion #region Marshalling Requirement Checking private static bool IsMarshallingRequired(MarshallerKind kind) { switch (kind) { case MarshallerKind.Enum: case MarshallerKind.BlittableValue: case MarshallerKind.BlittableStruct: case MarshallerKind.UnicodeChar: case MarshallerKind.VoidReturn: return false; } return true; } public bool IsMarshallingRequired() { return Out || IsManagedByRef || IsMarshallingRequired(MarshallerKind); } #endregion public virtual void EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams) { _ilCodeStreams = pInvokeILCodeStreams; switch (MarshallerType) { case MarshallerType.Argument: EmitArgumentMarshallingIL(); return; case MarshallerType.Element: EmitElementMarshallingIL(); return; case MarshallerType.Field: EmitFieldMarshallingIL(); return; } } private void EmitArgumentMarshallingIL() { switch (MarshalDirection) { case MarshalDirection.Forward: EmitForwardArgumentMarshallingIL(); return; case MarshalDirection.Reverse: EmitReverseArgumentMarshallingIL(); return; } } private void EmitElementMarshallingIL() { switch (MarshalDirection) { case MarshalDirection.Forward: EmitForwardElementMarshallingIL(); return; case MarshalDirection.Reverse: EmitReverseElementMarshallingIL(); return; } } private void EmitFieldMarshallingIL() { switch (MarshalDirection) { case MarshalDirection.Forward: EmitForwardFieldMarshallingIL(); return; case MarshalDirection.Reverse: EmitReverseFieldMarshallingIL(); return; } } protected virtual void EmitForwardArgumentMarshallingIL() { if (Return) { EmitMarshalReturnValueManagedToNative(); } else { EmitMarshalArgumentManagedToNative(); } } protected virtual void EmitReverseArgumentMarshallingIL() { if (Return) { EmitMarshalReturnValueNativeToManaged(); } else { EmitMarshalArgumentNativeToManaged(); } } protected virtual void EmitForwardElementMarshallingIL() { if (In) EmitMarshalElementManagedToNative(); else EmitMarshalElementNativeToManaged(); } protected virtual void EmitReverseElementMarshallingIL() { if (In) EmitMarshalElementNativeToManaged(); else EmitMarshalElementManagedToNative(); } protected virtual void EmitForwardFieldMarshallingIL() { if (In) EmitMarshalFieldManagedToNative(); else EmitMarshalFieldNativeToManaged(); } protected virtual void EmitReverseFieldMarshallingIL() { if (In) EmitMarshalFieldNativeToManaged(); else EmitMarshalFieldManagedToNative(); } protected virtual void EmitMarshalReturnValueManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; SetupArgumentsForReturnValueMarshalling(); StoreNativeValue(_ilCodeStreams.ReturnValueMarshallingCodeStream); AllocAndTransformNativeToManaged(_ilCodeStreams.ReturnValueMarshallingCodeStream); } public virtual void LoadReturnValue(ILCodeStream codeStream) { Debug.Assert(Return || IsHRSwappedRetVal); switch (MarshalDirection) { case MarshalDirection.Forward: LoadManagedValue(codeStream); return; case MarshalDirection.Reverse: LoadNativeValue(codeStream); return; } } protected virtual void SetupArguments() { ILEmitter emitter = _ilCodeStreams.Emitter; if (MarshalDirection == MarshalDirection.Forward) { // Due to StInd order (address, value), we can't do the following: // LoadValue // StoreManagedValue (LdArg + StInd) // The way to work around this is to put it in a local if (IsManagedByRef) _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, false); else _managedHome = new Home(Index - 1, ManagedType, false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } else { _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); if (IsNativeByRef) _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); else _nativeHome = new Home(Index - 1, NativeType, isByRef: false); } } protected virtual void SetupArgumentsForElementMarshalling() { ILEmitter emitter = _ilCodeStreams.Emitter; _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } protected virtual void SetupArgumentsForFieldMarshalling() { ILEmitter emitter = _ilCodeStreams.Emitter; // // these are temporary locals for propagating value // _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } protected virtual void SetupArgumentsForReturnValueMarshalling() { ILEmitter emitter = _ilCodeStreams.Emitter; _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } protected void LoadManagedValue(ILCodeStream stream) { _managedHome.LoadValue(stream); } protected void LoadManagedAddr(ILCodeStream stream) { _managedHome.LoadAddr(stream); } /// <summary> /// Loads the argument to be passed to managed functions /// In by-ref scenarios (ref T), it is &T /// </summary> protected void LoadManagedArg(ILCodeStream stream) { if (IsManagedByRef) _managedHome.LoadAddr(stream); else _managedHome.LoadValue(stream); } protected void StoreManagedValue(ILCodeStream stream) { _managedHome.StoreValue(stream); } protected void LoadNativeValue(ILCodeStream stream) { _nativeHome.LoadValue(stream); } /// <summary> /// Loads the argument to be passed to native functions /// In by-ref scenarios (ref T), it is T* /// </summary> protected void LoadNativeArg(ILCodeStream stream) { if (IsNativeByRef) { _nativeHome.LoadAddr(stream); stream.Emit(ILOpcode.conv_i); } else { _nativeHome.LoadValue(stream); } } protected void LoadNativeAddr(ILCodeStream stream) { _nativeHome.LoadAddr(stream); } protected void StoreNativeValue(ILCodeStream stream) { _nativeHome.StoreValue(stream); } /// <summary> /// Propagate by-ref arg to corresponding local /// We can't load value + ldarg + ldind in the expected order, so /// we had to use a non-by-ref local and manually propagate the value /// </summary> protected void PropagateFromByRefArg(ILCodeStream stream, Home home) { stream.EmitLdArg(Index - 1); switch (MarshalDirection) { case MarshalDirection.Forward: stream.EmitLdInd(ManagedType); break; case MarshalDirection.Reverse: stream.EmitLdInd(NativeType); break; } home.StoreValue(stream); } /// <summary> /// Propagate local to corresponding by-ref arg /// We can't load value + ldarg + ldind in the expected order, so /// we had to use a non-by-ref local and manually propagate the value /// </summary> protected void PropagateToByRefArg(ILCodeStream stream, Home home) { // If by-ref arg has index == 0 then that argument is used for HR swapping and we just return that value. if (IsHRSwappedRetVal) { // Returning result would be handled by LoadReturnValue return; } stream.EmitLdArg(Index - 1); home.LoadValue(stream); switch (MarshalDirection) { case MarshalDirection.Forward: stream.EmitStInd(ManagedType); break; case MarshalDirection.Reverse: stream.EmitStInd(NativeType); break; } } protected virtual void EmitMarshalArgumentManagedToNative() { SetupArguments(); if (IsManagedByRef && In) { // Propagate byref arg to local PropagateFromByRefArg(_ilCodeStreams.MarshallingCodeStream, _managedHome); } // // marshal // if (IsManagedByRef && !In) { ReInitNativeTransform(_ilCodeStreams.MarshallingCodeStream); } else { AllocAndTransformManagedToNative(_ilCodeStreams.MarshallingCodeStream); } LoadNativeArg(_ilCodeStreams.CallsiteSetupCodeStream); // // unmarshal // if (Out) { if (In) { ClearManagedTransform(_ilCodeStreams.UnmarshallingCodestream); } if (IsManagedByRef && !In) { AllocNativeToManaged(_ilCodeStreams.UnmarshallingCodestream); } TransformNativeToManaged(_ilCodeStreams.UnmarshallingCodestream); if (IsManagedByRef) { // Propagate back to byref arguments PropagateToByRefArg(_ilCodeStreams.UnmarshallingCodestream, _managedHome); } } EmitCleanupManaged(_ilCodeStreams.CleanupCodeStream); } /// <summary> /// Reads managed parameter from _vManaged and writes the marshalled parameter in _vNative /// </summary> protected virtual void AllocAndTransformManagedToNative(ILCodeStream codeStream) { AllocManagedToNative(codeStream); if (In) { TransformManagedToNative(codeStream); } } protected virtual void AllocAndTransformNativeToManaged(ILCodeStream codeStream) { AllocNativeToManaged(codeStream); TransformNativeToManaged(codeStream); } protected virtual void AllocManagedToNative(ILCodeStream codeStream) { } protected virtual void TransformManagedToNative(ILCodeStream codeStream) { LoadManagedValue(codeStream); StoreNativeValue(codeStream); } protected virtual void ClearManagedTransform(ILCodeStream codeStream) { } protected virtual void AllocNativeToManaged(ILCodeStream codeStream) { } protected virtual void TransformNativeToManaged(ILCodeStream codeStream) { LoadNativeValue(codeStream); StoreManagedValue(codeStream); } protected virtual void EmitCleanupManaged(ILCodeStream codeStream) { } protected virtual void EmitMarshalReturnValueNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; SetupArgumentsForReturnValueMarshalling(); StoreManagedValue(_ilCodeStreams.ReturnValueMarshallingCodeStream); AllocAndTransformManagedToNative(_ilCodeStreams.ReturnValueMarshallingCodeStream); } protected virtual void EmitMarshalArgumentNativeToManaged() { SetupArguments(); if (IsNativeByRef && In) { // Propagate byref arg to local PropagateFromByRefArg(_ilCodeStreams.MarshallingCodeStream, _nativeHome); } if (IsNativeByRef && !In) { ReInitManagedTransform(_ilCodeStreams.MarshallingCodeStream); } else { AllocAndTransformNativeToManaged(_ilCodeStreams.MarshallingCodeStream); } LoadManagedArg(_ilCodeStreams.CallsiteSetupCodeStream); if (Out) { if (IsNativeByRef) { AllocManagedToNative(_ilCodeStreams.UnmarshallingCodestream); } TransformManagedToNative(_ilCodeStreams.UnmarshallingCodestream); if (IsNativeByRef) { // Propagate back to byref arguments PropagateToByRefArg(_ilCodeStreams.UnmarshallingCodestream, _nativeHome); } } } protected virtual void EmitMarshalElementManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; Debug.Assert(codeStream != null); SetupArgumentsForElementMarshalling(); StoreManagedValue(codeStream); // marshal AllocAndTransformManagedToNative(codeStream); LoadNativeValue(codeStream); } protected virtual void EmitMarshalElementNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; Debug.Assert(codeStream != null); SetupArgumentsForElementMarshalling(); StoreNativeValue(codeStream); // unmarshal AllocAndTransformNativeToManaged(codeStream); LoadManagedValue(codeStream); } protected virtual void EmitMarshalFieldManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; SetupArgumentsForFieldMarshalling(); // // For field marshalling we expect the value of the field is already loaded // in the stack. // StoreManagedValue(marshallingCodeStream); // marshal AllocAndTransformManagedToNative(marshallingCodeStream); LoadNativeValue(marshallingCodeStream); } protected virtual void EmitMarshalFieldNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; SetupArgumentsForFieldMarshalling(); StoreNativeValue(codeStream); // unmarshal AllocAndTransformNativeToManaged(codeStream); LoadManagedValue(codeStream); } protected virtual void ReInitManagedTransform(ILCodeStream codeStream) { } protected virtual void ReInitNativeTransform(ILCodeStream codeStream) { } internal virtual void EmitElementCleanup(ILCodeStream codestream, ILEmitter emitter) { } } class NotSupportedMarshaller : Marshaller { public override void EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams) { throw new NotSupportedException(); } } class VoidReturnMarshaller : Marshaller { protected override void EmitMarshalReturnValueManagedToNative() { } protected override void EmitMarshalReturnValueNativeToManaged() { } public override void LoadReturnValue(ILCodeStream codeStream) { Debug.Assert(Return); } } class BlittableValueMarshaller : Marshaller { protected override void EmitMarshalArgumentManagedToNative() { if (IsHRSwappedRetVal) { base.EmitMarshalArgumentManagedToNative(); return; } if (IsNativeByRef && MarshalDirection == MarshalDirection.Forward) { ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; ILEmitter emitter = _ilCodeStreams.Emitter; ILLocalVariable native = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); ILLocalVariable vPinnedByRef = emitter.NewLocal(ManagedParameterType, true); marshallingCodeStream.EmitLdArg(Index - 1); marshallingCodeStream.EmitStLoc(vPinnedByRef); marshallingCodeStream.EmitLdLoc(vPinnedByRef); marshallingCodeStream.Emit(ILOpcode.conv_i); marshallingCodeStream.EmitStLoc(native); _ilCodeStreams.CallsiteSetupCodeStream.EmitLdLoc(native); } else { _ilCodeStreams.CallsiteSetupCodeStream.EmitLdArg(Index - 1); } } protected override void EmitMarshalArgumentNativeToManaged() { if (Out && !IsNativeByRef) { base.EmitMarshalArgumentNativeToManaged(); } else { _ilCodeStreams.CallsiteSetupCodeStream.EmitLdArg(Index - 1); } } } class BlittableStructPtrMarshaller : Marshaller { protected override void TransformManagedToNative(ILCodeStream codeStream) { if (Out) { // TODO: https://github.com/dotnet/corert/issues/4466 throw new NotSupportedException("Marshalling an LPStruct argument not yet implemented"); } else { LoadManagedAddr(codeStream); StoreNativeValue(codeStream); } } protected override void TransformNativeToManaged(ILCodeStream codeStream) { // TODO: https://github.com/dotnet/corert/issues/4466 throw new NotSupportedException("Marshalling an LPStruct argument not yet implemented"); } } class ArrayMarshaller : Marshaller { private Marshaller _elementMarshaller; protected TypeDesc ManagedElementType { get { Debug.Assert(ManagedType is ArrayType); var arrayType = (ArrayType)ManagedType; return arrayType.ElementType; } } protected TypeDesc NativeElementType { get { Debug.Assert(NativeType is PointerType); return ((PointerType)NativeType).ParameterType; } } protected override void SetupArgumentsForFieldMarshalling() { ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, ManagedType); } protected Marshaller GetElementMarshaller(MarshalDirection direction) { if (_elementMarshaller == null) { _elementMarshaller = CreateMarshaller(ElementMarshallerKind); _elementMarshaller.MarshallerKind = ElementMarshallerKind; _elementMarshaller.MarshallerType = MarshallerType.Element; #if !READYTORUN _elementMarshaller.InteropStateManager = InteropStateManager; #endif _elementMarshaller.Return = Return; _elementMarshaller.Context = Context; _elementMarshaller.ManagedType = ManagedElementType; _elementMarshaller.MarshalAsDescriptor = MarshalAsDescriptor; _elementMarshaller.PInvokeFlags = PInvokeFlags; } _elementMarshaller.In = (direction == MarshalDirection); _elementMarshaller.Out = !In; _elementMarshaller.MarshalDirection = MarshalDirection; return _elementMarshaller; } protected virtual void EmitElementCount(ILCodeStream codeStream, MarshalDirection direction) { if (direction == MarshalDirection.Forward) { // In forward direction we skip whatever is passed through SizeParamIndex, because the // size of the managed array is already known LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.ldlen); codeStream.Emit(ILOpcode.conv_i4); } else if (MarshalDirection == MarshalDirection.Forward && MarshallerType == MarshallerType.Argument && !Return && !IsManagedByRef) { EmitElementCount(codeStream, MarshalDirection.Forward); } else { uint? sizeParamIndex = MarshalAsDescriptor != null ? MarshalAsDescriptor.SizeParamIndex : null; uint? sizeConst = MarshalAsDescriptor != null ? MarshalAsDescriptor.SizeConst : null; if (sizeConst.HasValue) { codeStream.EmitLdc((int)sizeConst.Value); } if (sizeParamIndex.HasValue) { uint index = sizeParamIndex.Value; if (index < 0 || index >= Marshallers.Length - 1) { ThrowHelper.ThrowMarshalDirectiveException(); } //zero-th index is for return type index++; var indexType = Marshallers[index].ManagedType; switch (indexType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Int16: case TypeFlags.UInt16: case TypeFlags.Int32: case TypeFlags.UInt32: case TypeFlags.Int64: case TypeFlags.UInt64: case TypeFlags.IntPtr: case TypeFlags.UIntPtr: break; default: ThrowHelper.ThrowMarshalDirectiveException(); break; } // @TODO - We can use LoadManagedValue, but that requires byref arg propagation happen in a special setup stream // otherwise there is an ordering issue codeStream.EmitLdArg(Marshallers[index].Index - 1); if (Marshallers[index].IsManagedByRef) codeStream.EmitLdInd(indexType); if (sizeConst.HasValue) codeStream.Emit(ILOpcode.add); } if (!sizeConst.HasValue && !sizeParamIndex.HasValue) { // if neither sizeConst or sizeParamIndex are specified, default to 1 codeStream.EmitLdc(1); } } } protected override void AllocManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeLabel lNullArray = emitter.NewCodeLabel(); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_u); StoreNativeValue(codeStream); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); // allocate memory // nativeParameter = AllocCoTaskMem(checked(managedParameter.Length * sizeof(NativeElementType))); // loads the number of elements EmitElementCount(codeStream, MarshalDirection.Forward); TypeDesc nativeElementType = NativeElementType; codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.Emit(ILOpcode.mul_ovf); codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("AllocCoTaskMem", null))); StoreNativeValue(codeStream); codeStream.EmitLabel(lNullArray); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var elementType = ManagedElementType; var lRangeCheck = emitter.NewCodeLabel(); var lLoopHeader = emitter.NewCodeLabel(); var lNullArray = emitter.NewCodeLabel(); var vNativeTemp = emitter.NewLocal(NativeType); var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); var vSizeOf = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); var vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); // loads the number of elements EmitElementCount(codeStream, MarshalDirection.Forward); codeStream.EmitStLoc(vLength); TypeDesc nativeElementType = NativeElementType; codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.EmitStLoc(vSizeOf); LoadNativeValue(codeStream); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); codeStream.EmitLdLoc(vNativeTemp); LoadManagedValue(codeStream); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdElem(elementType); // generate marshalling IL for the element GetElementMarshaller(MarshalDirection.Forward) .EmitMarshallingIL(new PInvokeILCodeStreams(_ilCodeStreams.Emitter, codeStream)); codeStream.EmitStInd(nativeElementType); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdLoc(vSizeOf); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); codeStream.EmitLabel(lNullArray); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var elementType = ManagedElementType; var nativeElementType = NativeElementType; ILLocalVariable vSizeOf = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); ILCodeLabel lRangeCheck = emitter.NewCodeLabel(); ILCodeLabel lLoopHeader = emitter.NewCodeLabel(); var lNullArray = emitter.NewCodeLabel(); // Check for null array if (!IsManagedByRef) { LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); } EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.EmitStLoc(vLength); if (IsManagedByRef) { codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.newarr, emitter.NewToken(ManagedElementType)); StoreManagedValue(codeStream); } codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.EmitStLoc(vSizeOf); var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vNativeTemp = emitter.NewLocal(NativeType); LoadNativeValue(codeStream); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); LoadManagedValue(codeStream); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdInd(nativeElementType); // generate marshalling IL for the element GetElementMarshaller(MarshalDirection.Reverse) .EmitMarshallingIL(new PInvokeILCodeStreams(_ilCodeStreams.Emitter, codeStream)); codeStream.EmitStElem(elementType); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdLoc(vSizeOf); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); codeStream.EmitLabel(lNullArray); } protected override void AllocNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var elementType = ManagedElementType; EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.Emit(ILOpcode.newarr, emitter.NewToken(elementType)); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { Marshaller elementMarshaller = GetElementMarshaller(MarshalDirection.Forward); ILEmitter emitter = _ilCodeStreams.Emitter; var lNullArray = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); // generate cleanup code only if it is necessary if (elementMarshaller.CleanupRequired) { // // for (index=0; index< array.length; index++) // Cleanup(array[i]); // var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); ILCodeLabel lRangeCheck = emitter.NewCodeLabel(); ILCodeLabel lLoopHeader = emitter.NewCodeLabel(); ILLocalVariable vSizeOf = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); var nativeElementType = NativeElementType; // calculate sizeof(array[i]) codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.EmitStLoc(vSizeOf); // calculate array.length EmitElementCount(codeStream, MarshalDirection.Forward); codeStream.EmitStLoc(vLength); // load native value ILLocalVariable vNativeTemp = emitter.NewLocal(NativeType); LoadNativeValue(codeStream); codeStream.EmitStLoc(vNativeTemp); // index = 0 codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdInd(nativeElementType); // generate cleanup code for this element elementMarshaller.EmitElementCleanup(codeStream, emitter); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdLoc(vSizeOf); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); } LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); codeStream.EmitLabel(lNullArray); } } class BlittableArrayMarshaller : ArrayMarshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeLabel lNullArray = emitter.NewCodeLabel(); MethodDesc getArrayDataReferenceGenericMethod = InteropTypes.GetMemoryMarshal(Context).GetKnownMethod("GetArrayDataReference", null); MethodDesc getArrayDataReferenceMethod = getArrayDataReferenceGenericMethod.MakeInstantiatedMethod(ManagedElementType); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); if (IsManagedByRef) { base.AllocManagedToNative(codeStream); LoadNativeValue(codeStream); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(getArrayDataReferenceMethod)); EmitElementCount(codeStream, MarshalDirection.Forward); codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(ManagedElementType)); codeStream.Emit(ILOpcode.mul_ovf); codeStream.Emit(ILOpcode.cpblk); codeStream.EmitLabel(lNullArray); } else { ILLocalVariable vPinnedFirstElement = emitter.NewLocal(ManagedElementType.MakeByRefType(), true); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.ldlen); codeStream.Emit(ILOpcode.conv_i4); codeStream.Emit(ILOpcode.brfalse, lNullArray); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(getArrayDataReferenceMethod)); codeStream.EmitStLoc(vPinnedFirstElement); // Fall through. If array didn't have elements, vPinnedFirstElement is zeroinit. codeStream.EmitLabel(lNullArray); codeStream.EmitLdLoc(vPinnedFirstElement); codeStream.Emit(ILOpcode.conv_i); StoreNativeValue(codeStream); } } protected override void ReInitNativeTransform(ILCodeStream codeStream) { codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_u); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { if (IsManagedByRef || (MarshalDirection == MarshalDirection.Reverse && MarshallerType == MarshallerType.Argument)) base.TransformNativeToManaged(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { if (IsManagedByRef) base.EmitCleanupManaged(codeStream); } } class BooleanMarshaller : Marshaller { private int _trueValue; public BooleanMarshaller(int trueValue = 1) { _trueValue = trueValue; } protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeLabel pLoadFalseLabel = emitter.NewCodeLabel(); ILCodeLabel pDoneLabel = emitter.NewCodeLabel(); LoadManagedValue(codeStream); if (_trueValue == 1) { codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); } else { codeStream.Emit(ILOpcode.brfalse, pLoadFalseLabel); codeStream.EmitLdc(_trueValue); codeStream.Emit(ILOpcode.br, pDoneLabel); codeStream.EmitLabel(pLoadFalseLabel); codeStream.EmitLdc(0); codeStream.EmitLabel(pDoneLabel); } StoreNativeValue(codeStream); } protected override void AllocAndTransformNativeToManaged(ILCodeStream codeStream) { LoadNativeValue(codeStream); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); StoreManagedValue(codeStream); } } class UnicodeStringMarshaller : Marshaller { private bool ShouldBePinned { get { return MarshalDirection == MarshalDirection.Forward && MarshallerType != MarshallerType.Field && !IsManagedByRef && In && !Out; } } internal override bool CleanupRequired { get { return !ShouldBePinned; //cleanup is only required when it is not pinned } } internal override void EmitElementCleanup(ILCodeStream codeStream, ILEmitter emitter) { codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; if (ShouldBePinned) { // // Pin the char& and push a pointer to the first character on the stack. // TypeDesc charRefType = Context.GetWellKnownType(WellKnownType.Char).MakeByRefType(); ILLocalVariable vPinnedCharRef = emitter.NewLocal(charRefType, true); ILCodeLabel lNonNullString = emitter.NewCodeLabel(); ILCodeLabel lCommonExit = emitter.NewCodeLabel(); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brtrue, lNonNullString); // // Null input case // Don't pin anything - load a zero-value nuint (void*) onto the stack // codeStream.Emit(ILOpcode.ldc_i4_0); codeStream.Emit(ILOpcode.conv_u); codeStream.Emit(ILOpcode.br, lCommonExit); // // Non-null input case // Extract the char& from the string, pin it, then convert it to a nuint (void*) // codeStream.EmitLabel(lNonNullString); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetWellKnownType(WellKnownType.String). GetKnownMethod("GetPinnableReference", null))); codeStream.EmitStLoc(vPinnedCharRef); codeStream.EmitLdLoc(vPinnedCharRef); codeStream.Emit(ILOpcode.conv_u); // // Common exit // Top of stack contains a nuint (void*) pointing to start of char data, or nullptr // codeStream.EmitLabel(lCommonExit); StoreNativeValue(codeStream); } else { #if READYTORUN throw new NotSupportedException(); #else var helper = Context.GetHelperEntryPoint("InteropHelpers", "StringToUnicodeBuffer"); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreNativeValue(codeStream); #endif } } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var charPtrConstructor = Context.GetWellKnownType(WellKnownType.String).GetMethod(".ctor", new MethodSignature( MethodSignatureFlags.None, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Char).MakePointerType() } )); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(charPtrConstructor)); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { if (CleanupRequired) { var emitter = _ilCodeStreams.Emitter; var lNullCheck = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullCheck); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); codeStream.EmitLabel(lNullCheck); } } } class AnsiStringMarshaller : Marshaller { #if READYTORUN const int MAX_LOCAL_BUFFER_LENGTH = 260 + 1; // MAX_PATH + 1 private ILLocalVariable? _localBuffer = null; #endif internal override bool CleanupRequired { get { return true; } } internal override void EmitElementCleanup(ILCodeStream codeStream, ILEmitter emitter) { codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; // // ANSI marshalling. Allocate a byte array, copy characters // #if READYTORUN var stringToAnsi = Context.SystemModule.GetKnownType("System.StubHelpers", "CSTRMarshaler") .GetKnownMethod("ConvertToNative", null); bool bPassByValueInOnly = In && !Out && !IsManagedByRef; if (bPassByValueInOnly) { var bufSize = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); _localBuffer = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); // LocalBuffer = 0 codeStream.Emit(ILOpcode.ldnull); codeStream.EmitStLoc((ILLocalVariable)_localBuffer); var noOptimize = emitter.NewCodeLabel(); // if == NULL, goto NoOptimize LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, noOptimize); // String.Length + 2 LoadManagedValue(codeStream); var stringLen = Context.GetWellKnownType(WellKnownType.String) .GetKnownMethod("get_Length", null); codeStream.Emit(ILOpcode.call, emitter.NewToken(stringLen)); codeStream.EmitLdc(2); codeStream.Emit(ILOpcode.add); // (String.Length + 2) * GetMaxDBCSCharByteSize() codeStream.Emit(ILOpcode.ldsfld, emitter.NewToken(Context.SystemModule.GetKnownType( "System.Runtime.InteropServices","Marshal") .GetKnownField("SystemMaxDBCSCharSize"))); codeStream.Emit(ILOpcode.mul_ovf); // BufSize = (String.Length + 2) * GetMaxDBCSCharByteSize() codeStream.EmitStLoc(bufSize); // if (MAX_LOCAL_BUFFER_LENGTH < BufSize ) goto NoOptimize codeStream.EmitLdc(MAX_LOCAL_BUFFER_LENGTH + 1); codeStream.EmitLdLoc(bufSize); codeStream.Emit(ILOpcode.clt); codeStream.Emit(ILOpcode.brtrue, noOptimize); // LocalBuffer = localloc(BufSize); codeStream.EmitLdLoc(bufSize); codeStream.Emit(ILOpcode.localloc); codeStream.EmitStLoc((ILLocalVariable)_localBuffer); // NoOptimize: codeStream.EmitLabel(noOptimize); } int flags = (PInvokeFlags.BestFitMapping ? 0x1 : 0) | (PInvokeFlags.ThrowOnUnmappableChar ? 0x100 : 0); // CSTRMarshaler.ConvertToNative pManaged, dwAnsiMarshalFlags, pLocalBuffer codeStream.EmitLdc(flags); LoadManagedValue(codeStream); if (_localBuffer.HasValue) { codeStream.EmitLdLoc((ILLocalVariable)_localBuffer); } else { codeStream.Emit(ILOpcode.ldnull); } codeStream.Emit(ILOpcode.call, emitter.NewToken(stringToAnsi)); #else LoadManagedValue(codeStream); var stringToAnsi = Context.GetHelperEntryPoint("InteropHelpers", "StringToAnsiString"); codeStream.Emit(PInvokeFlags.BestFitMapping ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(PInvokeFlags.ThrowOnUnmappableChar ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(ILOpcode.call, emitter.NewToken(stringToAnsi)); #endif StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; #if READYTORUN var ansiToString = Context.SystemModule.GetKnownType("System.StubHelpers", "CSTRMarshaler") .GetKnownMethod("ConvertToManaged", null); #else var ansiToString = Context.GetHelperEntryPoint("InteropHelpers", "AnsiStringToString"); #endif LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(ansiToString)); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { var emitter = _ilCodeStreams.Emitter; #if READYTORUN var optimize = emitter.NewCodeLabel(); MethodDesc clearNative = Context.SystemModule.GetKnownType("System.StubHelpers", "CSTRMarshaler") .GetKnownMethod("ClearNative", null); if (_localBuffer.HasValue) { // if (m_dwLocalBuffer) goto Optimize codeStream.EmitLdLoc((ILLocalVariable)_localBuffer); codeStream.Emit(ILOpcode.brtrue, optimize); } LoadNativeValue(codeStream); // static void m_idClearNative(IntPtr ptr) codeStream.Emit(ILOpcode.call, emitter.NewToken(clearNative)); // Optimize: if (_localBuffer != default) { codeStream.EmitLabel(optimize); } #else var lNullCheck = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullCheck); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); codeStream.EmitLabel(lNullCheck); #endif } } class UTF8StringMarshaller : Marshaller { private const int LocalBufferLength = 0x100; private ILLocalVariable? _marshallerInstance = null; private TypeDesc Marshaller => Context.SystemModule.GetKnownType("System.Runtime.InteropServices.Marshalling", "Utf8StringMarshaller"); internal override bool CleanupRequired => true; internal override void EmitElementCleanup(ILCodeStream codeStream, ILEmitter emitter) { Debug.Assert(_marshallerInstance is null); codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; TypeDesc marshaller = Marshaller; if (_marshallerInstance == null) _marshallerInstance = emitter.NewLocal(marshaller); if (In && !Out && !IsManagedByRef) { var vBuffer = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); codeStream.EmitLdc(LocalBufferLength); codeStream.Emit(ILOpcode.localloc); codeStream.EmitStLoc(vBuffer); LoadManagedValue(codeStream); // Create ReadOnlySpan<byte> from the stack-allocated buffer codeStream.EmitLdLoc(vBuffer); codeStream.EmitLdc(LocalBufferLength); var spanOfByte = Context.SystemModule.GetKnownType("System", "Span`1").MakeInstantiatedType( new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Byte) }); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(spanOfByte.GetKnownMethod(".ctor", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Void).MakePointerType(), Context.GetWellKnownType(WellKnownType.Int32) })))); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(marshaller.GetKnownMethod(".ctor", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.String), spanOfByte })))); codeStream.EmitStLoc(_marshallerInstance.Value); } else { LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(marshaller.GetKnownMethod(".ctor", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.String) })))); codeStream.EmitStLoc(_marshallerInstance.Value); } codeStream.EmitLdLoca(_marshallerInstance.Value); codeStream.Emit(ILOpcode.call, emitter.NewToken(marshaller.GetKnownMethod("ToNativeValue", null))); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; TypeDesc marshaller = Marshaller; if (_marshallerInstance == null) _marshallerInstance = emitter.NewLocal(marshaller); codeStream.EmitLdLoca(_marshallerInstance.Value); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(marshaller.GetKnownMethod("FromNativeValue", null))); codeStream.EmitLdLoca(_marshallerInstance.Value); codeStream.Emit(ILOpcode.call, emitter.NewToken(marshaller.GetKnownMethod("ToManaged", null))); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; if (In && !Out && !IsManagedByRef) { Debug.Assert(_marshallerInstance != null); codeStream.EmitLdLoca(_marshallerInstance.Value); codeStream.Emit(ILOpcode.call, emitter.NewToken( Marshaller.GetKnownMethod("FreeNative", null))); } else { // The marshaller instance is not guaranteed to be initialized with the latest native value. // Free the native value directly. LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("FreeCoTaskMem", null))); } } } class SafeHandleMarshaller : Marshaller { private void AllocSafeHandle(ILCodeStream codeStream) { var ctor = ManagedType.GetParameterlessConstructor(); if (ctor == null) { ThrowHelper.ThrowMissingMethodException(ManagedType, ".ctor", new MethodSignature(MethodSignatureFlags.None, genericParameterCount: 0, ManagedType.Context.GetWellKnownType(WellKnownType.Void), TypeDesc.EmptyTypes)); } if (((MetadataType)ManagedType).IsAbstract) { ThrowHelper.ThrowMarshalDirectiveException(); } codeStream.Emit(ILOpcode.newobj, _ilCodeStreams.Emitter.NewToken(ctor)); } protected override void EmitMarshalReturnValueManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; ILCodeStream returnValueMarshallingCodeStream = _ilCodeStreams.ReturnValueMarshallingCodeStream; SetupArgumentsForReturnValueMarshalling(); AllocSafeHandle(marshallingCodeStream); StoreManagedValue(marshallingCodeStream); StoreNativeValue(returnValueMarshallingCodeStream); LoadManagedValue(returnValueMarshallingCodeStream); LoadNativeValue(returnValueMarshallingCodeStream); returnValueMarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( InteropTypes.GetSafeHandle(Context).GetKnownMethod("SetHandle", null))); } protected override void EmitMarshalArgumentManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; ILCodeStream callsiteCodeStream = _ilCodeStreams.CallsiteSetupCodeStream; ILCodeStream unmarshallingCodeStream = _ilCodeStreams.UnmarshallingCodestream; ILCodeStream cleanupCodeStream = _ilCodeStreams.CleanupCodeStream; SetupArguments(); if (IsManagedByRef && In) { PropagateFromByRefArg(marshallingCodeStream, _managedHome); } var safeHandleType = InteropTypes.GetSafeHandle(Context); if (In) { if (IsManagedByRef) PropagateFromByRefArg(marshallingCodeStream, _managedHome); var vAddRefed = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); LoadManagedValue(marshallingCodeStream); marshallingCodeStream.EmitLdLoca(vAddRefed); marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousAddRef", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Boolean).MakeByRefType() })))); LoadManagedValue(marshallingCodeStream); marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousGetHandle", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.IntPtr), TypeDesc.EmptyTypes)))); StoreNativeValue(marshallingCodeStream); ILCodeLabel lNotAddrefed = emitter.NewCodeLabel(); cleanupCodeStream.EmitLdLoc(vAddRefed); cleanupCodeStream.Emit(ILOpcode.brfalse, lNotAddrefed); LoadManagedValue(cleanupCodeStream); cleanupCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousRelease", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), TypeDesc.EmptyTypes)))); cleanupCodeStream.EmitLabel(lNotAddrefed); } if (Out && IsManagedByRef) { // 1) If this is an output parameter we need to preallocate a SafeHandle to wrap the new native handle value. We // must allocate this before the native call to avoid a failure point when we already have a native resource // allocated. We must allocate a new SafeHandle even if we have one on input since both input and output native // handles need to be tracked and released by a SafeHandle. // 2) Initialize a local IntPtr that will be passed to the native call. // 3) After the native call, the new handle value is written into the output SafeHandle and that SafeHandle // is propagated back to the caller. var vSafeHandle = emitter.NewLocal(ManagedType); AllocSafeHandle(marshallingCodeStream); marshallingCodeStream.EmitStLoc(vSafeHandle); var lSkipPropagation = emitter.NewCodeLabel(); if (In) { // Propagate the value only if it has changed ILLocalVariable vOriginalValue = emitter.NewLocal(NativeType); LoadNativeValue(marshallingCodeStream); marshallingCodeStream.EmitStLoc(vOriginalValue); cleanupCodeStream.EmitLdLoc(vOriginalValue); LoadNativeValue(cleanupCodeStream); cleanupCodeStream.Emit(ILOpcode.beq, lSkipPropagation); } cleanupCodeStream.EmitLdLoc(vSafeHandle); LoadNativeValue(cleanupCodeStream); cleanupCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("SetHandle", new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.IntPtr) })))); if (IsHRSwappedRetVal) { cleanupCodeStream.EmitLdLoc(vSafeHandle); StoreManagedValue(cleanupCodeStream); } else { cleanupCodeStream.EmitLdArg(Index - 1); cleanupCodeStream.EmitLdLoc(vSafeHandle); cleanupCodeStream.EmitStInd(ManagedType); } cleanupCodeStream.EmitLabel(lSkipPropagation); } LoadNativeArg(callsiteCodeStream); } protected override void EmitMarshalArgumentNativeToManaged() { throw new NotSupportedException(); } protected override void EmitMarshalElementNativeToManaged() { throw new NotSupportedException(); } protected override void EmitMarshalElementManagedToNative() { throw new NotSupportedException(); } protected override void EmitMarshalFieldManagedToNative() { throw new NotSupportedException(); } protected override void EmitMarshalFieldNativeToManaged() { throw new NotSupportedException(); } } class DelegateMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILCodeLabel lNullPointer = _ilCodeStreams.Emitter.NewCodeLabel(); ILCodeLabel lDone = _ilCodeStreams.Emitter.NewCodeLabel(); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.dup); codeStream.Emit(ILOpcode.brfalse, lNullPointer); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( #if READYTORUN InteropTypes.GetMarshal(Context).GetKnownMethod("GetFunctionPointerForDelegate", #else InteropTypes.GetPInvokeMarshal(Context).GetKnownMethod("GetFunctionPointerForDelegate", #endif new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.IntPtr), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType } )))); codeStream.Emit(ILOpcode.br, lDone); codeStream.EmitLabel(lNullPointer); codeStream.Emit(ILOpcode.pop); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_i); codeStream.EmitLabel(lDone); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILCodeLabel lNullPointer = _ilCodeStreams.Emitter.NewCodeLabel(); ILCodeLabel lDone = _ilCodeStreams.Emitter.NewCodeLabel(); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.dup); codeStream.Emit(ILOpcode.brfalse, lNullPointer); #if READYTORUN TypeDesc systemType = Context.SystemModule.GetKnownType("System", "Type"); codeStream.Emit(ILOpcode.ldtoken, _ilCodeStreams.Emitter.NewToken(ManagedType)); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken(systemType.GetKnownMethod("GetTypeFromHandle", null))); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropTypes.GetMarshal(Context).GetKnownMethod("GetDelegateForFunctionPointer", new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType, new TypeDesc[] { Context.GetWellKnownType(WellKnownType.IntPtr), systemType } )))); #else codeStream.Emit(ILOpcode.ldtoken, _ilCodeStreams.Emitter.NewToken(ManagedType)); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropTypes.GetPInvokeMarshal(Context).GetKnownMethod("GetDelegateForFunctionPointer", new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType, new TypeDesc[] { Context.GetWellKnownType(WellKnownType.IntPtr), Context.GetWellKnownType(WellKnownType.RuntimeTypeHandle) } )))); #endif codeStream.Emit(ILOpcode.br, lDone); codeStream.EmitLabel(lNullPointer); codeStream.Emit(ILOpcode.pop); codeStream.Emit(ILOpcode.ldnull); codeStream.EmitLabel(lDone); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { if (In && MarshalDirection == MarshalDirection.Forward && MarshallerType == MarshallerType.Argument) { LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken(InteropTypes.GetGC(Context).GetKnownMethod("KeepAlive", null))); } } } }
37.665564
161
0.581128
[ "MIT" ]
Danyy427/runtime
src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs
79,738
C#
using Eto.Forms; using sw = System.Windows; using swc = System.Windows.Controls; namespace Eto.Wpf.Forms.Printing { public class PrintDialogHandler : WidgetHandler<swc.PrintDialog, PrintDialog>, PrintDialog.IHandler { PrintSettings settings; public PrintDialogHandler() { Control = new swc.PrintDialog { UserPageRangeEnabled = true }; } public PrintDocument Document { get; set; } public DialogResult ShowDialog(Window parent) { if (parent?.HasFocus == false) parent.Focus(); Control.SetEtoSettings(settings); var result = Control.ShowDialog(); WpfFrameworkElementHelper.ShouldCaptureMouse = false; if (result == true) { settings.SetFromDialog(Control); Document?.Print(); return DialogResult.Ok; } return DialogResult.Cancel; } public PrintSettings PrintSettings { get { if (settings == null) settings = Control.GetEtoSettings(); return settings; } set { settings = value; Control.SetEtoSettings(settings); } } public bool AllowPageRange { get { return Control.UserPageRangeEnabled; } set { Control.UserPageRangeEnabled = value; } } // not supported in wpf public bool AllowSelection { get; set; } } }
18.984848
100
0.680766
[ "BSD-3-Clause" ]
OpenTabletDriver/Eto
src/Eto.Wpf/Forms/Printing/PrintDialogHandler.cs
1,253
C#
namespace StuffPacker.store.packlist.Get { public class GetPackListDataFailedAction { public string ErrorMessage { get; private set; } public GetPackListDataFailedAction(string errorMessage) { ErrorMessage = errorMessage; } } }
20.5
63
0.648084
[ "MIT" ]
StuffPacker/StuffPacker
src/StuffPacker/store/packlist/Get/GetPackListDataFailedAction.cs
289
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 mediastore-data-2017-09-01.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.MediaStoreData { /// <summary> /// Configuration for accessing Amazon MediaStoreData service /// </summary> public partial class AmazonMediaStoreDataConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.101.117"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonMediaStoreDataConfig() { this.AuthenticationServiceName = "mediastore"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "data.mediastore"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2017-09-01"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.6375
113
0.594087
[ "Apache-2.0" ]
Vfialkin/aws-sdk-net
sdk/src/Services/MediaStoreData/Generated/AmazonMediaStoreDataConfig.cs
2,131
C#
using CppSharp; using CppSharp.AST; using CppSharp.Passes; using System; using System.IO; namespace BindingsGenerator { class Vessel : ILibrary { public void Setup(Driver driver) { var options = driver.Options; var module = options.AddModule("Diligent"); module.Headers.Add("SDL.h"); options.OutputDir = "Vessel"; var parserOptions = driver.ParserOptions; var sdlPath = Path.Combine(Directory.GetCurrentDirectory(), "SDL", "SDL-2.0/include"); Console.WriteLine("Attempting to load Vessel from " + sdlPath); parserOptions.AddIncludeDirs(sdlPath); } public void SetupPasses(Driver driver) { /* driver.Context.TranslationUnitPasses.RemovePrefix("SDL_"); driver.Context.TranslationUnitPasses.RemovePrefix("SCANCODE_"); driver.Context.TranslationUnitPasses.RemovePrefix("SDLK_"); driver.Context.TranslationUnitPasses.RemovePrefix("KMOD_"); driver.Context.TranslationUnitPasses.RemovePrefix("LOG_CATEGORY_"); */ } public void Preprocess(Driver driver, ASTContext ctx) { /* ctx.IgnoreEnumWithMatchingItem("SDL_FALSE"); ctx.IgnoreEnumWithMatchingItem("DUMMY_ENUM_VALUE"); ctx.SetNameOfEnumWithMatchingItem("SDL_SCANCODE_UNKNOWN", "ScanCode"); ctx.SetNameOfEnumWithMatchingItem("SDLK_UNKNOWN", "Key"); ctx.SetNameOfEnumWithMatchingItem("KMOD_NONE", "KeyModifier"); ctx.SetNameOfEnumWithMatchingItem("SDL_LOG_CATEGORY_CUSTOM", "LogCategory"); ctx.GenerateEnumFromMacros("InitFlags", "SDL_INIT_(.*)").SetFlags(); ctx.GenerateEnumFromMacros("Endianness", "SDL_(.*)_ENDIAN"); ctx.GenerateEnumFromMacros("InputState", "SDL_RELEASED", "SDL_PRESSED"); ctx.GenerateEnumFromMacros("AlphaState", "SDL_ALPHA_(.*)"); ctx.GenerateEnumFromMacros("HatState", "SDL_HAT_(.*)"); ctx.IgnoreHeadersWithName("SDL_atomic*"); ctx.IgnoreHeadersWithName("SDL_endian*"); ctx.IgnoreHeadersWithName("SDL_main*"); ctx.IgnoreHeadersWithName("SDL_mutex*"); ctx.IgnoreHeadersWithName("SDL_stdinc*"); ctx.IgnoreHeadersWithName("SDL_error"); ctx.IgnoreEnumWithMatchingItem("SDL_ENOMEM"); ctx.IgnoreFunctionWithName("SDL_Error"); */ } public void Postprocess(Driver driver, ASTContext ctx) { /* ctx.SetNameOfEnumWithName("PIXELTYPE", "PixelType"); ctx.SetNameOfEnumWithName("BITMAPORDER", "BitmapOrder"); ctx.SetNameOfEnumWithName("PACKEDORDER", "PackedOrder"); ctx.SetNameOfEnumWithName("ARRAYORDER", "ArrayOrder"); ctx.SetNameOfEnumWithName("PACKEDLAYOUT", "PackedLayout"); ctx.SetNameOfEnumWithName("PIXELFORMAT", "PixelFormats"); ctx.SetNameOfEnumWithName("assert_state", "AssertState"); ctx.SetClassBindName("assert_data", "AssertData"); ctx.SetNameOfEnumWithName("eventaction", "EventAction"); ctx.SetNameOfEnumWithName("LOG_CATEGORY", "LogCategory"); */ } static class Program { public static void Main(string[] args) { ConsoleDriver.Run(new Vessel()); Console.WriteLine("Done! Press any key to exit..."); Console.ReadKey(); } } } }
32.673913
89
0.736194
[ "MIT" ]
hyblocker/VesselSharp
BindingsGenerator/Program.cs
3,008
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.ManagedBlockchain")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Managed Blockchain. (New Service) Amazon Managed Blockchain is a fully managed service that makes it easy to create and manage scalable blockchain networks using popular open source frameworks.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Managed Blockchain. (New Service) Amazon Managed Blockchain is a fully managed service that makes it easy to create and manage scalable blockchain networks using popular open source frameworks.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Managed Blockchain. (New Service) Amazon Managed Blockchain is a fully managed service that makes it easy to create and manage scalable blockchain networks using popular open source frameworks.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Managed Blockchain. (New Service) Amazon Managed Blockchain is a fully managed service that makes it easy to create and manage scalable blockchain networks using popular open source frameworks.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.1.21")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
53.607843
292
0.778347
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ManagedBlockchain/Properties/AssemblyInfo.cs
2,734
C#
using MOTMaster; using MOTMaster.SnippetLibrary; using System; using System.Collections.Generic; using DAQ.Pattern; using DAQ.Analog; // This script is supposed to be the basic script for loading a molecule MOT. // Note that times are all in units of the clock periods of the two pattern generator boards (at present, both are 10us). // All times are relative to the Q switch, though note that this is not the first event in the pattern. public class Patterns : MOTMasterScript { public Patterns() { Parameters = new Dictionary<string, object>(); Parameters["PatternLength"] = 100000; Parameters["TCLBlockStart"] = 4000; // This is a time before the Q switch Parameters["TCLBlockDuration"] = 15000; Parameters["FlashToQ"] = 16; // This is a time before the Q switch Parameters["QSwitchPulseDuration"] = 10; Parameters["FlashPulseDuration"] = 10; Parameters["HeliumShutterToQ"] = 100; Parameters["HeliumShutterDuration"] = 1550; Parameters["PushBeamFrequency"] = 5.0; Parameters["FluorescenceImaginDetuning"] = 3.0; Parameters["ExposureTime"] = 15; Parameters["MOTHoldTime"] = 100; Parameters["TurnAllLightOn"] = 1000; // Camera Parameters["MOTLoadTime"] = 50000; Parameters["CameraTriggerDelayAfterFirstImage"] = 8000; Parameters["Frame0TriggerDuration"] = 15; Parameters["TriggerJitter"] = 3; Parameters["WaitBeforeImage"] = 0; Parameters["FreeExpansionTime"] = 2000; //Rb light Parameters["ImagingFrequency"] = 2.1; //2.6 new resonance Parameters["ProbePumpTime"] = 0; //This is for investigating the time it takes atoms to reach the strectched state when taking an absorption image Parameters["MOTCoolingLoadingFrequency"] = 4.6;//5.4 usewd to be Parameters["MOTRepumpLoadingFrequency"] = 6.6; //6.9 //PMT Parameters["PMTTrigger"] = 5000; Parameters["PMTTriggerDuration"] = 10; // Slowing Parameters["slowingAOMOnStart"] = 250; //started from 250 Parameters["slowingAOMOnDuration"] = 45000; Parameters["slowingAOMOffStart"] = 1500;//started from 1500 Parameters["slowingAOMOffDuration"] = 40000; Parameters["slowingRepumpAOMOnStart"] = 0;//started from 0 Parameters["slowingRepumpAOMOnDuration"] = 45000; Parameters["slowingRepumpAOMOffStart"] = 1520; Parameters["slowingRepumpAOMOffDuration"] = 35000; // Slowing Chirp Parameters["SlowingChirpStartTime"] = 340;// 340; Parameters["SlowingChirpDuration"] = 1160; Parameters["SlowingChirpStartValue"] = 0.0; Parameters["SlowingChirpEndValue"] = -1.25; // Slowing field Parameters["slowingCoilsValue"] = 8.0; //1.05; Parameters["slowingCoilsOffTime"] = 1500; // B Field Parameters["MOTCoilsSwitchOn"] = 0; Parameters["MOTCoilsSwitchOff"] = 100000; Parameters["MOTCoilsCurrentValue"] = 1.0;//1.0; // 0.65; // Shim fields Parameters["xShimLoadCurrent"] = -1.35;//3.6 Parameters["yShimLoadCurrent"] = -1.94;//-0.12 Parameters["zShimLoadCurrent"] = -0.22;//-5.35 // v0 Light Switch Parameters["MOTAOMStartTime"] = 15000; Parameters["MOTAOMDuration"] = 500; // v0 Light Intensity Parameters["v0IntensityRampStartTime"] = 5000; Parameters["v0IntensityRampDuration"] = 2000; Parameters["v0IntensityRampStartValue"] = 5.8; Parameters["v0IntensityMolassesValue"] = 5.8; // v0 Light Frequency Parameters["v0FrequencyStartValue"] = 9.0; // triggering delay (10V = 1 second) // Parameters["triggerDelay"] = 5.0; // v0 F=1 (dodgy code using an analogue output to control a TTL) Parameters["v0F1AOMStartValue"] = 5.0; Parameters["v0F1AOMOffValue"] = 0.0; // Molasses parameters: Parameters["MolassesFrequnecyRampDuration"] = 1000; Parameters["MolassesHoldDuration"] = 1000; Parameters["MolassesEndFrequency"] = 0.5; } public override PatternBuilder32 GetDigitalPattern() { PatternBuilder32 p = new PatternBuilder32(); int patternStartBeforeQ = (int)Parameters["TCLBlockStart"]; int rbMOTLoadTime = patternStartBeforeQ + (int)Parameters["MOTLoadTime"]; int rbMOTSwitchOffTime = rbMOTLoadTime + (int)Parameters["MOTHoldTime"]; int molassesStartTime = rbMOTSwitchOffTime; int molassesEndTime = rbMOTSwitchOffTime + (int)Parameters["MolassesFrequnecyRampDuration"] + (int)Parameters["MolassesHoldDuration"]; int cameraTrigger1 = molassesEndTime + (int)Parameters["FreeExpansionTime"]; int cameraTrigger2 = cameraTrigger1 + (int)Parameters["CameraTriggerDelayAfterFirstImage"]; //probe image int cameraTrigger3 = cameraTrigger2 + (int)Parameters["CameraTriggerDelayAfterFirstImage"]; //bg MOTMasterScriptSnippet lm = new LoadMoleculeMOT(p, Parameters); // This is how you load "preset" patterns. // p.AddEdge("v00Shutter", 0, true); //p.Pulse(patternStartBeforeQ, 3000 - 1400, 10000, "bXSlowingShutter"); //Takes 14ms to start closing //p.Pulse(patternStartBeforeQ, (int)Parameters["Frame0Trigger"], (int)Parameters["Frame0TriggerDuration"], "cameraTrigger"); //camera trigger for first frame //p.AddEdge("rbAbsImagingBeam", 0, false); //Rb: p.AddEdge("rb3DCooling", 0, false); p.AddEdge("rb3DCooling", molassesEndTime, true); p.AddEdge("rb3DCooling", cameraTrigger1, false); p.AddEdge("rb3DCooling", cameraTrigger1 + (int)Parameters["ExposureTime"], true); p.AddEdge("rb2DCooling", 0, false); p.AddEdge("rb2DCooling", rbMOTLoadTime, true); p.AddEdge("rbPushBeam", 0, false); p.AddEdge("rbPushBeam", rbMOTLoadTime - 200, true); p.AddEdge("rbRepump", 0, false); //Turn everything back on at end of sequence: /* p.AddEdge("rb3DCooling", (int)Parameters["PatternLength"] - 10, false); p.AddEdge("rb2DCooling", (int)Parameters["PatternLength"] - 10, false); p.AddEdge("rbPushBeam", (int)Parameters["PatternLength"] - 10, false); */ p.AddEdge("rbAbsImagingBeam", 0, true); // Imaging p.Pulse(0, cameraTrigger1, (int)Parameters["Frame0TriggerDuration"], "cameraTrigger"); p.AddEdge("rb2DMOTShutter", 0, false); p.AddEdge("rb3DMOTShutter", 0, true); p.AddEdge("rbOPShutter", 0, false); // test new digital pattern board //p.AddEdge("test00", 0, false); //p.AddEdge("test00", 100, true); return p; } public override AnalogPatternBuilder GetAnalogPattern() { AnalogPatternBuilder p = new AnalogPatternBuilder((int)Parameters["PatternLength"]); int rbMOTLoadTime = (int)Parameters["MOTLoadTime"]; int rbMOTSwitchOffTime = rbMOTLoadTime + (int)Parameters["MOTHoldTime"]; int molassesStartTime = rbMOTSwitchOffTime; int molassesEndTime = rbMOTSwitchOffTime + (int)Parameters["MolassesFrequnecyRampDuration"] + (int)Parameters["MolassesHoldDuration"]; int cameraTrigger1 = molassesEndTime + (int)Parameters["FreeExpansionTime"]; int cameraTrigger2 = cameraTrigger1 + (int)Parameters["CameraTriggerDelayAfterFirstImage"]; //probe image int cameraTrigger3 = cameraTrigger2 + (int)Parameters["CameraTriggerDelayAfterFirstImage"]; //bg MOTMasterScriptSnippet lm = new LoadMoleculeMOT(p, Parameters); // Add Analog Channels p.AddChannel("v00Intensity"); p.AddChannel("v00Frequency"); p.AddChannel("xShimCoilCurrent"); p.AddChannel("yShimCoilCurrent"); p.AddChannel("zShimCoilCurrent"); p.AddChannel("v00EOMAmp"); p.AddChannel("v00Chirp"); // Add Rb Analog channels p.AddChannel("rb3DCoolingFrequency"); p.AddChannel("rb3DCoolingAttenuation"); p.AddChannel("rbRepumpFrequency"); p.AddChannel("rbRepumpAttenuation"); p.AddChannel("rbAbsImagingFrequency"); // B Field p.AddAnalogValue("MOTCoilsCurrent", 0, (double)Parameters["MOTCoilsCurrentValue"]); //switch on MOT coils to load Rb MOT p.AddAnalogValue("MOTCoilsCurrent", rbMOTSwitchOffTime, -0.05); //switch off coils after MOT is loaded // Shim Fields p.AddAnalogValue("xShimCoilCurrent", 0, (double)Parameters["xShimLoadCurrent"]); p.AddAnalogValue("yShimCoilCurrent", 0, (double)Parameters["yShimLoadCurrent"]); p.AddAnalogValue("zShimCoilCurrent", 0, (double)Parameters["zShimLoadCurrent"]); //Rb Laser intensities p.AddAnalogValue("rbRepumpAttenuation", 0, 0.0); p.AddAnalogValue("rb3DCoolingAttenuation", 0, 0.0); //Rb Laser detunings p.AddAnalogValue("rb3DCoolingFrequency", 0, (double)Parameters["MOTCoolingLoadingFrequency"]); p.AddAnalogValue("rbRepumpFrequency", 0, (double)Parameters["MOTRepumpLoadingFrequency"]); p.AddAnalogValue("rbAbsImagingFrequency", 0, (double)Parameters["ImagingFrequency"]); //MolassesDetuningRamp: p.AddLinearRamp("rb3DCoolingFrequency", molassesStartTime, (int)Parameters["MolassesFrequnecyRampDuration"], (double)Parameters["MolassesEndFrequency"]); p.AddAnalogValue("rb3DCoolingFrequency", molassesEndTime, (double)Parameters["FluorescenceImaginDetuning"]); return p; } }
40.432773
165
0.662995
[ "MIT" ]
ColdMatter/EDMSuite
MoleculeMOTMasterScripts/RbMolassesFluorescenceImaging.cs
9,625
C#
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Xamarin.Forms; using Pedometer.Views; using Pedometer.Privilege; namespace Pedometer.ViewModels { /// <summary> /// Provides start page view abstraction /// </summary> public class StartViewModel : ViewModelBase { /// <summary> /// Navigates to main page /// </summary> public Command GoToMainPageCommand { get; } /// <summary> /// Initializes StartViewModel class instance /// </summary> public StartViewModel() { GoToMainPageCommand = new Command(ExecuteGoToMainPageCommand); } /// <summary> /// Handles execution of GoToMainPageCommand /// Navigates to main page /// </summary> private void ExecuteGoToMainPageCommand() { Application.Current.MainPage = new MainPage(); } } }
30.693878
75
0.651596
[ "Apache-2.0" ]
AchoWang/Tizen-CSharp-Samples
Wearable/Pedometer/src/Pedometer/ViewModels/StartViewModel.cs
1,504
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BL.Restaurant { public class ProductosBL { Contexto _contexto;//Variable Global public BindingList<Producto> ListaProductos { get; set; } public ProductosBL() { _contexto = new Contexto(); ListaProductos = new BindingList<Producto>(); } public BindingList<Producto> ObtenerProductos() { _contexto.Productos.Load(); //que da la tabla producto cargue los datos ListaProductos = _contexto.Productos.Local.ToBindingList(); //Transforma los datos de la lista producto hacia el bindingList return ListaProductos; } public Resultado GuardarProducto(Producto producto) { var resultado = Validar(producto); if(resultado.Exitoso == false) { return resultado; } _contexto.SaveChanges(); // el entity se encarga de hacer el resto de los cambiios resultado.Exitoso = true; return resultado; } public void AgregarProducto() { var nuevoProducto = new Producto(); ListaProductos.Add(nuevoProducto); } public bool EliminarProducto(int id) { foreach (var producto in ListaProductos) { if (producto.Id == id) { ListaProductos.Remove(producto); _contexto.SaveChanges(); return true; } } return false; } private Resultado Validar(Producto producto) { var resultado = new Resultado(); resultado.Exitoso = true; if (string.IsNullOrEmpty(producto.Descripcion) == true) { resultado.Mensaje = "Ingrese una Descripcion"; resultado.Exitoso = false; } if (producto.Cantidad <= 0) { resultado.Mensaje = " La Cantidad Debe Ser Mayor que Cero(0)"; resultado.Exitoso = false; } if (producto.Precio <= 0) { resultado.Mensaje = "El Precio Debe Ser Mayor que Cero(0)"; resultado.Exitoso = false; } if (producto.Tipo ==null) { resultado.Mensaje = "El Tipo No Puede Estar Vacio"; resultado.Exitoso = false; } return resultado; } } public class Producto { public int Id { get; set; } public string Descripcion { get; set; } public int Cantidad { get; set; } public double Precio { get; set; } public string Tipo { get; set; } public bool Activo { get; set; } } public class Resultado { public bool Exitoso { get; set; } public string Mensaje { get; set; } } }
26.533898
136
0.53114
[ "MIT" ]
Ricardo0497/RESTAURANT
Restaurant/BL.Restaurant/ProductosBL.cs
3,133
C#
using System; using System.Threading.Tasks; using Univintel.GBN.Core; using UnivIntel.GBN.Core.DataAccess.Entities; using UnivIntel.PostgreSQL.ORM.Core; namespace UnivIntel.GBN.Core.Services { public interface ISessionService { void SetDatabase(IDatabaseService databaseService); Task CheckUserHaveAccessToCompany(Guid companyId, Guid accountId); Task CheckUserHaveAccessToSavedEntity<T>(Guid id, Guid accountId) where T: BaseRepository<T>, new(); Task KataCheckUserHaveAccessToSavedEntity<T>(Guid id, Guid accountId) where T : class, new(); Task<T> GetSavedEntityByAccount<T>(Guid id, Guid accountId) where T : BaseRepository<T>, new(); Task<AccountRank> GetAccountRank(Guid accountId); } }
31.958333
108
0.732725
[ "MIT" ]
mvkhokhlov/univintel_global_business_network_backend
GBN.Core/Services/ISessionService.cs
769
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ClearHl7.Extensions; using ClearHl7.Helpers; using ClearHl7.Serialization; using ClearHl7.V271.Types; namespace ClearHl7.V271.Segments { /// <summary> /// HL7 Version 2 Segment PRD - Provider Data. /// </summary> public class PrdSegment : ISegment { /// <inheritdoc/> public string Id { get; } = "PRD"; /// <inheritdoc/> public int Ordinal { get; set; } /// <summary> /// PRD.1 - Provider Role. /// <para>Suggested: 0286 Provider Role</para> /// </summary> public IEnumerable<CodedWithExceptions> ProviderRole { get; set; } /// <summary> /// PRD.2 - Provider Name. /// </summary> public IEnumerable<ExtendedPersonName> ProviderName { get; set; } /// <summary> /// PRD.3 - Provider Address. /// </summary> public IEnumerable<ExtendedAddress> ProviderAddress { get; set; } /// <summary> /// PRD.4 - Provider Location. /// </summary> public PersonLocation ProviderLocation { get; set; } /// <summary> /// PRD.5 - Provider Communication Information. /// </summary> public IEnumerable<ExtendedTelecommunicationNumber> ProviderCommunicationInformation { get; set; } /// <summary> /// PRD.6 - Preferred Method of Contact. /// <para>Suggested: 0185 Preferred Method Of Contact -&gt; ClearHl7.Codes.V271.CodePreferredMethodOfContact</para> /// </summary> public CodedWithExceptions PreferredMethodOfContact { get; set; } /// <summary> /// PRD.7 - Provider Identifiers. /// <para>Suggested: 0338 Practitioner ID Number Type -&gt; ClearHl7.Codes.V271.CodePractitionerIdNumberType</para> /// </summary> public IEnumerable<PractitionerLicenseOrOtherIdNumber> ProviderIdentifiers { get; set; } /// <summary> /// PRD.8 - Effective Start Date of Provider Role. /// </summary> public DateTime? EffectiveStartDateOfProviderRole { get; set; } /// <summary> /// PRD.9 - Effective End Date of Provider Role. /// </summary> public IEnumerable<DateTime> EffectiveEndDateOfProviderRole { get; set; } /// <summary> /// PRD.10 - Provider Organization Name and Identifier. /// </summary> public ExtendedCompositeNameAndIdNumberForOrganizations ProviderOrganizationNameAndIdentifier { get; set; } /// <summary> /// PRD.11 - Provider Organization Address. /// </summary> public IEnumerable<ExtendedAddress> ProviderOrganizationAddress { get; set; } /// <summary> /// PRD.12 - Provider Organization Location Information. /// </summary> public IEnumerable<PersonLocation> ProviderOrganizationLocationInformation { get; set; } /// <summary> /// PRD.13 - Provider Organization Communication Information. /// </summary> public IEnumerable<ExtendedTelecommunicationNumber> ProviderOrganizationCommunicationInformation { get; set; } /// <summary> /// PRD.14 - Provider Organization Method of Contact. /// <para>Suggested: 0185 Preferred Method Of Contact -&gt; ClearHl7.Codes.V271.CodePreferredMethodOfContact</para> /// </summary> public CodedWithExceptions ProviderOrganizationMethodOfContact { get; set; } /// <inheritdoc/> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <inheritdoc/> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None); if (segments.Length > 0) { if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0) { throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString)); } } ProviderRole = segments.Length > 1 && segments[1].Length > 0 ? segments[1].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<CodedWithExceptions>(x, false, seps)) : null; ProviderName = segments.Length > 2 && segments[2].Length > 0 ? segments[2].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedPersonName>(x, false, seps)) : null; ProviderAddress = segments.Length > 3 && segments[3].Length > 0 ? segments[3].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedAddress>(x, false, seps)) : null; ProviderLocation = segments.Length > 4 && segments[4].Length > 0 ? TypeSerializer.Deserialize<PersonLocation>(segments[4], false, seps) : null; ProviderCommunicationInformation = segments.Length > 5 && segments[5].Length > 0 ? segments[5].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedTelecommunicationNumber>(x, false, seps)) : null; PreferredMethodOfContact = segments.Length > 6 && segments[6].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[6], false, seps) : null; ProviderIdentifiers = segments.Length > 7 && segments[7].Length > 0 ? segments[7].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<PractitionerLicenseOrOtherIdNumber>(x, false, seps)) : null; EffectiveStartDateOfProviderRole = segments.Length > 8 && segments[8].Length > 0 ? segments[8].ToNullableDateTime() : null; EffectiveEndDateOfProviderRole = segments.Length > 9 && segments[9].Length > 0 ? segments[9].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => x.ToDateTime()) : null; ProviderOrganizationNameAndIdentifier = segments.Length > 10 && segments[10].Length > 0 ? TypeSerializer.Deserialize<ExtendedCompositeNameAndIdNumberForOrganizations>(segments[10], false, seps) : null; ProviderOrganizationAddress = segments.Length > 11 && segments[11].Length > 0 ? segments[11].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedAddress>(x, false, seps)) : null; ProviderOrganizationLocationInformation = segments.Length > 12 && segments[12].Length > 0 ? segments[12].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<PersonLocation>(x, false, seps)) : null; ProviderOrganizationCommunicationInformation = segments.Length > 13 && segments[13].Length > 0 ? segments[13].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => TypeSerializer.Deserialize<ExtendedTelecommunicationNumber>(x, false, seps)) : null; ProviderOrganizationMethodOfContact = segments.Length > 14 && segments[14].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[14], false, seps) : null; } /// <inheritdoc/> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return string.Format( culture, StringHelper.StringFormatSequence(0, 15, Configuration.FieldSeparator), Id, ProviderRole != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderRole.Select(x => x.ToDelimitedString())) : null, ProviderName != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderName.Select(x => x.ToDelimitedString())) : null, ProviderAddress != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderAddress.Select(x => x.ToDelimitedString())) : null, ProviderLocation?.ToDelimitedString(), ProviderCommunicationInformation != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderCommunicationInformation.Select(x => x.ToDelimitedString())) : null, PreferredMethodOfContact?.ToDelimitedString(), ProviderIdentifiers != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderIdentifiers.Select(x => x.ToDelimitedString())) : null, EffectiveStartDateOfProviderRole.HasValue ? EffectiveStartDateOfProviderRole.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, EffectiveEndDateOfProviderRole != null ? string.Join(Configuration.FieldRepeatSeparator, EffectiveEndDateOfProviderRole.Select(x => x.ToString(Consts.DateTimeFormatPrecisionSecond, culture))) : null, ProviderOrganizationNameAndIdentifier?.ToDelimitedString(), ProviderOrganizationAddress != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderOrganizationAddress.Select(x => x.ToDelimitedString())) : null, ProviderOrganizationLocationInformation != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderOrganizationLocationInformation.Select(x => x.ToDelimitedString())) : null, ProviderOrganizationCommunicationInformation != null ? string.Join(Configuration.FieldRepeatSeparator, ProviderOrganizationCommunicationInformation.Select(x => x.ToDelimitedString())) : null, ProviderOrganizationMethodOfContact?.ToDelimitedString() ).TrimEnd(Configuration.FieldSeparator.ToCharArray()); } } }
62.962963
276
0.657451
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7/V271/Segments/PrdSegment.cs
10,202
C#
using DShop.Services.Discounts.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DShop.Services.Discounts.Repositories { public interface ICustomersRepository { Task<Customer> GetAsync(Guid id); Task AddAsync(Customer customer); } }
21.866667
47
0.746951
[ "MIT" ]
nilayshah80/DNC-DShop
DNC-DShop.Services.Discounts/src/DShop.Services.Discounts/Repositories/ICustomersRepository.cs
330
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using Elasticsearch.Net.Utf8Json; namespace Nest { /// <summary> /// input to load data from multiple sources into the watch execution context when the watch is triggered. /// </summary> [InterfaceDataContract] [JsonFormatter(typeof(ChainInputFormatter))] public interface IChainInput : IInput { /// <summary> /// The input sources /// </summary> IDictionary<string, InputContainer> Inputs { get; set; } } /// <inheritdoc /> public class ChainInput : InputBase, IChainInput { public ChainInput() { } public ChainInput(IDictionary<string, InputContainer> inputs) => Inputs = inputs; /// <inheritdoc /> public IDictionary<string, InputContainer> Inputs { get; set; } internal override void WrapInContainer(IInputContainer container) => container.Chain = this; } /// <inheritdoc /> public class ChainInputDescriptor : DescriptorBase<ChainInputDescriptor, IChainInput>, IChainInput { public ChainInputDescriptor() { } public ChainInputDescriptor(IDictionary<string, InputContainer> inputs) => Self.Inputs = inputs; IDictionary<string, InputContainer> IChainInput.Inputs { get; set; } /// <inheritdoc /> public ChainInputDescriptor Input(string name, Func<InputDescriptor, InputContainer> selector) { if (Self.Inputs != null) { if (Self.Inputs.ContainsKey(name)) throw new InvalidOperationException($"An input named '{name}' has already been specified. Choose a different name"); } else Self.Inputs = new Dictionary<string, InputContainer>(); Self.Inputs.Add(name, selector.InvokeOrDefault(new InputDescriptor())); return this; } } internal class ChainInputFormatter : IJsonFormatter<IChainInput> { public IChainInput Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { if (reader.GetCurrentJsonToken() != JsonToken.BeginObject) { reader.ReadNextBlock(); return null; } // inputs property reader.ReadNext(); // { reader.ReadNext(); // "inputs" reader.ReadNext(); // : var count = 0; var inputs = new Dictionary<string, InputContainer>(); var inputContainerFormatter = formatterResolver.GetFormatter<InputContainer>(); while (reader.ReadIsInArray(ref count)) { reader.ReadNext(); // { var name = reader.ReadPropertyName(); var input = inputContainerFormatter.Deserialize(ref reader, formatterResolver); reader.ReadNext(); // } inputs.Add(name, input); } reader.ReadNext(); // } return new ChainInput(inputs); } public void Serialize(ref JsonWriter writer, IChainInput value, IJsonFormatterResolver formatterResolver) { if (value?.Inputs == null) return; writer.WriteBeginObject(); writer.WritePropertyName("inputs"); writer.WriteBeginArray(); var count = 0; var inputContainerFormatter = formatterResolver.GetFormatter<IInputContainer>(); foreach (var input in value.Inputs) { if (count > 0) writer.WriteValueSeparator(); writer.WriteBeginObject(); writer.WritePropertyName(input.Key); inputContainerFormatter.Serialize(ref writer, input.Value, formatterResolver); writer.WriteEndObject(); count++; } writer.WriteEndArray(); writer.WriteEndObject(); } } }
28.57377
121
0.716294
[ "Apache-2.0" ]
Brightspace/elasticsearch-net
src/Nest/XPack/Watcher/Input/ChainInput.cs
3,488
C#
using System; using System.Collections.Generic; namespace BalancedParenthesis { class Program { static void Main(string[] args) { string input = Console.ReadLine(); Stack<char> stack = new Stack<char>(); bool isInvalid = false; for (int i = 0; i < input.Length; i++) { if (input[i] == '{' || input[i] == '[' || input[i] == '(') { stack.Push(input[i]); } else { if (stack.Count == 0) { isInvalid = true; } else if ((input[i] == '}' && stack.Peek() == '{') || (input[i] == ']' && stack.Peek() == '[') || (input[i] == ')' && stack.Peek() == '(')) { stack.Pop(); } else { isInvalid = true; } } if (isInvalid) { break; } } if (stack.Count > 0) { isInvalid = true; } if (isInvalid) { Console.WriteLine("NO"); } else { Console.WriteLine("YES"); } } } }
22.818182
74
0.285525
[ "MIT" ]
Mithras11/C_Sharp-Advanced-SoftUni
Stacks_And_Queues/BalancedParenthesis/Program.cs
1,508
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FamiStudio { class TransformDialog { enum TransformOperation { SongCleanup, ProjectCleanup, Max }; readonly string[] ConfigSectionNames = { "Song Cleanup", "Project Cleanup", "" }; public delegate void EmptyDelegate(); public event EmptyDelegate CleaningUp; private PropertyPage[] pages = new PropertyPage[(int)TransformOperation.Max]; private MultiPropertyDialog dialog; private FamiStudio app; public unsafe TransformDialog(FamiStudio famistudio) { app = famistudio; dialog = new MultiPropertyDialog(550, 500); for (int i = 0; i < (int)TransformOperation.Max; i++) { var section = (TransformOperation)i; var page = dialog.AddPropertyPage(ConfigSectionNames[i], "Clean"); CreatePropertyPage(page, section); } } private string[] GetSongNames() { var names = new string[app.Project.Songs.Count]; for (var i = 0; i < app.Project.Songs.Count; i++) names[i] = app.Project.Songs[i].Name; return names; } private PropertyPage CreatePropertyPage(PropertyPage page, TransformOperation section) { switch (section) { case TransformOperation.SongCleanup: page.AddCheckBox("Merge identical patterns:", true); // 0 page.AddCheckBox("Delete empty patterns:", true); // 1 page.AddCheckBox("Adjust maximum note lengths:", true); // 2 page.AddCheckBoxList(null, GetSongNames(), null); // 3 break; case TransformOperation.ProjectCleanup: page.AddCheckBox("Delete unused instruments:", true); // 0 page.AddCheckBox("Merge identical instruments:", true); // 1 page.AddCheckBox("Unassign unused DPCM instrument keys:", true); // 2 page.AddCheckBox("Delete unassigned samples:", true); // 3 page.AddCheckBox("Permanently apply all DPCM samples processing:", false); // 4 page.AddCheckBox("Delete unused arpeggios:", true); // 5 page.PropertyChanged += ProjectCleanup_PropertyChanged; break; } page.Build(); pages[(int)section] = page; return page; } private void ProjectCleanup_PropertyChanged(PropertyPage props, int propIdx, int rowIdx, int colIdx, object value) { // Applying processing implies deleting source data. if (propIdx == 5) { var applyProcessing = (bool)value; if (applyProcessing) props.SetPropertyValue(4, true); props.SetPropertyEnabled(4, !applyProcessing); } } private int[] GetSongIds(bool[] selectedSongs) { var songIds = new List<int>(); for (int i = 0; i < selectedSongs.Length; i++) { if (selectedSongs[i]) songIds.Add(app.Project.Songs[i].Id); } return songIds.ToArray(); } private void SongCleanup() { var props = dialog.GetPropertyPage((int)TransformOperation.SongCleanup); var songIds = GetSongIds(props.GetPropertyValue<bool[]>(3)); var mergeIdenticalPatterns = props.GetPropertyValue<bool>(0); var deleteEmptyPatterns = props.GetPropertyValue<bool>(1); var reduceNoteLengths = props.GetPropertyValue<bool>(2); if (songIds.Length > 0 && (mergeIdenticalPatterns || deleteEmptyPatterns || reduceNoteLengths)) { app.UndoRedoManager.BeginTransaction(TransactionScope.Project); CleaningUp?.Invoke(); foreach (var songId in songIds) { app.Project.GetSong(songId).DeleteNotesPastMaxInstanceLength(); } if (reduceNoteLengths) { foreach (var songId in songIds) app.Project.GetSong(songId).SetNoteDurationToMaximumLength(); } if (mergeIdenticalPatterns) { foreach (var songId in songIds) app.Project.GetSong(songId).MergeIdenticalPatterns(); } if (deleteEmptyPatterns) { foreach (var songId in songIds) app.Project.GetSong(songId).DeleteEmptyPatterns(); } app.UndoRedoManager.EndTransaction(); } } private void ProjectCleanup() { var props = dialog.GetPropertyPage((int)TransformOperation.ProjectCleanup); var deleteUnusedInstruments = props.GetPropertyValue<bool>(0); var mergeIdenticalInstruments = props.GetPropertyValue<bool>(1); var unassignUnusedSamples = props.GetPropertyValue<bool>(2); var deleteUnusedSamples = props.GetPropertyValue<bool>(3); var applyAllSamplesProcessing = props.GetPropertyValue<bool>(4); var deleteUnusedArpeggios = props.GetPropertyValue<bool>(5); if (mergeIdenticalInstruments || deleteUnusedInstruments || unassignUnusedSamples || deleteUnusedSamples || applyAllSamplesProcessing || deleteUnusedArpeggios) { app.UndoRedoManager.BeginTransaction(TransactionScope.Project); CleaningUp?.Invoke(); if (deleteUnusedInstruments) { app.Project.DeleteUnusedInstruments(); } if (mergeIdenticalInstruments) { app.Project.MergeIdenticalInstruments(); } if (unassignUnusedSamples) { app.Project.UnmapUnusedSamples(); } if (deleteUnusedSamples) { app.Project.DeleteUnmappedSamples(); } if (applyAllSamplesProcessing) { app.Project.PermanentlyApplyAllSamplesProcessing(); } if (deleteUnusedArpeggios) { app.Project.DeleteUnusedArpeggios(); } app.UndoRedoManager.EndTransaction(); } } public DialogResult ShowDialog(FamiStudioForm parent) { var dialogResult = dialog.ShowDialog(parent); if (dialogResult == DialogResult.OK) { var operation = (TransformOperation)dialog.SelectedIndex; switch (operation) { case TransformOperation.SongCleanup: SongCleanup(); break; case TransformOperation.ProjectCleanup: ProjectCleanup(); break; } } return dialogResult; } } }
35.699115
172
0.501239
[ "MIT" ]
mcgrew/FamiStudio
FamiStudio/Source/UI/Common/TransformDialog.cs
7,845
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 servicecatalog-2015-12-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ServiceCatalog.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServiceCatalog.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateServiceAction operation /// </summary> public class CreateServiceActionResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateServiceActionResponse response = new CreateServiceActionResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ServiceActionDetail", targetDepth)) { var unmarshaller = ServiceActionDetailUnmarshaller.Instance; response.ServiceActionDetail = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParametersException")) { return InvalidParametersExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException")) { return LimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonServiceCatalogException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static CreateServiceActionResponseUnmarshaller _instance = new CreateServiceActionResponseUnmarshaller(); internal static CreateServiceActionResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateServiceActionResponseUnmarshaller Instance { get { return _instance; } } } }
38.298246
197
0.655062
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ServiceCatalog/Generated/Model/Internal/MarshallTransformations/CreateServiceActionResponseUnmarshaller.cs
4,366
C#