content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) .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.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query.Sql.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class FromSqlNonComposedQuerySqlGenerator : DefaultQuerySqlGenerator
{
private readonly string _sql;
private readonly Expression _arguments;
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public FromSqlNonComposedQuerySqlGenerator(
[NotNull] QuerySqlGeneratorDependencies dependencies,
[NotNull] SelectExpression selectExpression,
[NotNull] string sql,
[NotNull] Expression arguments)
: base(dependencies, selectExpression)
{
Check.NotEmpty(sql, nameof(sql));
Check.NotNull(arguments, nameof(arguments));
_sql = sql;
_arguments = arguments;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override Expression Visit(Expression expression)
{
GenerateFromSql(_sql, _arguments, ParameterValues);
return expression;
}
/// <summary>
/// Whether or not the generated SQL could have out-of-order projection columns.
/// </summary>
public override bool RequiresRuntimeProjectionRemapping => true;
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public override IRelationalValueBufferFactory CreateValueBufferFactory(
IRelationalValueBufferFactoryFactory relationalValueBufferFactoryFactory, DbDataReader dataReader)
{
Check.NotNull(relationalValueBufferFactoryFactory, nameof(relationalValueBufferFactoryFactory));
Check.NotNull(dataReader, nameof(dataReader));
var readerColumns
= Enumerable
.Range(0, dataReader.FieldCount)
.Select(
i => new
{
Name = dataReader.GetName(i),
Ordinal = i
})
.ToList();
var types = new TypeMaterializationInfo[SelectExpression.Projection.Count];
for (var i = 0; i < SelectExpression.Projection.Count; i++)
{
if (SelectExpression.Projection[i] is ColumnExpression columnExpression)
{
var columnName = columnExpression.Name;
if (columnName != null)
{
var readerColumn
= readerColumns.SingleOrDefault(
c =>
string.Equals(columnName, c.Name, StringComparison.OrdinalIgnoreCase));
if (readerColumn == null)
{
throw new InvalidOperationException(RelationalStrings.FromSqlMissingColumn(columnName));
}
types[i] = new TypeMaterializationInfo(
columnExpression.Type,
columnExpression.Property,
Dependencies.TypeMappingSource,
fromLeftOuterJoin: false,
readerColumn.Ordinal);
}
}
}
return relationalValueBufferFactoryFactory.Create(types);
}
}
}
| 40.763158 | 116 | 0.585754 | [
"Apache-2.0"
] | Alecu100/EntityFrameworkCore | src/EFCore.Relational/Query/Sql/Internal/FromSqlNonComposedQuerySqlGenerator.cs | 4,647 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UniHttpScriptBehaviour : UniScriptBehaviour
{
public string scriptUrl;
public void Awake()
{
if (string.IsNullOrEmpty(scriptUrl))
return;
StartCoroutine(ReloadScript());
}
IEnumerator ReloadScript()
{
var www = new WWW(scriptUrl);
yield return www;
if (string.IsNullOrEmpty(www.error))
Bind(www.text);
else
Debug.LogError("[LoadError] " + www.error);
}
}
| 20.888889 | 56 | 0.617021 | [
"MIT"
] | TK-Aria/AriaUnity-HotReload | Runtime/UniScript/Scripts/UniHttpScriptBehaviour.cs | 566 | C# |
using System;
namespace lottery1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lotto");
Random rnd = new Random();
int[] lottery = new int[7];
for (int i = 0; i < lottery.Length;)
{
lottery[i] = rnd.Next(41);
if (lottery[i] != 0)
{
i++;
}
}
bool didSwap;
do
{
didSwap = false;
for (int i = 0; i < lottery.Length - 1; i++)
{
if (lottery[i] > lottery[i + 1])
{
int temp = lottery[i + 1];
lottery[i + 1] = lottery[i];
lottery[i] = temp;
didSwap = true;
}
}
} while (didSwap);
for (int y = 0; y != lottery.Length; y++)
{
Console.Write(lottery[y]);
if (y < lottery.Length-1)
{
Console.Write(", ");
}
}
Console.WriteLine();
Console.WriteLine($"lisänumero: {rnd.Next(4)}");
Console.WriteLine($"Tuplausnumero: {rnd.Next(40)}");
}
}
}
| 27.938776 | 64 | 0.341125 | [
"MIT"
] | Teropau/programming-basics-2018 | Array_tasks/lottery1/lottery1/Program.cs | 1,372 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/mmeapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W"]/*' />
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe partial struct AUXCAPS2W
{
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.wMid"]/*' />
[NativeTypeName("WORD")]
public ushort wMid;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.wPid"]/*' />
[NativeTypeName("WORD")]
public ushort wPid;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.vDriverVersion"]/*' />
[NativeTypeName("MMVERSION")]
public uint vDriverVersion;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.szPname"]/*' />
[NativeTypeName("WCHAR [32]")]
public fixed ushort szPname[32];
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.wTechnology"]/*' />
[NativeTypeName("WORD")]
public ushort wTechnology;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.wReserved1"]/*' />
[NativeTypeName("WORD")]
public ushort wReserved1;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.dwSupport"]/*' />
[NativeTypeName("DWORD")]
public uint dwSupport;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.ManufacturerGuid"]/*' />
public Guid ManufacturerGuid;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.ProductGuid"]/*' />
public Guid ProductGuid;
/// <include file='AUXCAPS2W.xml' path='doc/member[@name="AUXCAPS2W.NameGuid"]/*' />
public Guid NameGuid;
}
| 37.75 | 145 | 0.684157 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/mmeapi/AUXCAPS2W.cs | 1,965 | C# |
using MC_Debug_Monitor.Properties;
using MC_Debug_Monitor.utils;
using System;
using System.Collections.Generic;
using System.Net;
using System.Windows.Forms;
namespace MC_Debug_Monitor.Controls
{
public partial class serverManager : UserControl
{
public serverManager()
{
InitializeComponent();
}
private void rconIPLeaved(object sender, EventArgs e)
{
if (rconIP.Text.Equals("localhost"))
{
rconIP.Text = "127.0.0.1";
return;
}
try
{
IPAddress.Parse(rconIP.Text);
}
catch
{
rconIP.Text = Settings.Default.rconIP;
System.Media.SystemSounds.Beep.Play();
}
saveAllSettings();
}
private void rconPortLeaved(object sender, EventArgs e)
{
saveAllSettings();
}
private void rconPassLeaved(object sender, EventArgs e)
{
saveAllSettings();
}
private void scoreboardMonitor_Load(object sender, EventArgs e)
{
rconIP.Text = Settings.Default.rconIP;
rconPort.Value = Settings.Default.rconPort;
rconPass.Text = Settings.Default.rconPass;
onDisConnectServer();
}
private void saveAllSettings()
{
Settings.Default.rconIP = rconIP.Text;
Settings.Default.rconPass = rconPass.Text;
Settings.Default.rconPort = rconPort.Value;
Settings.Default.Save();
}
private void getIPButton_Click(object sender, EventArgs e)
{
string hostname = Dns.GetHostName();
IPAddress[] adrList = Dns.GetHostAddresses(hostname);
foreach (IPAddress address in adrList)
{
rconIP.Text = address.ToString();
}
}
private void importButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Server properties file|server.properties";
if (ofd.ShowDialog() == DialogResult.OK)
{
System.IO.Stream stream;
stream = ofd.OpenFile();
if (stream != null)
{
Dictionary<string, string> properties = FileUtil.getServerProperties(stream);
try
{
if (properties["enable-rcon"].Equals("true"))
{
if (properties["server-ip"] != null) rconIP.Text = properties["server-ip"];
rconPort.Value = int.Parse(properties["rcon.port"]);
rconPass.Text = properties["rcon.password"];
System.Media.SystemSounds.Asterisk.Play();
}
else
{
MessageBox.Show("Rconが有効ではありません。\nserver.propertiesの内容を確認してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("設定の値が不正です。\nserver.propertiesの内容を確認してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
saveAllSettings();
}
private void serverControl_Enter(object sender, EventArgs e)
{
}
private void connectButton_Click(object sender, EventArgs e)
{
Invoke((Action)(async () =>
{
connectButton.Enabled = false;
rconSetting.Enabled = false;
await Program.mainform.tryConnectServer();
if (Program.mainform.isConnectedServer)
{
Program.mainform.rcon.OnDisconnected += (Action)Invoke((Action)onDisConnectServer);
onConnectServer();
}
else
{
onDisConnectServer();
}
}));
}
private void onConnectServer()
{
disconnectButton.Enabled = true;
reloadButton.Enabled = true;
rconSetting.Enabled = false;
connectButton.Enabled = false;
}
private void onDisConnectServer()
{
disconnectButton.Enabled = false;
reloadButton.Enabled = false;
connectButton.Enabled = true;
rconSetting.Enabled = true;
}
private void disconnectButton_Click(object sender, EventArgs e)
{
Program.mainform.onDisconnectServer();
onDisConnectServer();
}
private void reloadButton_Click(object sender, EventArgs e)
{
Invoke((Action)(async () =>
{
reloadButton.Enabled = false;
Program.mainform.setServerStatus("reloading");
Program.mainform.setStatusText("サーバーをリロード中");
if (Program.mainform.isConnectedServer)
{
await Program.mainform.sendCommand("reload");
}
Program.mainform.setStatusText("リロード完了");
reloadButton.Enabled = true;
Program.mainform.setServerStatus("online");
}));
}
}
}
| 32.381503 | 146 | 0.50482 | [
"MIT"
] | kemo14331/MC-Debug-Monitor | MC Debug Monitor/Controls/ServerManager.cs | 5,742 | C# |
using NiconicoToolkit.Mylist;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace NiconicoToolkit.Follow
{
public class FollowMylistResponse : ResponseWithMeta
{
[JsonPropertyName("data")]
public FollowMylistData Data { get; set; }
}
public class FollowMylistData
{
[JsonPropertyName("followLimit")]
public long FollowLimit { get; set; }
[JsonPropertyName("mylists")]
public List<FollowMylist> Mylists { get; set; }
}
public class FollowMylist
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("status")]
public ContentStatus Status { get; set; }
[JsonPropertyName("detail")]
public NvapiMylistItem Detail { get; set; }
}
}
| 23.657895 | 56 | 0.65406 | [
"MIT"
] | tor4kichi/NiconicoToolkit | NiconicoToolkit.Shared/Follow/FollowMylistResponse.cs | 901 | C# |
using System;
namespace keeema.aquapcetraffic
{
class TrafficItem
{
public string Place { get; set; }
public DateTime TimeStamp { get; set; }
public int Count { get; set; }
public override string ToString()
{
return $"Place: {this.Place}, Count: {this.Count}, Timestamp (UTC):{this.TimeStamp}";
}
}
} | 20.888889 | 97 | 0.571809 | [
"MIT"
] | keeema/aquapce-traffic | TrafficItem.cs | 376 | C# |
namespace LeetCode.Naive.Problems;
/// <summary>
/// Problem: https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/
/// Submission: https://leetcode.com/submissions/detail/635706432/
/// </summary>
internal class P2167
{
public class Solution
{
public int MinimumTime(string s)
{
// type 3 cost
const int any = 2;
var left = new int[s.Length];
var right = new int[s.Length];
var n = s.Length;
// the idea is by removing from left and right - we meet at some index i
// so build prefix and suffix arrays
// left[i] - minimum operation needed with options of removing from left or any ch (2 points)
// right[i] - minimum operation needed with options of removing from right or any ch (2 points)
for (int i = 0; i < n; i++)
{
if (s[i] == '0')
{
left[i] = (i > 0) ? left[i - 1] : 0;
}
else
{
// either cost is index or prev + 2 points
left[i] = (i > 0) ? Math.Min(i + 1, left[i - 1] + any) : 1;
}
}
for (int i = n - 1; i >= 0; i--)
{
if (s[i] == '0')
{
right[i] = (i < n - 1) ? right[i + 1] : 0;
}
else
{
right[i] = (i < n - 1) ? Math.Min(n - i, right[i + 1] + any) : 1;
}
}
var ans = int.MaxValue;
// find min at every meeting point
for (var i = 0; i < n - 1; i++)
{
ans = Math.Min(ans, left[i] + right[i + 1]);
}
ans = Math.Min(ans, left[n - 1]);
ans = Math.Min(ans, right[0]);
return ans;
}
}
}
| 25.686567 | 104 | 0.475886 | [
"MIT"
] | viacheslave/algo | leetcode/c#/Problems/P2167.cs | 1,721 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.KeyVault.V20200401Preview.Outputs
{
/// <summary>
/// A rule governing the accessibility of a vault from a specific virtual network.
/// </summary>
[OutputType]
public sealed class VirtualNetworkRuleResponse
{
/// <summary>
/// Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'.
/// </summary>
public readonly string Id;
/// <summary>
/// Property to specify whether NRP will ignore the check if parent subnet has serviceEndpoints configured.
/// </summary>
public readonly bool? IgnoreMissingVnetServiceEndpoint;
[OutputConstructor]
private VirtualNetworkRuleResponse(
string id,
bool? ignoreMissingVnetServiceEndpoint)
{
Id = id;
IgnoreMissingVnetServiceEndpoint = ignoreMissingVnetServiceEndpoint;
}
}
}
| 33.717949 | 167 | 0.679848 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/KeyVault/V20200401Preview/Outputs/VirtualNetworkRuleResponse.cs | 1,315 | C# |
using System;
using System.Collections.Generic;
namespace ViennaNET.Messaging.Resources.Impl
{
/// <summary>
/// Базовый класс хранилища ресурсов для сериализации сообщений
/// </summary>
public abstract class ResourcesStorage : IResourcesStorage
{
/// <inheritdoc />
public IDictionary<Type, IEnumerable<string>> EmbeddedResources { get; } = new Dictionary<Type, IEnumerable<string>>();
/// <summary>
/// Помещает соответствие типа сообщения и строки пути в хранилище
/// </summary>
/// <param name="type">Тип сообщения</param>
/// <param name="path">Строка пути</param>
protected void SetEmbeddedResourceDefinition(Type type, IEnumerable<string> path)
{
EmbeddedResources[type] = path;
}
protected void SetEmbeddedResourceDefinition(Type type, string path)
{
EmbeddedResources[type] = new[] { path };
}
}
} | 30.758621 | 123 | 0.684978 | [
"MIT"
] | Magicianred/ViennaNET | ViennaNET.Messaging/Resources/Impl/ResourcesStorage.cs | 1,023 | C# |
//------------------------
// My Ideas
// Endless runner
// Avoid obstacles(Trees, you bounce back a bit if you hit it)
// Pickup objects
// Powerups(faster, higher highscore)
// powerdowns( slower, less highscore, restart, reverse controlls)
// or use the trees as real obstacles?
// High score
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playerscript_2dplatformer: MonoBehaviour {
public GUIText countext;
public GUIText wintext;
private int count;
public float speed = 0.3f;
public float jump = 1.0f;
public Transform startposition;
public int wincount = 4;
// Use this for initialization
void Start() {
print("Hej");
count = 0;
SetCountText();
wintext.text = "";
}
// Update is called once per frame
void Update() {
}
void FixedUpdate() {
PlayerMovement();
QuitApp();
}
public void PlayerMovement() {
if (Input.anyKey) {
if (Input.GetKeyDown(KeyCode.W)) {
// print ("W is pressed");
this.transform.Translate(new Vector2(0, jump));
}
if (Input.GetKey(KeyCode.A)) {
// print ("A is pressed");
this.transform.Translate(new Vector2(-speed, 0));
}
if (Input.GetKey(KeyCode.S)) {
// print ("S is pressed");
this.transform.Translate(new Vector2(0, -speed));
}
if (Input.GetKey(KeyCode.D)) {
// print ("D is pressed");
this.transform.Translate(new Vector2(speed, 0));
}
if (Input.GetKey(KeyCode.R)) {
// reset to startposition aka origo.
this.transform.position = startposition.position;
this.transform.rotation = startposition.rotation;
// print ("R is pressed");
}
} else {
//print ("nothing is pressed");
}
// print ("Goodbye");
}
void QuitApp() {
if (Input.GetKeyDown(KeyCode.Escape)) {
Application.Quit();
}
}
// On Collision something something
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "wall") {
print("Collision has been dectected");
}
if (collision.gameObject.tag == "Checkpoint") {
print("Checkpoint has been dectected");
}
if (collision.gameObject.tag == "start") {
print("start has been dectected");
}
if (collision.gameObject.tag == "end") {
print("end has been dectected");
}
if (collision.gameObject.tag == "Obstacle") {
StartCoroutine(HitObstacle());
print("Obstacle hit");
}
}
void OnTriggerStay(Collider trigger) {
if (trigger.gameObject.tag == "Ladder") {
print("Ladder is enabled.");
}
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Pickup") {
print("Picked up object");
other.gameObject.SetActive(false);
count = count + 1;
SetCountText();
}
if (other.gameObject.tag == "Speedboost") {
StartCoroutine(StopSpeedBoost());
print("SpeedBoost");
}
}
void SetCountText() {
countext.text = "Count" + count.ToString();
if (count >= wincount) {
wintext.text = "You win!";
Application.LoadLevel("level02");
}
}
IEnumerator StopSpeedBoost() {
speed = 1.0F;
yield return new WaitForSeconds(3F);
speed = 0.3;
print("speedboost over");
}
IEnumerator HitObstacle() {
speed = 0.2F;
yield return new WaitForSeconds(3F);
speed = 0.3F;
}
}
| 29.441379 | 66 | 0.487936 | [
"Unlicense"
] | adde9708/Scripts-unity | Playerscript_2dplatformer.cs | 4,271 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PixelGridSnap : MonoBehaviour
{
[SerializeField]
private float pixelsPerUnit = 16f;
void LateUpdate ()
{
var unitsPerPixel = 1f / pixelsPerUnit;
var parentPos = transform.parent.position;
parentPos.x = roundNearest(parentPos.x, unitsPerPixel);
parentPos.y = roundNearest(parentPos.y, unitsPerPixel);
transform.position = parentPos;
}
float roundNearest(float x, float m)
{
var mod = MathHelper.trueMod(x, m);
var roundedDown = x - mod;
if (mod >= m / 2f)
return roundedDown + m;
else
return roundedDown;
}
}
| 22.363636 | 63 | 0.624661 | [
"MIT"
] | Chienoki/NitoriWare | Assets/Scripts/Generic Microgame Behaviors/Movement/PixelGridSnap.cs | 740 | C# |
using System.Reflection;
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("C&C AI Editor")]
[assembly: AssemblyDescription("AI Editor for RA2 and TS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Askeladd")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Askeladd")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
[assembly: AssemblyFileVersionAttribute("2.0.4.5")]
| 41.183333 | 84 | 0.706597 | [
"ISC"
] | E1Elite/aiedit | AssemblyInfo.cs | 2,471 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace System.Net.Sockets
{
// OverlappedAsyncResult
//
// This class is used to take care of storage for async Socket operation
// from the BeginSend, BeginSendTo, BeginReceive, BeginReceiveFrom calls.
internal partial class OverlappedAsyncResult : BaseOverlappedAsyncResult
{
private int _socketAddressSize;
internal int GetSocketAddressSize()
{
return _socketAddressSize;
}
public void CompletionCallback(int numBytes, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode)
{
if (_socketAddress != null)
{
Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socket address: {socketAddress}");
_socketAddressSize = socketAddressSize;
}
base.CompletionCallback(numBytes, errorCode);
}
}
}
| 33.848485 | 148 | 0.671441 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Unix.cs | 1,117 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
namespace StrandedStringBuilder
{
[DebuggerStepThrough]
internal sealed class Chunk
{
public object Value;
private string _string;
private bool _isConverted;
public Chunk Next;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Chunk(object value)
{
Value = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Chunk(string value)
{
Value = value;
_isConverted = true;
_string = value;
}
public int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!_isConverted) Init();
return _string?.Length ?? 0;
}
}
public string String
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!_isConverted) Init();
return _string;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Init()
{
if (_string != null) return;
_string = Value?.ToString();
_isConverted = true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString()
{
return String;
}
public static Chunk Empty => new Chunk("");
public static Chunk NewLine => new Chunk(Environment.NewLine);
}
}
| 24.333333 | 70 | 0.54735 | [
"MIT"
] | ChaosPandion/StrandedStringBuilder | StrandedStringBuilder/Chunk.cs | 1,681 | C# |
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using WebApiClientCore.Exceptions;
namespace WebApiClientCore.JsonConverters
{
/// <summary>
/// JsonString的类型转换器
/// </summary>
class JsonStringConverter : JsonConverterFactory
{
/// <summary>
/// 获取唯一实例
/// </summary>
public static JsonStringConverter Default { get; } = new JsonStringConverter();
/// <summary>
/// 返回是否可以转换
/// </summary>
/// <param name="typeToConvert"></param>
/// <returns></returns>
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsInheritFrom<IJsonString>();
}
/// <summary>
/// 创建转换器
/// </summary>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
return Lambda.CreateCtorFunc<JsonConverter>(typeof(Converter<>).MakeGenericType(typeToConvert))();
}
/// <summary>
/// 转换器
/// </summary>
/// <typeparam name="T"></typeparam>
private class Converter<T> : JsonConverter<T>
{
/// <summary>
/// 将json文本反序列化JsonString的Value的类型
/// 并构建JsonString类型并返回
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var json = reader.GetString();
var valueType = typeToConvert.GenericTypeArguments.First();
var value = JsonSerializer.Deserialize(json, valueType, options);
var jsonString = Activator.CreateInstance(typeToConvert, new object[] { value });
if (jsonString == null)
{
throw new TypeInstanceCreateException(typeToConvert);
}
return (T)jsonString;
}
/// <summary>
/// 将JsonString的value序列化文本,并作为json的某字段值
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
var jsonString = (IJsonString?)value;
if (jsonString == null)
{
writer.WriteStringValue(default(string));
}
else
{
var json = JsonSerializer.Serialize(jsonString.Value, jsonString.ValueType, options);
writer.WriteStringValue(json);
}
}
}
}
}
| 34.640449 | 112 | 0.53422 | [
"MIT"
] | BarlowDu/WebApiClient | WebApiClientCore/JsonConverters/JsonStringConverter.cs | 3,211 | C# |
#region License
// Copyright (c) 2020 Jens Eisenbach
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Text.Json.Serialization;
using BricklinkSharp.Client.Json;
namespace BricklinkSharp.Client
{
public class Cost : CostBase
{
[JsonPropertyName("salesTax_collected_by_BL"), JsonConverter(typeof(DecimalStringConverter))]
public decimal SalesTaxCollectedByBricklink { get; set; }
[JsonPropertyName("final_total"), JsonConverter(typeof(DecimalStringConverter))]
public decimal FinalTotal { get; set; }
[JsonPropertyName("etc1"), JsonConverter(typeof(DecimalStringConverter))]
public decimal Etc1 { get; set; }
[JsonPropertyName("etc2"), JsonConverter(typeof(DecimalStringConverter))]
public decimal Etc2 { get; set; }
[JsonPropertyName("insurance"), JsonConverter(typeof(DecimalStringConverter))]
public decimal Insurance { get; set; }
[JsonPropertyName("shipping"), JsonConverter(typeof(DecimalStringConverter))]
public decimal Shipping { get; set; }
[JsonPropertyName("credit"), JsonConverter(typeof(DecimalStringConverter))]
public decimal Credit { get; set; }
[JsonPropertyName("coupon"), JsonConverter(typeof(DecimalStringConverter))]
public decimal Coupon { get; set; }
[JsonPropertyName("vat_rate"), JsonConverter(typeof(DecimalStringConverter))]
public decimal VatRate { get; set; }
[JsonPropertyName("vat_amount"), JsonConverter(typeof(DecimalStringConverter))]
public decimal VatAmount { get; set; }
}
} | 42.111111 | 101 | 0.727101 | [
"MIT"
] | aalex675/BricklinkSharp | BricklinkSharp.Client/Cost.cs | 2,655 | C# |
using System;
using System.Linq;
using System.Diagnostics.Contracts;
/// <summary>
/// Extensions for Tuples
/// </summary>
public static partial class TupleExtensions
{
public static long Sum<T1>(this Tuple<T1> value, Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return func(value.Item1);
}
public static long Sum<T1, T2>(this Tuple<T1, T2> value, Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return (from v in value select func(v)).Sum();
}
public static long Sum<T1, T2, T3>(this Tuple<T1, T2, T3> value, Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return (from v in value select func(v)).Sum();
}
public static long Sum<T1, T2, T3, T4>(this Tuple<T1, T2, T3, T4> value, Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return (from v in value select func(v)).Sum();
}
public static long Sum<T1, T2, T3, T4, T5>(this Tuple<T1, T2, T3, T4, T5> value, Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return (from v in value select func(v)).Sum();
}
public static long Sum<T1, T2, T3, T4, T5, T6>(this Tuple<T1, T2, T3, T4, T5, T6> value, Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return (from v in value select func(v)).Sum();
}
public static long Sum<T1, T2, T3, T4, T5, T6, T7>(this Tuple<T1, T2, T3, T4, T5, T6, T7> value,
Func<object, long> func)
{
Contract.Requires<ArgumentNullException>(value != null);
Contract.Requires<ArgumentNullException>(func != null);
return (from v in value select func(v)).Sum();
}
} | 34.852459 | 115 | 0.680621 | [
"MIT"
] | nicenemo/Noaber | Noaber/TupleExtensions/TupleExtensions.SumOfLong.cs | 2,128 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaseGeometryYVP.GeomObjects;
namespace StepExtractor.EntityModels
{
public class CartesianPoint : Point3D, IEntityModel
{
/// <summary>
/// Название сущности в STEP файле
/// </summary>
public const string NAME = "CARTESIAN_POINT";
/// <summary>
/// Свойство, реализуемое из интерфейса IEntityModel, возвращающее название сущности
/// </summary>
public string StepName
{
get { return NAME; }
}
/// <summary>
/// Имя сущности
/// </summary>
public string Name { get; set; }
}
}
| 23.83871 | 92 | 0.602165 | [
"Apache-2.0"
] | iHandy/STEPOperations | StepExtractor/StepExtractor/EntityModels/CartesianPoint.cs | 833 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* NPOI HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System;
using System.Text;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
namespace NumberFormatInXls
{
class Program
{
static void Main(string[] args)
{
InitializeWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("new sheet");
//increase the width of Column A
sheet.SetColumnWidth(0, 5000);
//create the format instance
IDataFormat format = hssfworkbook.CreateDataFormat();
// Create a row and put some cells in it. Rows are 0 based.
ICell cell = sheet.CreateRow(0).CreateCell(0);
//set value for the cell
cell.SetCellValue(1.2);
//number format with 2 digits after the decimal point - "1.20"
ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
cell.CellStyle = cellStyle;
//RMB currency format with comma - "¥20,000"
ICell cell2 = sheet.CreateRow(1).CreateCell(0);
cell2.SetCellValue(20000);
ICellStyle cellStyle2 = hssfworkbook.CreateCellStyle();
cellStyle2.DataFormat = format.GetFormat("¥#,##0");
cell2.CellStyle = cellStyle2;
//scentific number format - "3.15E+00"
ICell cell3 = sheet.CreateRow(2).CreateCell(0);
cell3.SetCellValue(3.151234);
ICellStyle cellStyle3 = hssfworkbook.CreateCellStyle();
cellStyle3.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");
cell3.CellStyle = cellStyle3;
//percent format, 2 digits after the decimal point - "99.33%"
ICell cell4 = sheet.CreateRow(3).CreateCell(0);
cell4.SetCellValue(0.99333);
ICellStyle cellStyle4 = hssfworkbook.CreateCellStyle();
cellStyle4.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");
cell4.CellStyle = cellStyle4;
//phone number format - "021-65881234"
ICell cell5 = sheet.CreateRow(4).CreateCell(0);
cell5.SetCellValue( 02165881234);
ICellStyle cellStyle5 = hssfworkbook.CreateCellStyle();
cellStyle5.DataFormat = format.GetFormat("000-00000000");
cell5.CellStyle = cellStyle5;
//Chinese capitalized character number - 壹贰叁 元
ICell cell6 = sheet.CreateRow(5).CreateCell(0);
cell6.SetCellValue(123);
ICellStyle cellStyle6 = hssfworkbook.CreateCellStyle();
cellStyle6.DataFormat = format.GetFormat("[DbNum2][$-804]0 元");
cell6.CellStyle = cellStyle6;
//Chinese date string
ICell cell7 = sheet.CreateRow(6).CreateCell(0);
cell7.SetCellValue(new DateTime(2004,5,6));
ICellStyle cellStyle7 = hssfworkbook.CreateCellStyle();
cellStyle7.DataFormat = format.GetFormat("yyyy年m月d日");
cell7.CellStyle = cellStyle7;
//Chinese date string
ICell cell8 = sheet.CreateRow(7).CreateCell(0);
cell8.SetCellValue(new DateTime(2005, 11, 6));
ICellStyle cellStyle8 = hssfworkbook.CreateCellStyle();
cellStyle8.DataFormat = format.GetFormat("yyyy年m月d日");
cell8.CellStyle = cellStyle8;
WriteToFile();
}
static HSSFWorkbook hssfworkbook;
static void WriteToFile()
{
//Write the stream data of workbook to the root directory
FileStream file = new FileStream(@"test.xls", FileMode.Create);
hssfworkbook.Write(file);
file.Close();
}
static void InitializeWorkbook()
{
hssfworkbook = new HSSFWorkbook();
//create a entry of DocumentSummaryInformation
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
//create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
}
}
}
| 40.5 | 99 | 0.601002 | [
"Apache-2.0"
] | 0xAAE/npoi | examples/hssf/NumberFormatInXls/Program.cs | 5,615 | C# |
using System.Collections.Generic;
using System.IO;
public class ConfigFileFinder
{
public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory, ILogger logger)
{
var files = new List<string>();
var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml");
if (File.Exists(solutionConfigFilePath))
{
files.Add(solutionConfigFilePath);
logger.LogDebug($"Found path to weavers file '{solutionConfigFilePath}'.");
}
var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml");
if (!File.Exists(projectConfigFilePath))
{
throw new WeavingException(
$@"Could not file a FodyWeavers.xml at the project level ({projectConfigFilePath}). Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content:
<Weavers>
<WeaverName/>
</Weavers>
");
}
files.Add(projectConfigFilePath);
logger.LogDebug($"Found path to weavers file '{projectConfigFilePath}'.");
if (files.Count == 0)
{
var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath);
logger.LogDebug($"Could not find path to weavers file. Searched '{pathsSearched}'.");
}
return files;
}
} | 38.025641 | 291 | 0.669589 | [
"MIT"
] | LaudateCorpus1/Fody | Fody/ConfigFileFinder.cs | 1,483 | C# |
using System;
using Newtonsoft.Json;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeToken : StripeObject
{
[JsonProperty("created")]
[JsonConverter(typeof(StripeDateTimeConverter))]
public DateTime? Created { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("used")]
public bool? Used { get; set; }
[JsonProperty("livemode")]
public bool? LiveMode { get; set; }
[JsonProperty("card")]
public StripeCard StripeCard { get; set; }
[JsonProperty("bank_account[id]")]
public string BankAccountId { get; set; }
[JsonProperty("bank_account[object]")]
public string BankAccountObject { get; set; }
[JsonProperty("bank_account[bank_name]")]
public string BankAccountName { get; set; }
[JsonProperty("bank_account[country]")]
public string BankAccountCountry { get; set; }
[JsonProperty("bank_account[currency]")]
public string BankAccountCurrency { get; set; }
[JsonProperty("bank_account[last4]")]
public string BankAccountLast4 { get; set; }
[JsonProperty("bank_account[fingerprint]")]
public string BankAccountFingerprint { get; set; }
[JsonProperty("bank_account[validated]")]
public bool? BankAccountValidated { get; set; }
[JsonProperty("bank_account[verified]")]
public bool? BankAccountVerified { get; set; }
}
} | 26.076923 | 52 | 0.715339 | [
"Apache-2.0"
] | iATN/stripe.net | src/Stripe/Entities/StripeToken.cs | 1,358 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using BJJTrainer.Data;
namespace BJJTrainer.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20161004175901_AddVideoPropertyToDrill")]
partial class AddVideoPropertyToDrill
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("BJJTrainer.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 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")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("BJJTrainer.Models.Category", b =>
{
b.Property<int>("CategoryId")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("CategoryId");
b.ToTable("Categories");
});
modelBuilder.Entity("BJJTrainer.Models.Drill", b =>
{
b.Property<int>("DrillId")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<int>("RoutineId");
b.Property<int>("TechniqueId");
b.Property<int>("Time");
b.Property<string>("Video");
b.HasKey("DrillId");
b.HasIndex("RoutineId");
b.HasIndex("TechniqueId");
b.ToTable("Drills");
});
modelBuilder.Entity("BJJTrainer.Models.Position", b =>
{
b.Property<int>("PositionId")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("PositionId");
b.ToTable("Positions");
});
modelBuilder.Entity("BJJTrainer.Models.Routine", b =>
{
b.Property<int>("RoutineId")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("RoutineId");
b.ToTable("Routines");
});
modelBuilder.Entity("BJJTrainer.Models.Technique", b =>
{
b.Property<int>("TechniqueId")
.ValueGeneratedOnAdd();
b.Property<int>("CategoryId");
b.Property<string>("Name");
b.Property<int>("PositionId");
b.HasKey("TechniqueId");
b.HasIndex("CategoryId");
b.HasIndex("PositionId");
b.ToTable("Techniques");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.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.EntityFrameworkCore.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.EntityFrameworkCore.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.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.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("BJJTrainer.Models.Drill", b =>
{
b.HasOne("BJJTrainer.Models.Routine", "Routine")
.WithMany("Drills")
.HasForeignKey("RoutineId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("BJJTrainer.Models.Technique", "Technique")
.WithMany()
.HasForeignKey("TechniqueId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("BJJTrainer.Models.Technique", b =>
{
b.HasOne("BJJTrainer.Models.Category", "Category")
.WithMany("Techniques")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("BJJTrainer.Models.Position", "Position")
.WithMany("Techniques")
.HasForeignKey("PositionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("BJJTrainer.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("BJJTrainer.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("BJJTrainer.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 33.442368 | 117 | 0.470517 | [
"MIT"
] | blogue/BJJTrainer | src/BJJTrainer/Data/Migrations/20161004175901_AddVideoPropertyToDrill.Designer.cs | 10,737 | C# |
namespace OmniSharp.Mef
{
public interface IRequestHandler
{
}
}
| 11.142857 | 36 | 0.653846 | [
"MIT"
] | 333fred/omnisharp-roslyn | src/OmniSharp.Abstractions/Mef/IRequestHandler.cs | 80 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics.CodeAnalysis;
namespace GreenEnergyHub.TimeSeries.Core.Enumeration
{
public class ExactValueNameComparisonStrategy : IEnumValueNameComparisonStrategy
{
public bool IsEquivalent([NotNull] Enum subjectValue, [NotNull] Enum comparisonValue)
{
return subjectValue.ToString() == comparisonValue.ToString();
}
}
}
| 35.607143 | 93 | 0.738215 | [
"Apache-2.0"
] | Energinet-DataHub/geh-timeseries | source/GreenEnergyHub.TimeSeries/source/GreenEnergyHub.TimeSeries.Core/Enumeration/ExactValueNameComparisonStrategy.cs | 999 | C# |
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using BootstrapBlazor.Components;
using BootstrapBlazor.Shared.Common;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace BootstrapBlazor.Shared.Samples;
/// <summary>
///
/// </summary>
public sealed partial class Layouts
{
[Inject]
[NotNull]
private IStringLocalizer<Menus>? LocalizerMenu { get; set; }
[Inject]
[NotNull]
private IStringLocalizer<Layouts>? Localizer { get; set; }
private IEnumerable<MenuItem>? IconSideMenuItems { get; set; }
/// <summary>
/// OnInitializedAsync 方法
/// </summary>
/// <returns></returns>
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
IconSideMenuItems = await MenusDataGerator.GetIconSideMenuItemsAsync(LocalizerMenu);
}
private IEnumerable<AttributeItem> GetAttributes() => new AttributeItem[]
{
// TODO: 移动到数据库中
new AttributeItem() {
Name = "Header",
Description = Localizer["Desc1"],
Type = "RenderFragment",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "Side",
Description = Localizer["Desc2"],
Type = "RenderFragment",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "SideWidth",
Description = Localizer["Desc3"],
Type = "string",
ValueList = " — ",
DefaultValue = "300px"
},
new AttributeItem() {
Name = "Main",
Description = Localizer["Desc4"],
Type = "RenderFragment",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "Footer",
Description = Localizer["Desc2"],
Type = "RenderFragment",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "Menus",
Description = Localizer["Desc6"],
Type = "IEnumerable<MenuItem>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "IsFullSide",
Description = Localizer["Desc7"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "IsPage",
Description = Localizer["Desc8"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "IsFixedFooter",
Description = Localizer["Desc9"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "IsFixedHeader",
Description = Localizer["Desc10"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "ShowCollapseBar",
Description = Localizer["Desc11"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "ShowFooter",
Description = Localizer["Desc12"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "ShowGotoTop",
Description = Localizer["Desc13"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "UseTabSet",
Description = Localizer["Desc14"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem() {
Name = "AdditionalAssemblies",
Description = Localizer["Desc15"],
Type = "IEnumerable<Assembly>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "OnCollapsed",
Description = Localizer["Desc16"],
Type = "Func<bool, Task>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "OnClickMenu",
Description = Localizer["Desc17"],
Type = "Func<bool, MenuItem>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "TabDefaultUrl",
Description = Localizer["TabDefaultUrl"],
Type = "string?",
ValueList = " — ",
DefaultValue = " — "
}
};
}
| 33.668605 | 111 | 0.458125 | [
"Apache-2.0"
] | O-o0O/BootstrapBlazor | src/BootstrapBlazor.Shared/Samples/Layouts.razor.cs | 5,849 | C# |
using System;
using System.IO;
using SmartVideo.Transport;
namespace SmartVideoHub
{
public class SmartVideoLocalServiceHandler : SmartVideoLocalService.Iface
{
public bool uploadMedia(MediaStruct media)
{
try {
Console.WriteLine("Receiving media from : {0}, size : {1}",media.DeviceId, media.Data.Length);
MediaQueue.Instance.Enqueue(media);
return true;
} catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return false;
}
}
}
| 26.043478 | 110 | 0.564274 | [
"MIT"
] | zhen08/SmartHomeV1 | SmartVideo/SmartVideoHub/SmartVideoLocalServiceHandler.cs | 601 | 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.Lightsail;
using Amazon.Lightsail.Model;
namespace Amazon.PowerShell.Cmdlets.LS
{
/// <summary>
/// Updates an existing Amazon Lightsail bucket.
///
///
/// <para>
/// Use this action to update the configuration of an existing bucket, such as versioning,
/// public accessibility, and the AWS accounts that can access the bucket.
/// </para>
/// </summary>
[Cmdlet("Update", "LSBucket", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.Lightsail.Model.UpdateBucketResponse")]
[AWSCmdlet("Calls the Amazon Lightsail UpdateBucket API operation.", Operation = new[] {"UpdateBucket"}, SelectReturnType = typeof(Amazon.Lightsail.Model.UpdateBucketResponse))]
[AWSCmdletOutput("Amazon.Lightsail.Model.UpdateBucketResponse",
"This cmdlet returns an Amazon.Lightsail.Model.UpdateBucketResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class UpdateLSBucketCmdlet : AmazonLightsailClientCmdlet, IExecutor
{
#region Parameter AccessRules_AllowPublicOverride
/// <summary>
/// <para>
/// <para>A Boolean value that indicates whether the access control list (ACL) permissions that
/// are applied to individual objects override the <code>getObject</code> option that
/// is currently specified.</para><para>When this is true, you can use the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectAcl.html">PutObjectAcl</a>
/// Amazon S3 API action to set individual objects to public (read-only) using the <code>public-read</code>
/// ACL, or to private using the <code>private</code> ACL.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("AccessRules_AllowPublicOverrides")]
public System.Boolean? AccessRules_AllowPublicOverride { get; set; }
#endregion
#region Parameter BucketName
/// <summary>
/// <para>
/// <para>The name of the bucket to update.</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 BucketName { get; set; }
#endregion
#region Parameter AccessRules_GetObject
/// <summary>
/// <para>
/// <para>Specifies the anonymous access to all objects in a bucket.</para><para>The following options can be specified:</para><ul><li><para><code>public</code> - Sets all objects in the bucket to public (read-only), making
/// them readable by anyone in the world.</para><para>If the <code>getObject</code> value is set to <code>public</code>, then all objects
/// in the bucket default to public regardless of the <code>allowPublicOverrides</code>
/// value.</para></li><li><para><code>private</code> - Sets all objects in the bucket to private, making them readable
/// only by you or anyone you give access to.</para><para>If the <code>getObject</code> value is set to <code>private</code>, and the <code>allowPublicOverrides</code>
/// value is set to <code>true</code>, then all objects in the bucket default to private
/// unless they are configured with a <code>public-read</code> ACL. Individual objects
/// with a <code>public-read</code> ACL are readable by anyone in the world.</para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.Lightsail.AccessType")]
public Amazon.Lightsail.AccessType AccessRules_GetObject { get; set; }
#endregion
#region Parameter ReadonlyAccessAccount
/// <summary>
/// <para>
/// <para>An array of strings to specify the AWS account IDs that can access the bucket.</para><para>You can give a maximum of 10 AWS accounts access to a bucket.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ReadonlyAccessAccounts")]
public System.String[] ReadonlyAccessAccount { get; set; }
#endregion
#region Parameter Versioning
/// <summary>
/// <para>
/// <para>Specifies whether to enable or suspend versioning of objects in the bucket.</para><para>The following options can be specified:</para><ul><li><para><code>Enabled</code> - Enables versioning of objects in the specified bucket.</para></li><li><para><code>Suspended</code> - Suspends versioning of objects in the specified bucket.
/// Existing object versions are retained.</para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String Versioning { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Lightsail.Model.UpdateBucketResponse).
/// Specifying the name of a property of type Amazon.Lightsail.Model.UpdateBucketResponse 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; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the BucketName parameter.
/// The -PassThru parameter is deprecated, use -Select '^BucketName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^BucketName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.BucketName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-LSBucket (UpdateBucket)"))
{
return;
}
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.Lightsail.Model.UpdateBucketResponse, UpdateLSBucketCmdlet>(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.BucketName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.AccessRules_AllowPublicOverride = this.AccessRules_AllowPublicOverride;
context.AccessRules_GetObject = this.AccessRules_GetObject;
context.BucketName = this.BucketName;
#if MODULAR
if (this.BucketName == null && ParameterWasBound(nameof(this.BucketName)))
{
WriteWarning("You are passing $null as a value for parameter BucketName 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
if (this.ReadonlyAccessAccount != null)
{
context.ReadonlyAccessAccount = new List<System.String>(this.ReadonlyAccessAccount);
}
context.Versioning = this.Versioning;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.Lightsail.Model.UpdateBucketRequest();
// populate AccessRules
var requestAccessRulesIsNull = true;
request.AccessRules = new Amazon.Lightsail.Model.AccessRules();
System.Boolean? requestAccessRules_accessRules_AllowPublicOverride = null;
if (cmdletContext.AccessRules_AllowPublicOverride != null)
{
requestAccessRules_accessRules_AllowPublicOverride = cmdletContext.AccessRules_AllowPublicOverride.Value;
}
if (requestAccessRules_accessRules_AllowPublicOverride != null)
{
request.AccessRules.AllowPublicOverrides = requestAccessRules_accessRules_AllowPublicOverride.Value;
requestAccessRulesIsNull = false;
}
Amazon.Lightsail.AccessType requestAccessRules_accessRules_GetObject = null;
if (cmdletContext.AccessRules_GetObject != null)
{
requestAccessRules_accessRules_GetObject = cmdletContext.AccessRules_GetObject;
}
if (requestAccessRules_accessRules_GetObject != null)
{
request.AccessRules.GetObject = requestAccessRules_accessRules_GetObject;
requestAccessRulesIsNull = false;
}
// determine if request.AccessRules should be set to null
if (requestAccessRulesIsNull)
{
request.AccessRules = null;
}
if (cmdletContext.BucketName != null)
{
request.BucketName = cmdletContext.BucketName;
}
if (cmdletContext.ReadonlyAccessAccount != null)
{
request.ReadonlyAccessAccounts = cmdletContext.ReadonlyAccessAccount;
}
if (cmdletContext.Versioning != null)
{
request.Versioning = cmdletContext.Versioning;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Lightsail.Model.UpdateBucketResponse CallAWSServiceOperation(IAmazonLightsail client, Amazon.Lightsail.Model.UpdateBucketRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Lightsail", "UpdateBucket");
try
{
#if DESKTOP
return client.UpdateBucket(request);
#elif CORECLR
return client.UpdateBucketAsync(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.Boolean? AccessRules_AllowPublicOverride { get; set; }
public Amazon.Lightsail.AccessType AccessRules_GetObject { get; set; }
public System.String BucketName { get; set; }
public List<System.String> ReadonlyAccessAccount { get; set; }
public System.String Versioning { get; set; }
public System.Func<Amazon.Lightsail.Model.UpdateBucketResponse, UpdateLSBucketCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 49.055556 | 345 | 0.623757 | [
"Apache-2.0"
] | aws/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/Lightsail/Basic/Update-LSBucket-Cmdlet.cs | 15,894 | 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Mvc.Internal
{
/// <summary>
/// Default implementation of <see cref="IActionDescriptorCollectionProvider"/>.
/// </summary>
public class ActionDescriptorCollectionProvider : IActionDescriptorCollectionProvider
{
private readonly IActionDescriptorProvider[] _actionDescriptorProviders;
private readonly IActionDescriptorChangeProvider[] _actionDescriptorChangeProviders;
private ActionDescriptorCollection _collection;
private int _version = -1;
/// <summary>
/// Initializes a new instance of the <see cref="ActionDescriptorCollectionProvider" /> class.
/// </summary>
/// <param name="actionDescriptorProviders">The sequence of <see cref="IActionDescriptorProvider"/>.</param>
/// <param name="actionDescriptorChangeProviders">The sequence of <see cref="IActionDescriptorChangeProvider"/>.</param>
public ActionDescriptorCollectionProvider(
IEnumerable<IActionDescriptorProvider> actionDescriptorProviders,
IEnumerable<IActionDescriptorChangeProvider> actionDescriptorChangeProviders)
{
_actionDescriptorProviders = actionDescriptorProviders
.OrderBy(p => p.Order)
.ToArray();
_actionDescriptorChangeProviders = actionDescriptorChangeProviders.ToArray();
ChangeToken.OnChange(
GetCompositeChangeToken,
UpdateCollection);
}
private IChangeToken GetCompositeChangeToken()
{
if (_actionDescriptorChangeProviders.Length == 1)
{
return _actionDescriptorChangeProviders[0].GetChangeToken();
}
var changeTokens = new IChangeToken[_actionDescriptorChangeProviders.Length];
for (var i = 0; i < _actionDescriptorChangeProviders.Length; i++)
{
changeTokens[i] = _actionDescriptorChangeProviders[i].GetChangeToken();
}
return new CompositeChangeToken(changeTokens);
}
/// <summary>
/// Returns a cached collection of <see cref="ActionDescriptor" />.
/// </summary>
public ActionDescriptorCollection ActionDescriptors
{
get
{
if (_collection == null)
{
UpdateCollection();
}
return _collection;
}
}
private void UpdateCollection()
{
var context = new ActionDescriptorProviderContext();
for (var i = 0; i < _actionDescriptorProviders.Length; i++)
{
_actionDescriptorProviders[i].OnProvidersExecuting(context);
}
for (var i = _actionDescriptorProviders.Length - 1; i >= 0; i--)
{
_actionDescriptorProviders[i].OnProvidersExecuted(context);
}
_collection = new ActionDescriptorCollection(
new ReadOnlyCollection<ActionDescriptor>(context.Results),
Interlocked.Increment(ref _version));
}
}
} | 37.715789 | 128 | 0.63885 | [
"Apache-2.0"
] | Elfocrash/Mvc | src/Microsoft.AspNetCore.Mvc.Core/Internal/ActionDescriptorCollectionProvider.cs | 3,583 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OAuth2Manager.Common;
namespace OAuth2Manager.Core.Methods.TwoLegged
{
public class OAuth2ResourceOwnerPassword : OAuth2Base
{
private string userName;
private string password;
private string clientSecret;
public OAuth2ResourceOwnerPassword(string clientId, string clientSecret, string redirectUrl, string scope, string authorizationUrl, string userName, string password) :
base(clientId, redirectUrl, scope, authorizationUrl)
{
this.userName = userName;
this.password = password;
this.clientSecret = clientSecret;
}
public virtual async Task<bool> InvokeUserAuthorization()
{
//initialize the underlying OAuthorizer
InitAuthorizer(clientSecret);
base.OAuthState = OAuthState.INITIALIZED;
var parameters = new List<KeyValuePair<string, string>>(capacity: 6)
{
new KeyValuePair<string,string>(OAuthConstants.USERNAME, this.userName),
new KeyValuePair<string,string>(OAuthConstants.PASSWORD, this.password),
new KeyValuePair<string,string>(OAuthConstants.CLIENT_SECRET, this.clientSecret)
};
var accessTokenUrl = Authorizer.BuildAuthorizeUrl(AuthorizationUrl, OAuthConstants.GRANT_TYPE_PASSWORD, parameters);
Uri authUri = new Uri(accessTokenUrl);
OAuthState = OAuthState.ACCESS_TOKEN_WAIT;
try
{
var result = await Authorizer.GetAccessTokenAsync(accessTokenUrl);
if (result != null)
{
OAuthState = OAuthState.SUCCEEDED;
AccessToken = result.Token;
return true;
}
else
{
OAuthState = OAuthState.FAILED;
return false;
}
}
catch (Exception)
{
OAuthState = OAuthState.FAILED;
throw;
}
}
}
}
| 34.984375 | 175 | 0.584636 | [
"MIT"
] | IAmWaseem/oauth2-xamarin | Core/Methods/TwoLegged/OAuth2ResourceOwnerPassword.cs | 2,241 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Iot;
using Aliyun.Acs.Iot.Transform;
using Aliyun.Acs.Iot.Transform.V20190730;
namespace Aliyun.Acs.Iot.Model.V20190730
{
public class GetPoolFunctionsByIdListForTmallGenieRequest : RpcAcsRequest<GetPoolFunctionsByIdListForTmallGenieResponse>
{
public GetPoolFunctionsByIdListForTmallGenieRequest()
: base("Iot", "2019-07-30", "GetPoolFunctionsByIdListForTmallGenie")
{
}
private List<long?> tmallFunctionIdLists = new List<long?>(){ };
private string thingTemplateKey;
private List<string> identifierLists = new List<string>(){ };
private string iotInstanceId;
private string tmallFunctionType;
private string apiProduct;
private string apiRevision;
public List<long?> TmallFunctionIdLists
{
get
{
return tmallFunctionIdLists;
}
set
{
tmallFunctionIdLists = value;
for (int i = 0; i < tmallFunctionIdLists.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"TmallFunctionIdList." + (i + 1) , tmallFunctionIdLists[i]);
}
}
}
public string ThingTemplateKey
{
get
{
return thingTemplateKey;
}
set
{
thingTemplateKey = value;
DictionaryUtil.Add(QueryParameters, "ThingTemplateKey", value);
}
}
public List<string> IdentifierLists
{
get
{
return identifierLists;
}
set
{
identifierLists = value;
for (int i = 0; i < identifierLists.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"IdentifierList." + (i + 1) , identifierLists[i]);
}
}
}
public string IotInstanceId
{
get
{
return iotInstanceId;
}
set
{
iotInstanceId = value;
DictionaryUtil.Add(QueryParameters, "IotInstanceId", value);
}
}
public string TmallFunctionType
{
get
{
return tmallFunctionType;
}
set
{
tmallFunctionType = value;
DictionaryUtil.Add(QueryParameters, "TmallFunctionType", value);
}
}
public string ApiProduct
{
get
{
return apiProduct;
}
set
{
apiProduct = value;
DictionaryUtil.Add(BodyParameters, "ApiProduct", value);
}
}
public string ApiRevision
{
get
{
return apiRevision;
}
set
{
apiRevision = value;
DictionaryUtil.Add(BodyParameters, "ApiRevision", value);
}
}
public override GetPoolFunctionsByIdListForTmallGenieResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return GetPoolFunctionsByIdListForTmallGenieResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 23.248408 | 124 | 0.669863 | [
"Apache-2.0"
] | sdk-team/aliyun-openapi-net-sdk | aliyun-net-sdk-iot/Iot/Model/V20190730/GetPoolFunctionsByIdListForTmallGenieRequest.cs | 3,650 | C# |
using io.odysz.anclient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using TreeViewFileExplorer.ShellClasses;
namespace TreeViewFileExplorer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private SessionClient client;
public MainWindow(SessionClient client)
{
InitializeComponent();
InitializeFileSystemObjects();
this.client = client;
}
#region Events
private void FileSystemObject_AfterExplore(object sender, EventArgs e)
{
Cursor = Cursors.Arrow;
}
private void FileSystemObject_BeforeExplore(object sender, EventArgs e)
{
Cursor = Cursors.Wait;
}
#endregion
#region Methods
private void InitializeFileSystemObjects()
{
var drives = DriveInfo.GetDrives();
DriveInfo
.GetDrives()
.ToList()
.ForEach(drive =>
{
var fileSystemObject = new FileSystemObjectInfo(drive, ref filelist);
fileSystemObject.BeforeExplore += FileSystemObject_BeforeExplore;
fileSystemObject.AfterExplore += FileSystemObject_AfterExplore;
treeView.Items.Add(fileSystemObject);
});
PreSelect(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
}
private void PreSelect(string path)
{
if (!Directory.Exists(path))
{
return;
}
var driveFileSystemObjectInfo = GetDriveFileSystemObjectInfo(path);
driveFileSystemObjectInfo.IsExpanded = true;
PreSelect(driveFileSystemObjectInfo, path);
}
private void PreSelect(FileSystemObjectInfo fileSystemObjectInfo, string path)
{
foreach (var childFileSystemObjectInfo in fileSystemObjectInfo.Children)
{
var isParentPath = IsParentPath(path, childFileSystemObjectInfo.FileSystemInfo.FullName);
if (isParentPath)
{
if (string.Equals(childFileSystemObjectInfo.FileSystemInfo.FullName, path))
{
/* We found the item for pre-selection */
}
else
{
childFileSystemObjectInfo.IsExpanded = true;
PreSelect(childFileSystemObjectInfo, path);
}
}
//else if (IsRepoDir(childFileSystemObjectInfo))
//{
// continue;
//}
}
}
#endregion
#region Helpers
private FileSystemObjectInfo GetDriveFileSystemObjectInfo(string path)
{
var directory = new DirectoryInfo(path);
var drive = DriveInfo
.GetDrives()
.Where(d => d.RootDirectory.FullName == directory.Root.FullName)
.FirstOrDefault();
return GetDriveFileSystemObjectInfo(drive);
}
private FileSystemObjectInfo GetDriveFileSystemObjectInfo(DriveInfo drive)
{
foreach (var fso in treeView.Items.OfType<FileSystemObjectInfo>())
{
if (fso.FileSystemInfo.FullName == drive.RootDirectory.FullName)
{
return fso;
}
}
return null;
}
private bool IsParentPath(string path, string targetPath)
{
return path.StartsWith(targetPath);
}
private void toUpload(object sender, RoutedEventArgs e)
{
List<SyncObjectInfo> bufUpload = new List<SyncObjectInfo>();
foreach (SyncObjectInfo file in filelist.Items)
bufUpload.Add(file);
}
#endregion
}
}
| 31.393939 | 105 | 0.552365 | [
"Apache-2.0"
] | odys-z/jclient | examples/example.cs/album-wpf/album-sync/MainWindow.xaml.cs | 4,146 | C# |
// -----------------------------------------------------------------------
// <copyright file="ContinuousFuture.cs" company="">
// Copyright 2013 Alexander Soffronow Pagonidis
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using ProtoBuf;
namespace QDMS
{
/// <summary>
/// Represents a composite instrument, which strings together futures of different maturities to create a continuous one
/// </summary>
[ProtoContract]
public class ContinuousFuture : ICloneable
{
/// <summary>
///
/// </summary>
public ContinuousFuture()
{
UseJan = true;
UseFeb = true;
UseMar = true;
UseApr = true;
UseMay = true;
UseJun = true;
UseJul = true;
UseAug = true;
UseSep = true;
UseOct = true;
UseNov = true;
UseDec = true;
Month = 1;
}
/// <summary>
/// Continuous future ID
/// </summary>
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[ProtoMember(1)]
public int ID { get; set; }
/// <summary>
/// Instrument ID
/// </summary>
[ProtoMember(2)]
public int InstrumentID { get; set; }
/// <summary>
/// Instrument
/// </summary>
public virtual Instrument Instrument { get; set; }
/// <summary>
/// Underlying symbol ID
/// </summary>
[ProtoMember(3)]
public int UnderlyingSymbolID { get; set; }
/// <summary>
/// The underlying symbol that the continuous future is based on.
/// </summary>
[ProtoMember(20)]
public virtual UnderlyingSymbol UnderlyingSymbol { get; set; }
/// <summary>
/// Which contract month to use to construct the continuous prices.
/// For example, Month = 1 uses the "front" future, Month = 2 uses the next one and so forth.
/// </summary>
[ProtoMember(4)]
public int Month { get; set; }
/// <summary>
/// What criteria should be used when determining whether to roll over to the next contract.
/// </summary>
[ProtoMember(5)]
public ContinuousFuturesRolloverType RolloverType { get; set; }
/// <summary>
/// Number of days that the criteria will use to determine rollover.
/// </summary>
[ProtoMember(6)]
public int RolloverDays { get; set; }
/// <summary>
/// How to adjust prices from one contract to the next
/// </summary>
[ProtoMember(7)]
public ContinuousFuturesAdjustmentMode AdjustmentMode { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(8, IsRequired = true)]
public bool UseJan { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(9, IsRequired = true)]
public bool UseFeb { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(10, IsRequired = true)]
public bool UseMar { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(11, IsRequired = true)]
public bool UseApr { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(12, IsRequired = true)]
public bool UseMay { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(13, IsRequired = true)]
public bool UseJun { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(14, IsRequired = true)]
public bool UseJul { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(15, IsRequired = true)]
public bool UseAug { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(16, IsRequired = true)]
public bool UseSep { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(17, IsRequired = true)]
public bool UseOct { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(18, IsRequired = true)]
public bool UseNov { get; set; }
/// <summary>
///
/// </summary>
[ProtoMember(19, IsRequired = true)]
public bool UseDec { get; set; }
/// <summary>
///
/// </summary>
/// <param name="month"></param>
/// <returns></returns>
public bool MonthIsUsed(int month)
{
switch (month)
{
case 1:
return UseJan;
case 2:
return UseFeb;
case 3:
return UseMar;
case 4:
return UseApr;
case 5:
return UseMay;
case 6:
return UseJun;
case 7:
return UseJul;
case 8:
return UseAug;
case 9:
return UseSep;
case 10:
return UseOct;
case 11:
return UseNov;
case 12:
return UseDec;
default:
return false;
}
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
var clone = new ContinuousFuture
{
ID = ID,
InstrumentID = InstrumentID,
Instrument = Instrument,
UnderlyingSymbol = UnderlyingSymbol,
UnderlyingSymbolID = UnderlyingSymbolID,
Month = Month,
RolloverType = RolloverType,
RolloverDays = RolloverDays,
AdjustmentMode = AdjustmentMode,
UseJan = UseJan,
UseFeb = UseFeb,
UseMar = UseMar,
UseApr = UseApr,
UseMay = UseMay,
UseJun = UseJun,
UseJul = UseJul,
UseAug = UseAug,
UseSep = UseSep,
UseOct = UseOct,
UseNov = UseNov,
UseDec = UseDec
};
return clone;
}
}
}
| 27.991803 | 124 | 0.454612 | [
"BSD-3-Clause"
] | santoch/qdms | QDMS/EntityModels/ContinuousFuture.cs | 6,832 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
////REVIEW: switch to something that doesn't require the backing store to be an actual array?
//// (maybe switch m_Array to an InlinedArray and extend InlinedArray to allow having three configs:
//// 1. firstValue only, 2. firstValue + additionalValues, 3. everything in additionalValues)
namespace UnityEngine.InputSystem.Utilities
{
/// <summary>
/// Read-only access to an array or to a slice of an array.
/// </summary>
/// <typeparam name="TValue">Type of values stored in the array.</typeparam>
/// <remarks>
/// The purpose of this struct is to allow exposing internal arrays directly such that no
/// boxing and no going through interfaces is required but at the same time not allowing
/// the internal arrays to be modified.
///
/// It differs from <c>ReadOnlySpan<T></c> in that it can be stored on the heap and differs
/// from <c>ReadOnlyCollection<T></c> in that it supports slices directly without needing
/// an intermediate object representing the slice.
///
/// Note that in most cases, the ReadOnlyArray instance should be treated as a <em>temporary</em>.
/// The actual array referred to by a ReadOnlyArray instance is usually owned and probably mutated
/// by another piece of code. When that code makes changes to the array, the ReadOnlyArray
/// instance will not get updated.
/// </remarks>
public struct ReadOnlyArray<TValue> : IReadOnlyList<TValue>
{
internal TValue[] m_Array;
internal int m_StartIndex;
internal int m_Length;
/// <summary>
/// Construct a read-only array covering all of the given array.
/// </summary>
/// <param name="array">Array to index.</param>
public ReadOnlyArray(TValue[] array)
{
m_Array = array;
m_StartIndex = 0;
m_Length = array?.Length ?? 0;
}
/// <summary>
/// Construct a read-only array that covers only the given slice of <paramref name="array"/>.
/// </summary>
/// <param name="array">Array to index.</param>
/// <param name="index">Index at which to start indexing <paramref name="array"/>. The given element
/// becomes index #0 for the read-only array.</param>
/// <param name="length">Length of the slice to index from <paramref name="array"/>.</param>
public ReadOnlyArray(TValue[] array, int index, int length)
{
m_Array = array;
m_StartIndex = index;
m_Length = length;
}
/// <summary>
/// Convert to array.
/// </summary>
/// <returns>A new array containing a copy of the contents of the read-only array.</returns>
public TValue[] ToArray()
{
var result = new TValue[m_Length];
if (m_Length > 0)
Array.Copy(m_Array, m_StartIndex, result, 0, m_Length);
return result;
}
public int IndexOf(Predicate<TValue> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
for (var i = 0; i < m_Length; ++i)
if (predicate(m_Array[m_StartIndex + i]))
return i;
return -1;
}
/// <inheritdoc />
public IEnumerator<TValue> GetEnumerator()
{
return new Enumerator<TValue>(m_Array, m_StartIndex, m_Length);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "`ToXXX` message only really makes sense as static, which is not recommended for generic types.")]
public static implicit operator ReadOnlyArray<TValue>(TValue[] array)
{
return new ReadOnlyArray<TValue>(array);
}
/// <summary>
/// Number of elements in the array.
/// </summary>
public int Count => m_Length;
/// <summary>
/// Return the element at the given index.
/// </summary>
/// <param name="index">Index into the array.</param>
/// <exception cref="IndexOutOfRangeException"><paramref name="index"/> is less than 0 or greater than <see cref="Count"/>.</exception>
/// <exception cref="InvalidOperationException"></exception>
public TValue this[int index]
{
get
{
if (index < 0 || index >= m_Length)
throw new ArgumentOutOfRangeException(nameof(index));
// We allow array to be null as we are patching up ReadOnlyArrays in a separate
// path in several places.
if (m_Array == null)
throw new InvalidOperationException();
return m_Array[m_StartIndex + index];
}
}
internal class Enumerator<T> : IEnumerator<T>
{
private readonly T[] m_Array;
private readonly int m_IndexStart;
private readonly int m_IndexEnd;
private int m_Index;
public Enumerator(T[] array, int index, int length)
{
m_Array = array;
m_IndexStart = index - 1; // First call to MoveNext() moves us to first valid index.
m_IndexEnd = index + length;
m_Index = m_IndexStart;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (m_Index < m_IndexEnd)
++m_Index;
return (m_Index != m_IndexEnd);
}
public void Reset()
{
m_Index = m_IndexStart;
}
public T Current
{
get
{
if (m_Index == m_IndexEnd)
throw new InvalidOperationException("Iterated beyond end");
return m_Array[m_Index];
}
}
object IEnumerator.Current => Current;
}
}
/// <summary>
/// Extension methods to help with <see cref="ReadOnlyArrayExtensions"/> contents.
/// </summary>
public static class ReadOnlyArrayExtensions
{
public static bool Contains<TValue>(this ReadOnlyArray<TValue> array, TValue value)
where TValue : IComparable<TValue>
{
for (var i = 0; i < array.m_Length; ++i)
if (array.m_Array[array.m_StartIndex + i].CompareTo(value) == 0)
return true;
return false;
}
public static bool ContainsReference<TValue>(this ReadOnlyArray<TValue> array, TValue value)
where TValue : class
{
return IndexOfReference(array, value) != -1;
}
public static int IndexOfReference<TValue>(this ReadOnlyArray<TValue> array, TValue value)
where TValue : class
{
for (var i = 0; i < array.m_Length; ++i)
if (ReferenceEquals(array.m_Array[array.m_StartIndex + i], value))
return i;
return -1;
}
}
}
| 36.945274 | 237 | 0.566927 | [
"Unlicense"
] | 23SAMY23/Meet-and-Greet-MR | Meet & Greet MR (AR)/Library/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/Utilities/ReadOnlyArray.cs | 7,426 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using AtCoder;
public static class SuffixArrayLong
{
public static long Calc(int n)
{
long ans = 0;
n >>= 4;
var s = new long[n];
for (int i = 0; i < s.Length; i++)
s[i] = long.MaxValue + (i % 2 == 0 ? i : -i);
var sa = StringLib.SuffixArray(s);
var lcp = StringLib.LCPArray(s, sa);
ans = lcp[0];
return ans;
}
}
| 23.076923 | 57 | 0.6 | [
"CC0-1.0"
] | kzrnm/ac-library-csharp | Test/AtCoderLibrary.Benchmark/Benchmark/SuffixArrayLong.cs | 602 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Internal;
using System.Data.Entity.ModelConfiguration.Utilities;
using System.Data.Entity.Utilities;
using System.Data.Entity.Validation;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that
/// it can be used to query from a database and group together changes that will then be written
/// back to the store as a unit.
/// DbContext is conceptually similar to ObjectContext.
/// </summary>
/// <remarks>
/// <para>
/// DbContext is usually used with a derived type that contains <see cref="DbSet{TEntity}" /> properties for
/// the root entities of the model. These sets are automatically initialized when the
/// instance of the derived class is created. This behavior can be modified by applying the
/// <see cref="SuppressDbSetInitializationAttribute" /> attribute to either the entire derived context
/// class, or to individual properties on the class.
/// </para>
/// <para>
/// The Entity Data Model backing the context can be specified in several ways.
/// </para>
/// <para>
/// When using the Code First
/// approach, the <see cref="DbSet{TEntity}" /> properties on the derived context are used to build a model
/// by convention. The protected OnModelCreating method can be overridden to tweak this model. More
/// control over the model used for the Model First approach can be obtained by creating a <see cref="DbCompiledModel" />
/// explicitly from a <see cref="DbModelBuilder" /> and passing this model to one of the DbContext constructors.
/// </para>
/// <para>
/// When using the Database First or Model First approach the Entity Data Model can be created using the
/// Entity Designer (or manually through creation of an EDMX file) and then this model can be specified using
/// entity connection string or an <see cref="System.Data.Entity.Core.EntityClient.EntityConnection" /> object.
/// The connection to the database (including the name of the database) can be specified in several ways.
/// </para>
/// <para>
/// If the parameterless DbContext constructor is called from a derived context, then the name of the derived context
/// is used to find a connection string in the app.config or web.config file. If no connection string is found, then
/// the name is passed to the DefaultConnectionFactory registered on the <see cref="Entity.Database" /> class. The connection
/// factory then uses the context name as the database name in a default connection string. (This default connection
/// string points to (localdb)\MSSQLLocalDB unless a different DefaultConnectionFactory is registered.)
/// </para>
/// <para>
/// Instead of using the derived context name, the connection/database name can also be specified explicitly by
/// passing the name to one of the DbContext constructors that takes a string. The name can also be passed in
/// the form "name=myname", in which case the name must be found in the config file or an exception will be thrown.
/// </para>
/// <para>
/// Note that the connection found in the app.config or web.config file can be a normal database connection
/// string (not a special Entity Framework connection string) in which case the DbContext will use Code First.
/// However, if the connection found in the config file is a special Entity Framework connection string, then the
/// DbContext will use Database/Model First and the model specified in the connection string will be used.
/// </para>
/// <para>
/// An existing or explicitly created DbConnection can also be used instead of the database/connection name.
/// </para>
/// <para>
/// A <see cref="DbModelBuilderVersionAttribute" /> can be applied to a class derived from DbContext to set the
/// version of conventions used by the context when it creates a model. If no attribute is applied then the
/// latest version of conventions will be used.
/// </para>
/// </remarks>
public class DbContext : IDisposable, IObjectContextAdapter
{
#region Construction and fields
// Handles lazy creation of an underlying ObjectContext
private InternalContext _internalContext;
private Database _database;
/// <summary>
/// Constructs a new context instance using conventions to create the name of the database to
/// which a connection will be made. The by-convention name is the full name (namespace + class name)
/// of the derived context class.
/// See the class remarks for how this is used to create a connection.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected DbContext()
{
InitializeLazyInternalContext(new LazyInternalConnection(this, GetType().DatabaseName()));
}
/// <summary>
/// Constructs a new context instance using conventions to create the name of the database to
/// which a connection will be made, and initializes it from the given model.
/// The by-convention name is the full name (namespace + class name) of the derived context class.
/// See the class remarks for how this is used to create a connection.
/// </summary>
/// <param name="model"> The model that will back this context. </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected DbContext(DbCompiledModel model)
{
Check.NotNull(model, "model");
InitializeLazyInternalContext(new LazyInternalConnection(this, GetType().DatabaseName()), model);
}
/// <summary>
/// Constructs a new context instance using the given string as the name or connection string for the
/// database to which a connection will be made.
/// See the class remarks for how this is used to create a connection.
/// </summary>
/// <param name="nameOrConnectionString"> Either the database name or a connection string. </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(string nameOrConnectionString)
{
Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString");
InitializeLazyInternalContext(new LazyInternalConnection(this, nameOrConnectionString));
}
/// <summary>
/// Constructs a new context instance using the given string as the name or connection string for the
/// database to which a connection will be made, and initializes it from the given model.
/// See the class remarks for how this is used to create a connection.
/// </summary>
/// <param name="nameOrConnectionString"> Either the database name or a connection string. </param>
/// <param name="model"> The model that will back this context. </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(string nameOrConnectionString, DbCompiledModel model)
{
Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString");
Check.NotNull(model, "model");
InitializeLazyInternalContext(new LazyInternalConnection(this, nameOrConnectionString), model);
}
/// <summary>
/// Constructs a new context instance using the existing connection to connect to a database.
/// The connection will not be disposed when the context is disposed if <paramref name="contextOwnsConnection" />
/// is <c>false</c>.
/// </summary>
/// <param name="existingConnection"> An existing connection to use for the new context. </param>
/// <param name="contextOwnsConnection">
/// If set to <c>true</c> the connection is disposed when the context is disposed, otherwise the caller must dispose the connection.
/// </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(DbConnection existingConnection, bool contextOwnsConnection)
{
Check.NotNull(existingConnection, "existingConnection");
InitializeLazyInternalContext(new EagerInternalConnection(this, existingConnection, contextOwnsConnection));
}
/// <summary>
/// Constructs a new context instance using the existing connection to connect to a database,
/// and initializes it from the given model.
/// The connection will not be disposed when the context is disposed if <paramref name="contextOwnsConnection" />
/// is <c>false</c>.
/// </summary>
/// <param name="existingConnection"> An existing connection to use for the new context. </param>
/// <param name="model"> The model that will back this context. </param>
/// <param name="contextOwnsConnection">
/// If set to <c>true</c> the connection is disposed when the context is disposed, otherwise the caller must dispose the connection.
/// </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
{
Check.NotNull(existingConnection, "existingConnection");
Check.NotNull(model, "model");
InitializeLazyInternalContext(new EagerInternalConnection(this, existingConnection, contextOwnsConnection), model);
}
/// <summary>
/// Constructs a new context instance around an existing ObjectContext.
/// </summary>
/// <param name="objectContext"> An existing ObjectContext to wrap with the new context. </param>
/// <param name="dbContextOwnsObjectContext">
/// If set to <c>true</c> the ObjectContext is disposed when the DbContext is disposed, otherwise the caller must dispose the connection.
/// </param>
public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
{
Check.NotNull(objectContext, "objectContext");
DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());
_internalContext = new EagerInternalContext(this, objectContext, dbContextOwnsObjectContext);
DiscoverAndInitializeSets();
}
// <summary>
// Initializes the internal context, discovers and initializes sets, and initializes from a model if one is provided.
// </summary>
// <param name="internalConnection"> The internal connection object with which to initialize. </param>
// <param name="model"> An optional <see cref="DbCompiledModel" /> with which to initialize. </param>
internal virtual void InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model = null)
{
DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());
_internalContext = new LazyInternalContext(
this, internalConnection, model
, DbConfiguration.DependencyResolver.GetService<Func<DbContext, IDbModelCacheKey>>()
, DbConfiguration.DependencyResolver.GetService<AttributeProvider>());
DiscoverAndInitializeSets();
}
// <summary>
// Discovers DbSets and initializes them.
// </summary>
private void DiscoverAndInitializeSets()
{
new DbSetDiscoveryService(this).InitializeSets();
}
#endregion
#region Model building
/// <summary>
/// This method is called when the model for a derived context has been initialized, but
/// before the model has been locked down and used to initialize the context. The default
/// implementation of this method does nothing, but it can be overridden in a derived class
/// such that the model can be further configured before it is locked down.
/// </summary>
/// <remarks>
/// Typically, this method is called only once when the first instance of a derived context
/// is created. The model for that context is then cached and is for all further instances of
/// the context in the app domain. This caching can be disabled by setting the ModelCaching
/// property on the given ModelBuilder, but note that this can seriously degrade performance.
/// More control over caching is provided through use of the DbModelBuilder and DbContextFactory
/// classes directly.
/// </remarks>
/// <param name="modelBuilder"> The builder that defines the model for the context being created. </param>
protected virtual void OnModelCreating(DbModelBuilder modelBuilder)
{
}
// <summary>
// Internal method used to make the call to the real OnModelCreating method.
// </summary>
// <param name="modelBuilder"> The model builder. </param>
internal void CallOnModelCreating(DbModelBuilder modelBuilder)
{
OnModelCreating(modelBuilder);
}
#endregion
#region Database management
/// <summary>
/// Creates a Database instance for this context that allows for creation/deletion/existence checks
/// for the underlying database.
/// </summary>
public Database Database
{
get
{
if (_database == null)
{
_database = new Database(InternalContext);
}
return _database;
}
}
#endregion
#region Context methods
/// <summary>
/// Returns a <see cref="DbSet{TEntity}"/> instance for access to entities of the given type in the context
/// and the underlying store.
/// </summary>
/// <remarks>
/// Note that Entity Framework requires that this method return the same instance each time that it is called
/// for a given context instance and entity type. Also, the non-generic <see cref="DbSet"/> returned by the
/// <see cref="Set(Type)"/> method must wrap the same underlying query and set of entities. These invariants must
/// be maintained if this method is overridden for anything other than creating test doubles for unit testing.
/// See the <see cref="DbSet{TEntity}"/> class for more details.
/// </remarks>
/// <typeparam name="TEntity"> The type entity for which a set should be returned. </typeparam>
/// <returns> A set for the given entity type. </returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Set")]
public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class
{
return (DbSet<TEntity>)InternalContext.Set<TEntity>();
}
/// <summary>
/// Returns a non-generic <see cref="DbSet"/> instance for access to entities of the given type in the context
/// and the underlying store.
/// </summary>
/// <param name="entityType"> The type of entity for which a set should be returned. </param>
/// <returns> A set for the given entity type. </returns>
/// <remarks>
/// Note that Entity Framework requires that this method return the same instance each time that it is called
/// for a given context instance and entity type. Also, the generic <see cref="DbSet{TEntity}"/> returned by the
/// <see cref="Set"/> method must wrap the same underlying query and set of entities. These invariants must
/// be maintained if this method is overridden for anything other than creating test doubles for unit testing.
/// See the <see cref="DbSet"/> class for more details.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Set")]
public virtual DbSet Set(Type entityType)
{
Check.NotNull(entityType, "entityType");
return (DbSet)InternalContext.Set(entityType);
}
/// <summary>
/// Saves all changes made in this context to the underlying database.
/// </summary>
/// <returns>
/// The number of state entries written to the underlying database. This can include
/// state entries for entities and/or relationships. Relationship state entries are created for
/// many-to-many relationships and relationships where there is no foreign key property
/// included in the entity class (often referred to as independent associations).
/// </returns>
/// <exception cref="DbUpdateException">An error occurred sending updates to the database.</exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A database command did not affect the expected number of rows. This usually indicates an optimistic
/// concurrency violation; that is, a row has been changed in the database since it was queried.
/// </exception>
/// <exception cref="DbEntityValidationException">
/// The save was aborted because validation of entity property values failed.
/// </exception>
/// <exception cref="NotSupportedException">
/// An attempt was made to use unsupported behavior such as executing multiple asynchronous commands concurrently
/// on the same context instance.</exception>
/// <exception cref="ObjectDisposedException">The context or connection have been disposed.</exception>
/// <exception cref="InvalidOperationException">
/// Some error occurred attempting to process entities in the context either before or after sending commands
/// to the database.
/// </exception>
public virtual int SaveChanges()
{
return InternalContext.SaveChanges();
}
#if !NET40
/// <summary>
/// Asynchronously saves all changes made in this context to the underlying database.
/// </summary>
/// <remarks>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </remarks>
/// <returns>
/// A task that represents the asynchronous save operation.
/// The task result contains the number of state entries written to the underlying database. This can include
/// state entries for entities and/or relationships. Relationship state entries are created for
/// many-to-many relationships and relationships where there is no foreign key property
/// included in the entity class (often referred to as independent associations).
/// </returns>
/// <exception cref="DbUpdateException">An error occurred sending updates to the database.</exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A database command did not affect the expected number of rows. This usually indicates an optimistic
/// concurrency violation; that is, a row has been changed in the database since it was queried.
/// </exception>
/// <exception cref="DbEntityValidationException">
/// The save was aborted because validation of entity property values failed.
/// </exception>
/// <exception cref="NotSupportedException">
/// An attempt was made to use unsupported behavior such as executing multiple asynchronous commands concurrently
/// on the same context instance.</exception>
/// <exception cref="ObjectDisposedException">The context or connection have been disposed.</exception>
/// <exception cref="InvalidOperationException">
/// Some error occurred attempting to process entities in the context either before or after sending commands
/// to the database.
/// </exception>
public virtual Task<int> SaveChangesAsync()
{
return SaveChangesAsync(CancellationToken.None);
}
/// <summary>
/// Asynchronously saves all changes made in this context to the underlying database.
/// </summary>
/// <remarks>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </remarks>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken" /> to observe while waiting for the task to complete.
/// </param>
/// <returns>
/// A task that represents the asynchronous save operation.
/// The task result contains the number of state entries written to the underlying database. This can include
/// state entries for entities and/or relationships. Relationship state entries are created for
/// many-to-many relationships and relationships where there is no foreign key property
/// included in the entity class (often referred to as independent associations).
/// </returns>
/// <exception cref="InvalidOperationException">Thrown if the context has been disposed.</exception>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "cancellationToken")]
public virtual Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
return InternalContext.SaveChangesAsync(cancellationToken);
}
#endif
/// <summary>
/// Returns the Entity Framework ObjectContext that is underlying this context.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the context has been disposed.</exception>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
ObjectContext IObjectContextAdapter.ObjectContext
{
get
{
// When dropping down to ObjectContext we force o-space loading for the types
// that we know about so that code can use the ObjectContext with o-space metadata
// without having to explicitly call LoadFromAssembly. For example Dynamic Data does
// this--see Dev11 142609.
InternalContext.ForceOSpaceLoadingForKnownEntityTypes();
return InternalContext.ObjectContext;
}
}
/// <summary>
/// Validates tracked entities and returns a Collection of <see cref="DbEntityValidationResult" /> containing validation results.
/// </summary>
/// <returns> Collection of validation results for invalid entities. The collection is never null and must not contain null values or results for valid entities. </returns>
/// <remarks>
/// 1. This method calls DetectChanges() to determine states of the tracked entities unless
/// DbContextConfiguration.AutoDetectChangesEnabled is set to false.
/// 2. By default only Added on Modified entities are validated. The user is able to change this behavior
/// by overriding ShouldValidateEntity method.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public IEnumerable<DbEntityValidationResult> GetValidationErrors()
{
var validationResults = new List<DbEntityValidationResult>();
//ChangeTracker.Entries() will call DetectChanges unless disabled by the user
foreach (var dbEntityEntry in ChangeTracker.Entries())
{
#pragma warning disable 612,618
if (dbEntityEntry.InternalEntry.EntityType != typeof(EdmMetadata)
&&
#pragma warning restore 612,618
ShouldValidateEntity(dbEntityEntry))
{
var validationResult = ValidateEntity(dbEntityEntry, new Dictionary<object, object>());
if (validationResult != null
&& !validationResult.IsValid)
{
validationResults.Add(validationResult);
}
}
}
return validationResults;
}
/// <summary>
/// Extension point allowing the user to override the default behavior of validating only
/// added and modified entities.
/// </summary>
/// <param name="entityEntry"> DbEntityEntry instance that is supposed to be validated. </param>
/// <returns> true to proceed with validation; false otherwise. </returns>
protected virtual bool ShouldValidateEntity(DbEntityEntry entityEntry)
{
Check.NotNull(entityEntry, "entityEntry");
return (entityEntry.State & (EntityState.Added | EntityState.Modified)) != 0;
}
/// <summary>
/// Extension point allowing the user to customize validation of an entity or filter out validation results.
/// Called by <see cref="GetValidationErrors" />.
/// </summary>
/// <param name="entityEntry"> DbEntityEntry instance to be validated. </param>
/// <param name="items">
/// User-defined dictionary containing additional info for custom validation. It will be passed to
/// <see
/// cref="System.ComponentModel.DataAnnotations.ValidationContext" />
/// and will be exposed as
/// <see
/// cref="System.ComponentModel.DataAnnotations.ValidationContext.Items" />
/// . This parameter is optional and can be null.
/// </param>
/// <returns> Entity validation result. Possibly null when overridden. </returns>
protected virtual DbEntityValidationResult ValidateEntity(
DbEntityEntry entityEntry, IDictionary<object, object> items)
{
Check.NotNull(entityEntry, "entityEntry");
return entityEntry.InternalEntry.GetValidationResult(items);
}
// <summary>
// Internal method that calls the protected ValidateEntity method.
// </summary>
// <param name="entityEntry"> DbEntityEntry instance to be validated. </param>
// <returns> Entity validation result. Possibly null when ValidateEntity is overridden. </returns>
internal virtual DbEntityValidationResult CallValidateEntity(DbEntityEntry entityEntry)
{
return ValidateEntity(entityEntry, new Dictionary<object, object>());
}
#endregion
#region Entity entries
/// <summary>
/// Gets a <see cref="DbEntityEntry{T}" /> object for the given entity providing access to
/// information about the entity and the ability to perform actions on the entity.
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity. </param>
/// <returns> An entry for the entity. </returns>
public DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class
{
Check.NotNull(entity, "entity");
return new DbEntityEntry<TEntity>(new InternalEntityEntry(InternalContext, entity));
}
/// <summary>
/// Gets a <see cref="DbEntityEntry" /> object for the given entity providing access to
/// information about the entity and the ability to perform actions on the entity.
/// </summary>
/// <param name="entity"> The entity. </param>
/// <returns> An entry for the entity. </returns>
public DbEntityEntry Entry(object entity)
{
Check.NotNull(entity, "entity");
return new DbEntityEntry(new InternalEntityEntry(InternalContext, entity));
}
#endregion
#region ChangeTracker and Configuration
/// <summary>
/// Provides access to features of the context that deal with change tracking of entities.
/// </summary>
/// <value> An object used to access features that deal with change tracking. </value>
public DbChangeTracker ChangeTracker
{
get { return new DbChangeTracker(InternalContext); }
}
/// <summary>
/// Provides access to configuration options for the context.
/// </summary>
/// <value> An object used to access configuration options. </value>
public DbContextConfiguration Configuration
{
get { return new DbContextConfiguration(InternalContext); }
}
#endregion
#region Disposable
/// <summary>
/// Calls the protected Dispose method.
/// </summary>
public void Dispose()
{
Dispose(disposing: true);
// This class has no unmanaged resources but it is possible that somebody could add some in a subclass.
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the context. The underlying <see cref="ObjectContext" /> is also disposed if it was created
/// is by this context or ownership was passed to this context when this context was created.
/// The connection to the database (<see cref="DbConnection" /> object) is also disposed if it was created
/// is by this context or ownership was passed to this context when this context was created.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
_internalContext.Dispose();
}
#endregion
#region InternalContext access
// <summary>
// Provides access to the underlying InternalContext for other parts of the internal design.
// </summary>
internal virtual InternalContext InternalContext
{
get { return _internalContext; }
}
#endregion
#region Hidden Object methods
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return base.ToString();
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <inheritdoc />
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
return base.GetType();
}
#endregion
}
}
| 50.28858 | 180 | 0.656151 | [
"Apache-2.0"
] | DenisBalan/ef6 | src/EntityFramework/DbContext.cs | 32,587 | 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.Collections.Generic;
using System.Device.Gpio;
using System.Device.Gpio.Drivers;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Iot.Device.Gpio.Drivers
{
/// <summary>
/// A generic GPIO driver for Allwinner SoCs.
/// </summary>
/// <remarks>
/// This is a generic GPIO driver for Allwinner SoCs.
/// It can even drive the internal pins that are not drawn out.
/// Before you operate, you must be clear about what you are doing.
/// </remarks>
public unsafe class SunxiDriver : SysFsDriver
{
private const string GpioMemoryFilePath = "/dev/mem";
// final_address = mapped_address + (target_address & map_mask) https://stackoverflow.com/a/37922968
private static readonly int _mapMask = Environment.SystemPageSize - 1;
private static readonly object s_initializationLock = new object();
private IDictionary<int, PinState> _pinModes = new Dictionary<int, PinState>();
private IntPtr _cpuxPointer = IntPtr.Zero;
private IntPtr _cpusPointer = IntPtr.Zero;
/// <summary>
/// CPUX-PORT base address.
/// </summary>
protected virtual int CpuxPortBaseAddress { get; }
/// <summary>
/// CPUS-PORT base address.
/// </summary>
protected virtual int CpusPortBaseAddress { get; }
/// <inheritdoc/>
protected override int PinCount => throw new PlatformNotSupportedException("This driver is generic so it can not enumerate how many pins are available.");
/// <inheritdoc/>
protected override int ConvertPinNumberToLogicalNumberingScheme(int pinNumber) => throw new PlatformNotSupportedException("This driver is generic so it can not perform conversions between pin numbering schemes.");
/// <summary>
/// Initializes a new instance of the <see cref="SunxiDriver"/> class.
/// </summary>
protected SunxiDriver()
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="SunxiDriver"/>.
/// </summary>
/// <param name="cpuxPortBaseAddress">CPUX-PORT base address (This can be find in the corresponding SoC datasheet).</param>
/// <param name="cpusPortBaseAddress">CPUS-PORT base address (This can be find in the corresponding SoC datasheet).</param>
public SunxiDriver(int cpuxPortBaseAddress, int cpusPortBaseAddress)
{
CpuxPortBaseAddress = cpuxPortBaseAddress;
CpusPortBaseAddress = cpusPortBaseAddress;
Initialize();
}
/// <inheritdoc/>
protected override void OpenPin(int pinNumber)
{
SetPinMode(pinNumber, PinMode.Input);
}
/// <inheritdoc/>
protected override void ClosePin(int pinNumber)
{
if (_pinModes.ContainsKey(pinNumber))
{
if (_pinModes[pinNumber].InUseByInterruptDriver)
{
base.ClosePin(pinNumber);
}
switch (_pinModes[pinNumber].CurrentPinMode)
{
case PinMode.InputPullDown:
case PinMode.InputPullUp:
SetPinMode(pinNumber, PinMode.Input);
break;
case PinMode.Output:
Write(pinNumber, PinValue.Low);
SetPinMode(pinNumber, PinMode.Input);
break;
default:
break;
}
_pinModes.Remove(pinNumber);
}
}
/// <inheritdoc/>
protected override void SetPinMode(int pinNumber, PinMode mode)
{
// Get port controller, port number and shift
(int PortController, int Port) unmapped = UnmapPinNumber(pinNumber);
int cfgNum = unmapped.Port / 8;
int cfgShift = unmapped.Port % 8;
int pulNum = unmapped.Port / 16;
int pulShift = unmapped.Port % 16;
// Pn_CFG is used to set the direction; Pn_PUL is used to set the pull up/dowm mode
uint* cfgPointer, pulPointer;
int cfgOffset, pulOffset;
// PortController from A to K
if (unmapped.PortController <= 10)
{
// Pn_CFG initial offset is 0x00
cfgOffset = (CpuxPortBaseAddress + unmapped.PortController * 0x24 + cfgNum * 0x04) & _mapMask;
// Pn_PUL initial offset is 0x1C
pulOffset = (CpuxPortBaseAddress + unmapped.PortController * 0x24 + 0x1C + pulNum * 0x04) & _mapMask;
cfgPointer = (uint*)(_cpuxPointer + cfgOffset);
pulPointer = (uint*)(_cpuxPointer + pulOffset);
}
else
{
cfgOffset = (CpusPortBaseAddress + (unmapped.PortController - 11) * 0x24 + cfgNum * 0x04) & _mapMask;
pulOffset = (CpusPortBaseAddress + (unmapped.PortController - 11) * 0x24 + 0x1C + pulNum * 0x04) & _mapMask;
cfgPointer = (uint*)(_cpusPointer + cfgOffset);
pulPointer = (uint*)(_cpusPointer + pulOffset);
}
uint cfgValue = *cfgPointer;
uint pulValue = *pulPointer;
// Clear register
// Input is 0b000; Output is 0b001
cfgValue &= ~(0b1111U << (cfgShift * 4));
// Pull-up is 0b01; Pull-down is 0b10; Default is 0b00
pulValue &= ~(0b11U << (pulShift * 2));
switch (mode)
{
case PinMode.Output:
cfgValue |= 0b_001U << (cfgShift * 4);
break;
case PinMode.Input:
// After clearing the register, the value is the input mode.
break;
case PinMode.InputPullDown:
pulValue |= 0b10U << (pulShift * 2);
break;
case PinMode.InputPullUp:
pulValue |= 0b01U << (pulShift * 2);
break;
default:
throw new ArgumentException("Unsupported pin mode.");
}
*cfgPointer = cfgValue;
*pulPointer = pulValue;
if (_pinModes.ContainsKey(pinNumber))
{
_pinModes[pinNumber].CurrentPinMode = mode;
}
else
{
_pinModes.Add(pinNumber, new PinState(mode));
}
}
/// <inheritdoc/>
protected override void Write(int pinNumber, PinValue value)
{
(int PortController, int Port) unmapped = UnmapPinNumber(pinNumber);
uint* dataPointer;
int dataOffset;
if (unmapped.PortController <= 10)
{
// Pn_DAT offset is 0x10
dataOffset = (CpuxPortBaseAddress + unmapped.PortController * 0x24 + 0x10) & _mapMask;
dataPointer = (uint*)(_cpuxPointer + dataOffset);
}
else
{
dataOffset = (CpusPortBaseAddress + (unmapped.PortController - 11) * 0x24 + 0x10) & _mapMask;
dataPointer = (uint*)(_cpusPointer + dataOffset);
}
uint dataValue = *dataPointer;
if (value == PinValue.High)
{
dataValue |= 0b1U << unmapped.Port;
}
else
{
dataValue &= ~(0b1U << unmapped.Port);
}
*dataPointer = dataValue;
}
/// <inheritdoc/>
protected unsafe override PinValue Read(int pinNumber)
{
(int PortController, int Port) unmapped = UnmapPinNumber(pinNumber);
uint* dataPointer;
int dataOffset;
if (unmapped.PortController <= 10)
{
// Pn_DAT offset is 0x10
dataOffset = (CpuxPortBaseAddress + unmapped.PortController * 0x24 + 0x10) & _mapMask;
dataPointer = (uint*)(_cpuxPointer + dataOffset);
}
else
{
dataOffset = (CpusPortBaseAddress + (unmapped.PortController - 11) * 0x24 + 0x10) & _mapMask;
dataPointer = (uint*)(_cpusPointer + dataOffset);
}
uint dataValue = *dataPointer;
return Convert.ToBoolean((dataValue >> unmapped.Port) & 0b1) ? PinValue.High : PinValue.Low;
}
/// <inheritdoc/>
protected override void AddCallbackForPinValueChangedEvent(int pinNumber, PinEventTypes eventTypes, PinChangeEventHandler callback)
{
_pinModes[pinNumber].InUseByInterruptDriver = true;
base.OpenPin(pinNumber);
base.AddCallbackForPinValueChangedEvent(pinNumber, eventTypes, callback);
}
/// <inheritdoc/>
protected override void RemoveCallbackForPinValueChangedEvent(int pinNumber, PinChangeEventHandler callback)
{
_pinModes[pinNumber].InUseByInterruptDriver = false;
base.OpenPin(pinNumber);
base.RemoveCallbackForPinValueChangedEvent(pinNumber, callback);
}
/// <inheritdoc/>
protected override WaitForEventResult WaitForEvent(int pinNumber, PinEventTypes eventTypes, CancellationToken cancellationToken)
{
_pinModes[pinNumber].InUseByInterruptDriver = true;
base.OpenPin(pinNumber);
return base.WaitForEvent(pinNumber, eventTypes, cancellationToken);
}
/// <inheritdoc/>
protected override ValueTask<WaitForEventResult> WaitForEventAsync(int pinNumber, PinEventTypes eventTypes, CancellationToken cancellationToken)
{
_pinModes[pinNumber].InUseByInterruptDriver = true;
base.OpenPin(pinNumber);
return base.WaitForEventAsync(pinNumber, eventTypes, cancellationToken);
}
/// <inheritdoc/>
protected override bool IsPinModeSupported(int pinNumber, PinMode mode)
{
return mode switch
{
PinMode.Input or PinMode.InputPullDown or PinMode.InputPullUp or PinMode.Output => true,
_ => false,
};
}
/// <inheritdoc/>
protected override PinMode GetPinMode(int pinNumber)
{
return _pinModes[pinNumber].CurrentPinMode;
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (_cpuxPointer != IntPtr.Zero)
{
Interop.munmap(_cpuxPointer, 0);
_cpuxPointer = IntPtr.Zero;
}
if (_cpusPointer != IntPtr.Zero)
{
Interop.munmap(_cpusPointer, 0);
_cpusPointer = IntPtr.Zero;
}
}
private void Initialize()
{
if (_cpuxPointer != IntPtr.Zero)
{
return;
}
lock (s_initializationLock)
{
if (_cpuxPointer != IntPtr.Zero)
{
return;
}
int fileDescriptor = Interop.open(GpioMemoryFilePath, FileOpenFlags.O_RDWR | FileOpenFlags.O_SYNC);
if (fileDescriptor == -1)
{
throw new IOException($"Error {Marshal.GetLastWin32Error()} initializing the Gpio driver (File open error).");
}
IntPtr cpuxMap = Interop.mmap(IntPtr.Zero, Environment.SystemPageSize, MemoryMappedProtections.PROT_READ | MemoryMappedProtections.PROT_WRITE, MemoryMappedFlags.MAP_SHARED, fileDescriptor, CpuxPortBaseAddress & ~_mapMask);
IntPtr cpusMap = Interop.mmap(IntPtr.Zero, Environment.SystemPageSize, MemoryMappedProtections.PROT_READ | MemoryMappedProtections.PROT_WRITE, MemoryMappedFlags.MAP_SHARED, fileDescriptor, CpusPortBaseAddress & ~_mapMask);
if (cpuxMap.ToInt64() == -1)
{
Interop.munmap(cpuxMap, 0);
throw new IOException($"Error {Marshal.GetLastWin32Error()} initializing the Gpio driver (CPUx initialize error).");
}
if (cpusMap.ToInt64() == -1)
{
Interop.munmap(cpusMap, 0);
throw new IOException($"Error {Marshal.GetLastWin32Error()} initializing the Gpio driver (CPUs initialize error).");
}
_cpuxPointer = cpuxMap;
_cpusPointer = cpusMap;
Interop.close(fileDescriptor);
}
}
/// <summary>
/// Map pin number with port controller name to pin number in the driver's logical numbering scheme.
/// </summary>
/// <param name="portController">Port controller name, like 'A', 'C'.</param>
/// <param name="port">Number of pins.</param>
/// <returns>Pin number in the driver's logical numbering scheme.</returns>
public static int MapPinNumber(char portController, int port)
{
int alphabetPosition = (portController >= 'A' && portController <= 'Z') ? portController - 'A' : throw new Exception();
return alphabetPosition * 32 + port;
}
/// <summary>
/// Unmap pin number in the driver's logical numbering scheme to pin number with port name.
/// </summary>
/// <param name="pinNumber">Pin number in the driver's logical numbering scheme.</param>
/// <returns>Pin number with port name.</returns>
protected static (int PortController, int Port) UnmapPinNumber(int pinNumber)
{
int port = pinNumber % 32;
int portController = (pinNumber - port) / 32;
return (portController, port);
}
private class PinState
{
public PinState(PinMode currentMode)
{
CurrentPinMode = currentMode;
InUseByInterruptDriver = false;
}
public PinMode CurrentPinMode { get; set; }
public bool InUseByInterruptDriver { get; set; }
}
}
}
| 37.207161 | 238 | 0.563101 | [
"MIT"
] | Manny27nyc/nanoFramework.IoT.Device | src/devices_generated/Gpio/Drivers/Sunxi/SunxiDriver.cs | 14,548 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Zodziu_paieska
{
class Program
{
const string INPUT_FILE1 = @"../../../Trecias.txt";
const string INPUT_FILE2 = @"../../../Zodziai_1.txt";
static void Main(string[] args)
{
string inputLine;
List<string> Words;
List<string> Matrix;
Dictionary<string, int> Map;
int n;
Read(out inputLine, out Words);
Init(out Matrix, out Map, out n, inputLine, Words);
Solve(Matrix, ref Map, n);
Print(Map, n);
}
static void Read(out string inputLine, out List<string> Words)
{
inputLine = String.Concat(File.ReadAllLines(INPUT_FILE1));
Words = File.ReadAllLines(INPUT_FILE2).ToList();
}
static void Init(out List<string> Matrix, out Dictionary<string, int> Map, out int n, string inputLine, List<string> Words)
{
n = (int)Math.Ceiling(Math.Sqrt(inputLine.Length));
Matrix = new List<string>(n);
Map = new Dictionary<string, int>();
for(int i = 0; i < n; i++)
{
string line = "";
for(int j = 0; j < n; j++)
{
int idx = i * n + j;
if(idx >= inputLine.Length)
{
line += " ";
}
else
{
line += inputLine[idx];
}
}
Matrix.Add(line);
}
foreach(var word in Words)
{
Map[word.ToLower()] = 0;
}
}
static void Solve(List<string> Matrix, ref Dictionary<string, int> Map, int n)
{
// each row
for(int i = 0; i < n; i++)
{
string str = "";
for (int j = 0; j < n; j++)
{
str += Matrix[i][j];
}
for(int l = 1; l < n; l++)
{
for (int s = 0; s + l <= n; s++)
{
string lookFor = str.Substring(s, l);
if(Map.ContainsKey(lookFor))
{
Map[lookFor]++;
}
}
}
}
// each col
for (int j = 0; j < n; j++)
{
string str = "";
for (int i = 0; i < n; i++)
{
str += Matrix[i][j];
}
for (int l = 1; l < n; l++)
{
for (int s = 0; s + l <= n; s++)
{
string lookFor = str.Substring(s, l);
if (Map.ContainsKey(lookFor))
{
Map[lookFor]++;
}
}
}
}
// diagonal that starts on 1st row
for (int j = 0; j < n; j++)
{
string str = "";
int jj = j;
for (int i = 0; i < n && jj < n; i++, jj++)
{
str += Matrix[i][jj];
}
for (int l = 1; l < n; l++)
{
for (int s = 0; s + l <= str.Length; s++)
{
string lookFor = str.Substring(s, l);
if (Map.ContainsKey(lookFor))
{
Map[lookFor]++;
}
}
}
}
// diagonal that starts on 1st col
for (int i = 0; i < n; i++)
{
string str = "";
int ii = i;
for (int j = 0; j < n && ii < n; j++, ii++)
{
str += Matrix[ii][j];
}
for (int l = 1; l < n; l++)
{
for (int s = 0; s + l <= str.Length; s++)
{
string lookFor = str.Substring(s, l);
if (Map.ContainsKey(lookFor))
{
Map[lookFor]++;
}
}
}
}
}
static void Print(Dictionary<string, int> Map, int n)
{
Console.WriteLine("n = {0}", n);
foreach(KeyValuePair<string, int> p in Map)
{
Console.WriteLine("{0} {1}", p.Key, p.Value);
}
}
}
}
| 30.654088 | 131 | 0.326016 | [
"MIT"
] | Luj8n/ktug | LD/LD_05/C#/martynas-sm/Zodziu_paieska/Program.cs | 4,876 | C# |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System.Configuration;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Portal.Cms.WebsiteSelectors;
namespace Microsoft.Xrm.Portal.Configuration
{
/// <summary>
/// The configuration settings for <see cref="IWebsiteSelector"/> dependencies.
/// </summary>
/// <remarks>
/// For an example of the configuration format refer to the <see cref="PortalCrmConfigurationManager"/>.
/// </remarks>
public sealed class WebsiteSelectorElement : InitializableConfigurationElement<IWebsiteSelector>
{
private const string DefaultWebsiteSelectorTypeName = "Microsoft.Xrm.Portal.Cms.WebsiteSelectors.NameWebsiteSelector, Microsoft.Xrm.Portal";
private static readonly ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propType;
static WebsiteSelectorElement()
{
_propType = new ConfigurationProperty("type", typeof(string), DefaultWebsiteSelectorTypeName, ConfigurationPropertyOptions.None);
_properties = new ConfigurationPropertyCollection { _propType };
}
protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Gets or sets the element name.
/// </summary>
public override string Name { get; set; }
/// <summary>
/// The dependency type name.
/// </summary>
[ConfigurationProperty("type", DefaultValue = DefaultWebsiteSelectorTypeName)]
public override string Type
{
get { return (string)base[_propType]; }
set { base[_propType] = value; }
}
/// <summary>
/// Creates a <see cref="IWebsiteSelector"/> object.
/// </summary>
/// <param name="portalName"></param>
/// <returns></returns>
public IWebsiteSelector CreateWebsiteSelector(string portalName = null)
{
return CreateDependencyAndInitialize(() => new NameWebsiteSelector(portalName), portalName);
}
}
}
| 32.548387 | 142 | 0.745292 | [
"MIT"
] | Adoxio/xRM-Portals-Community-Edition | Framework/Microsoft.Xrm.Portal/Configuration/WebsiteSelectorElement.cs | 2,018 | C# |
using FronApiUs.Core.Contracts;
using FronApiUs.Core.Endpoints;
using FronApiUs.Core.Models;
using FronApiUs.Core.Parameters;
using MediatR;
namespace FronApiUs.Core.Requests;
public class GetNowSensorData : IFronApiUsRequest, IRequest<List<NowSensorData>>
{
public GetNowSensorData(int deviceId)
{
var parameters = new SensorDataParameters(deviceId, FronApiUsConstants.DataCollection.SensorData.Now);
Endpoint = new SensorDataEndpoint(parameters);
}
public IFronApiUsEndpoint<IFronApiUsParameters> Endpoint { get; }
}
public class GetNowSensorDataHandler : IRequestHandler<GetNowSensorData, List<NowSensorData>>
{
private readonly IFronApiUsClient _fronApiUsClient;
public GetNowSensorDataHandler(IFronApiUsClient fronApiUsClient)
{
_fronApiUsClient = fronApiUsClient;
}
public Task<List<NowSensorData>> Handle(GetNowSensorData request, CancellationToken token)
{
throw new NotImplementedException();
}
} | 29.939394 | 110 | 0.771255 | [
"MIT"
] | KingLurchi/FronApiUs | src/FronApiUs.Core/Requests/GetNowSensorData.cs | 990 | C# |
using System.Web;
using System.Web.Optimization;
namespace MyLibrary
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 38.6875 | 112 | 0.572698 | [
"MIT"
] | alinawieczorek/my-library | MyLibrary/MyLibrary/App_Start/BundleConfig.cs | 1,240 | C# |
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Claims;
using Thinktecture.IdentityServer.Core.Connect.Models;
using Thinktecture.IdentityServer.Core.Models;
using Thinktecture.IdentityServer.Core.Services;
namespace Thinktecture.IdentityServer.Core.Connect
{
public class ValidatedAuthorizeRequest
{
public NameValueCollection Raw { get; set; }
public ClaimsPrincipal Subject { get; set; }
public string ResponseType { get; set; }
public string ResponseMode { get; set; }
public Flows Flow { get; set; }
public CoreSettings CoreSettings { get; set; }
public ScopeValidator ValidatedScopes { get; set; }
public string ClientId { get; set; }
public Client Client { get; set; }
public Uri RedirectUri { get; set; }
public List<string> RequestedScopes { get; set; }
public bool WasConsentShown { get; set; }
public string State { get; set; }
public string UiLocales { get; set; }
public bool IsOpenIdRequest { get; set; }
public bool IsResourceRequest { get; set; }
public string Nonce { get; set; }
public List<string> AuthenticationContextClasses { get; set; }
public List<string> AuthenticationMethods { get; set; }
public string DisplayMode { get; set; }
public string PromptMode { get; set; }
public int? MaxAge { get; set; }
public bool AccessTokenRequested
{
get
{
return (ResponseType == Constants.ResponseTypes.IdTokenToken ||
ResponseType == Constants.ResponseTypes.Code);
}
}
public ValidatedAuthorizeRequest()
{
RequestedScopes = new List<string>();
AuthenticationContextClasses = new List<string>();
AuthenticationMethods = new List<string>();
}
}
} | 34.55 | 79 | 0.630487 | [
"BSD-3-Clause"
] | dmorosinotto/Thinktecture.IdentityServer.v3 | source/Core/Connect/Validation/ValidatedAuthorizeRequest.cs | 2,075 | 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 route53-2013-04-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Route53.Model
{
/// <summary>
/// A complex type that describes change information about changes made to your hosted
/// zone.
/// </summary>
public partial class ChangeInfo
{
private string _id;
private ChangeStatus _status;
private DateTime? _submittedAt;
private string _comment;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public ChangeInfo() { }
/// <summary>
/// Instantiates ChangeInfo with the parameterized properties
/// </summary>
/// <param name="id">This element contains an ID that you use when performing a <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetChange.html">GetChange</a> action to get detailed information about the change.</param>
/// <param name="status">The current state of the request. <code>PENDING</code> indicates that this request has not yet been applied to all Amazon Route 53 DNS servers.</param>
/// <param name="submittedAt">The date and time that the change request was submitted in <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601 format</a> and Coordinated Universal Time (UTC). For example, the value <code>2017-03-27T17:48:16.751Z</code> represents March 27, 2017 at 17:48:16.751 UTC.</param>
public ChangeInfo(string id, ChangeStatus status, DateTime submittedAt)
{
_id = id;
_status = status;
_submittedAt = submittedAt;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// This element contains an ID that you use when performing a <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetChange.html">GetChange</a>
/// action to get detailed information about the change.
/// </para>
/// </summary>
[AWSProperty(Required=true, Max=32)]
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The current state of the request. <code>PENDING</code> indicates that this request
/// has not yet been applied to all Amazon Route 53 DNS servers.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public ChangeStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property SubmittedAt.
/// <para>
/// The date and time that the change request was submitted in <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO
/// 8601 format</a> and Coordinated Universal Time (UTC). For example, the value <code>2017-03-27T17:48:16.751Z</code>
/// represents March 27, 2017 at 17:48:16.751 UTC.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DateTime SubmittedAt
{
get { return this._submittedAt.GetValueOrDefault(); }
set { this._submittedAt = value; }
}
// Check to see if SubmittedAt property is set
internal bool IsSetSubmittedAt()
{
return this._submittedAt.HasValue;
}
/// <summary>
/// Gets and sets the property Comment.
/// <para>
/// A comment you can provide.
/// </para>
/// </summary>
[AWSProperty(Max=256)]
public string Comment
{
get { return this._comment; }
set { this._comment = value; }
}
// Check to see if Comment property is set
internal bool IsSetComment()
{
return this._comment != null;
}
}
} | 36.12766 | 319 | 0.608559 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Route53/Generated/Model/ChangeInfo.cs | 5,094 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.AppPlatform.V20201101Preview.Inputs
{
/// <summary>
/// Certificate resource payload.
/// </summary>
public sealed class CertificatePropertiesArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The certificate version of key vault.
/// </summary>
[Input("certVersion")]
public Input<string>? CertVersion { get; set; }
/// <summary>
/// The certificate name of key vault.
/// </summary>
[Input("keyVaultCertName", required: true)]
public Input<string> KeyVaultCertName { get; set; } = null!;
/// <summary>
/// The vault uri of user key vault.
/// </summary>
[Input("vaultUri", required: true)]
public Input<string> VaultUri { get; set; } = null!;
public CertificatePropertiesArgs()
{
}
}
}
| 28.878049 | 81 | 0.61402 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/AppPlatform/V20201101Preview/Inputs/CertificatePropertiesArgs.cs | 1,184 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 24.09.2021.
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using NUnit.Framework;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Migrations.Generations.SET001.DataTypes.Clr.DateOnly{
////////////////////////////////////////////////////////////////////////////////
//class TestSet_005__def_DefaultValueSql
public static class TestSet_005__def_DefaultValueSql
{
private const string c_testTableName
="EFCORE_TTABLE_DUMMY";
private const string c_testColumnName
="MY_COLUMN";
//-----------------------------------------------------------------------
private const string c_testColumnTypeName
="DATE";
//-----------------------------------------------------------------------
[Test]
public static void Test_0001__NOT_NULL()
{
var operation
=new CreateTableOperation
{
Name
=c_testTableName,
Columns
={
new AddColumnOperation
{
Name = c_testColumnName,
Table = c_testTableName,
ClrType = null,
ColumnType = c_testColumnTypeName,
IsNullable = false,
DefaultValueSql = "12345"
},
},
};//operation
//------------------------------------------------------------
var expectedSQL
=new TestSqlTemplate()
.T("CREATE TABLE ").N(c_testTableName).T(" (").CRLF()
.T(" ").N(c_testColumnName).T(" DATE DEFAULT 12345 NOT NULL").CRLF()
.T(");").CRLF();
TestHelper.Exec
(new[]{operation},
new[]{expectedSQL});
}//Test_0001__NOT_NULL
//-----------------------------------------------------------------------
[Test]
public static void Test_0002__NULLABLE()
{
var operation
=new CreateTableOperation
{
Name
=c_testTableName,
Columns
={
new AddColumnOperation
{
Name = c_testColumnName,
Table = c_testTableName,
ClrType = null,
ColumnType = c_testColumnTypeName,
IsNullable = true,
DefaultValueSql = "12345"
},
},
};//operation
//------------------------------------------------------------
var expectedSQL
=new TestSqlTemplate()
.T("CREATE TABLE ").N(c_testTableName).T(" (").CRLF()
.T(" ").N(c_testColumnName).T(" DATE DEFAULT 12345").CRLF()
.T(");").CRLF();
TestHelper.Exec
(new[]{operation},
new[]{expectedSQL});
}//Test_0002__NULLABLE
};//class TestSet_005__def_DefaultValueSql
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Migrations.Generations.SET001.DataTypes.Clr.DateOnly
| 29.897959 | 126 | 0.497611 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Migrations/Generations/SET001/DataTypes/Clr/DateOnly/TestSet_005__def_DefaultValueSql.cs | 2,932 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MyApp.Domain
{
public class Standard
{
public int Id { get; set; }
[MaxLength(100), Required]
public string Name { get; set; }
public int? MaxNumberOfStudents { get; set; }
public int? TeacherId { get; set; }
public Teacher Teacher { get; set; }
public ICollection<Student> Students { get; set; }
}
}
| 23.307692 | 58 | 0.661716 | [
"MIT"
] | antanta/MyApp | MyApp.Domain/Standard.cs | 608 | C# |
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Text;
namespace BlazorTransitionableRoute
{
public class Transition
{
private Transition(RouteData routeData, bool intoView, bool backwards, bool firstRender)
{
RouteData = routeData;
this.IntoView = intoView;
this.Backwards = backwards;
this.FirstRender = firstRender;
}
public static Transition Create(RouteData routeData, bool intoView, bool backwards, bool firstRender)
=> new Transition(routeData, intoView, backwards, firstRender);
public RouteData RouteData { get; }
public bool IntoView { get; }
public bool Backwards { get; }
public bool FirstRender { get; }
}
}
| 31.037037 | 110 | 0.638425 | [
"MIT"
] | KieranFleckney/BlazorTransitionableRoute | src/BlazorTransitionableRoute/Transition.cs | 840 | C# |
//
// PointerType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using MD = ScriptSharp.Importer.IL.Metadata;
namespace ScriptSharp.Importer.IL {
internal /* public */ sealed class PointerType : TypeSpecification {
public override string Name {
get { return base.Name + "*"; }
}
public override string FullName {
get { return base.FullName + "*"; }
}
public override bool IsValueType {
get { return false; }
set { throw new InvalidOperationException (); }
}
public override bool IsPointer {
get { return true; }
}
public PointerType (TypeReference type)
: base (type)
{
Mixin.CheckType (type);
this.etype = MD.ElementType.Ptr;
}
}
}
| 29.564516 | 73 | 0.717949 | [
"Apache-2.0"
] | AmanArnold/dsharp | src/Core/Compiler/Importer/IL/PointerType.cs | 1,833 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 23.09.2021.
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using NUnit.Framework;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Migrations.Generations.SET001.DataTypes.Clr.Boolean{
////////////////////////////////////////////////////////////////////////////////
using T_DATA=System.Boolean;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_002__def_ClrType_and_TypeName
public static class TestSet_002__def_ClrType_and_TypeName
{
private const string c_testTableName
="EFCORE_TTABLE_DUMMY";
private const string c_testColumnName
="MY_COLUMN";
//-----------------------------------------------------------------------
private const string c_testColumnTypeName
="BOOLEAN";
//-----------------------------------------------------------------------
[Test]
public static void Test_0001__NOT_NULL()
{
var operation
=new CreateTableOperation
{
Name
=c_testTableName,
Columns
={
new AddColumnOperation
{
Name = c_testColumnName,
Table = c_testTableName,
ClrType = typeof(T_DATA),
ColumnType = c_testColumnTypeName,
IsNullable = false,
},
},
};//operation
//------------------------------------------------------------
var expectedSQL
=new TestSqlTemplate()
.T("CREATE TABLE ").N(c_testTableName).T(" (").CRLF()
.T(" ").N(c_testColumnName).T(" BOOLEAN NOT NULL").CRLF()
.T(");").CRLF();
TestHelper.Exec
(new[]{operation},
new[]{expectedSQL});
}//Test_0001__NOT_NULL
//-----------------------------------------------------------------------
[Test]
public static void Test_0002__NULLABLE()
{
var operation
=new CreateTableOperation
{
Name
=c_testTableName,
Columns
={
new AddColumnOperation
{
Name = c_testColumnName,
Table = c_testTableName,
ClrType = typeof(T_DATA),
ColumnType = c_testColumnTypeName,
IsNullable = true,
},
},
};//operation
//------------------------------------------------------------
var expectedSQL
=new TestSqlTemplate()
.T("CREATE TABLE ").N(c_testTableName).T(" (").CRLF()
.T(" ").N(c_testColumnName).T(" BOOLEAN").CRLF()
.T(");").CRLF();
TestHelper.Exec
(new[]{operation},
new[]{expectedSQL});
}//Test_0002__NULLABLE
};//class TestSet_002__def_ClrType_and_TypeName
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Migrations.Generations.SET001.DataTypes.Clr.Boolean
| 29.86 | 125 | 0.487609 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Migrations/Generations/SET001/DataTypes/Clr/Boolean/TestSet_002__def_ClrType_and_TypeName.cs | 2,988 | C# |
using GraphicsComposerLib.PovRay.SDL.Modifiers;
namespace GraphicsComposerLib.PovRay.SDL.Textures
{
public interface ISdlTexture : ISdlObjectModifier
{
}
} | 19.888889 | 53 | 0.731844 | [
"MIT"
] | ga-explorer/GeometricAlgebraFulcrumLib | GraphicsComposerLib/GraphicsComposerLib.PovRay/SDL/Textures/ISdlTexture.cs | 181 | 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.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.ML.Data;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Runtime;
using Microsoft.ML.TensorFlow;
using Microsoft.ML.Transforms;
using Tensorflow;
using static Tensorflow.Binding;
namespace Microsoft.ML.TensorFlow
{
internal static class TensorFlowUtils
{
/// <summary>
/// Key to access operator's type (a string) in <see cref="DataViewSchema.Column.Annotations"/>.
/// Its value describes the Tensorflow operator that produces this <see cref="DataViewSchema.Column"/>.
/// </summary>
internal const string TensorflowOperatorTypeKind = "TensorflowOperatorType";
/// <summary>
/// Key to access upstream operators' names (a string array) in <see cref="DataViewSchema.Column.Annotations"/>.
/// Its value states operators that the associated <see cref="DataViewSchema.Column"/>'s generator depends on.
/// </summary>
internal const string TensorflowUpstreamOperatorsKind = "TensorflowUpstreamOperators";
internal static DataViewSchema GetModelSchema(IExceptionContext ectx, Graph graph, string opType = null)
{
var schemaBuilder = new DataViewSchema.Builder();
foreach (Operation op in graph)
{
if (opType != null && opType != op.OpType)
continue;
var tfType = op.OutputType(0);
// Determine element type in Tensorflow tensor. For example, a vector of floats may get NumberType.R4 here.
var mlType = Tf2MlNetTypeOrNull(tfType);
// If the type is not supported in ML.NET then we cannot represent it as a column in an Schema.
// We also cannot output it with a TensorFlowTransform, so we skip it.
// Furthermore, operators which have NumOutputs <= 0 needs to be filtered.
// The 'GetTensorShape' method crashes TensorFlow runtime
// (https://github.com/dotnet/machinelearning/issues/2156) when the operator has no outputs.
if (mlType == null || op.NumOutputs <= 0)
continue;
// Construct the final ML.NET type of a Tensorflow variable.
var tensorShape = op.output.TensorShape.dims;
var columnType = new VectorDataViewType(mlType);
if (!(Utils.Size(tensorShape) == 1 && tensorShape[0] <= 0) &&
(Utils.Size(tensorShape) > 0 && tensorShape.Skip(1).All(x => x > 0)))
columnType = new VectorDataViewType(mlType, tensorShape[0] > 0 ? tensorShape : tensorShape.Skip(1).ToArray());
// There can be at most two metadata fields.
// 1. The first field always presents. Its value is this operator's type. For example,
// if an output is produced by an "Softmax" operator, the value of this field should be "Softmax".
// 2. The second field stores operators whose outputs are consumed by this operator. In other words,
// these values are names of some upstream operators which should be evaluated before executing
// the current operator. It's possible that one operator doesn't need any input, so this field
// can be missing.
var metadataBuilder = new DataViewSchema.Annotations.Builder();
// Create the first metadata field.
metadataBuilder.Add(TensorflowOperatorTypeKind, TextDataViewType.Instance, (ref ReadOnlyMemory<char> value) => value = op.OpType.AsMemory());
if (op.NumInputs > 0)
{
// Put upstream operators' names to an array (type: VBuffer) of string (type: ReadOnlyMemory<char>).
VBuffer<ReadOnlyMemory<char>> upstreamOperatorNames = default;
var bufferEditor = VBufferEditor.Create(ref upstreamOperatorNames, op.NumInputs);
for (int i = 0; i < op.NumInputs; ++i)
bufferEditor.Values[i] = op.inputs[i].op.name.AsMemory();
upstreamOperatorNames = bufferEditor.Commit(); // Used in metadata's getter.
// Create the second metadata field.
metadataBuilder.Add(TensorflowUpstreamOperatorsKind, new VectorDataViewType(TextDataViewType.Instance, op.NumInputs),
(ref VBuffer<ReadOnlyMemory<char>> value) => { upstreamOperatorNames.CopyTo(ref value); });
}
schemaBuilder.AddColumn(op.name, columnType, metadataBuilder.ToAnnotations());
}
return schemaBuilder.ToSchema();
}
/// <summary>
/// This method retrieves the information about the graph nodes of a TensorFlow model as an <see cref="DataViewSchema"/>.
/// For every node in the graph that has an output type that is compatible with the types supported by
/// <see cref="TensorFlowTransformer"/>, the output schema contains a column with the name of that node, and the
/// type of its output (including the item type and the shape, if it is known). Every column also contains metadata
/// of kind <see cref="TensorflowOperatorTypeKind"/>, indicating the operation type of the node, and if that node has inputs in the graph,
/// it contains metadata of kind <see cref="TensorflowUpstreamOperatorsKind"/>, indicating the names of the input nodes.
/// </summary>
/// <param name="env">The environment to use.</param>
/// <param name="modelPath">Model to load.</param>
internal static DataViewSchema GetModelSchema(IHostEnvironment env, string modelPath)
{
var model = LoadTensorFlowModel(env, modelPath);
return GetModelSchema(env, model.Session.graph);
}
/// <summary>
/// Load TensorFlow model into memory.
/// </summary>
/// <param name="env">The environment to use.</param>
/// <param name="modelPath">The model to load.</param>
/// <returns></returns>
internal static TensorFlowModel LoadTensorFlowModel(IHostEnvironment env, string modelPath)
{
var session = GetSession(env, modelPath);
return new TensorFlowModel(env, session, modelPath);
}
internal static PrimitiveDataViewType Tf2MlNetType(TF_DataType type)
{
var mlNetType = Tf2MlNetTypeOrNull(type);
if (mlNetType == null)
throw new NotSupportedException("TensorFlow type not supported.");
return mlNetType;
}
internal static PrimitiveDataViewType Tf2MlNetTypeOrNull(TF_DataType type)
{
switch (type)
{
case TF_DataType.TF_FLOAT:
return NumberDataViewType.Single;
case TF_DataType.DtFloatRef:
return NumberDataViewType.Single;
case TF_DataType.TF_DOUBLE:
return NumberDataViewType.Double;
case TF_DataType.TF_UINT8:
return NumberDataViewType.Byte;
case TF_DataType.TF_UINT16:
return NumberDataViewType.UInt16;
case TF_DataType.TF_UINT32:
return NumberDataViewType.UInt32;
case TF_DataType.TF_UINT64:
return NumberDataViewType.UInt64;
case TF_DataType.TF_INT8:
return NumberDataViewType.SByte;
case TF_DataType.TF_INT16:
return NumberDataViewType.Int16;
case TF_DataType.TF_INT32:
return NumberDataViewType.Int32;
case TF_DataType.TF_INT64:
return NumberDataViewType.Int64;
case TF_DataType.TF_BOOL:
return BooleanDataViewType.Instance;
case TF_DataType.TF_STRING:
return TextDataViewType.Instance;
default:
return null;
}
}
internal static Session LoadTFSession(IExceptionContext ectx, byte[] modelBytes, string modelFile = null)
{
var graph = new Graph();
try
{
graph.Import(modelBytes, "");
}
catch (Exception ex)
{
if (!string.IsNullOrEmpty(modelFile))
throw ectx.Except($"TensorFlow exception triggered while loading model from '{modelFile}'");
#pragma warning disable MSML_NoMessagesForLoadContext
throw ectx.ExceptDecode(ex, "Tensorflow exception triggered while loading model.");
#pragma warning restore MSML_NoMessagesForLoadContext
}
return new Session(graph);
}
internal static void DownloadIfNeeded(IHostEnvironment env, string url, string dir, string fileName, int timeout)
{
using (var ch = env.Start("Ensuring meta files are present."))
{
var ensureModel = ResourceManagerUtils.Instance.EnsureResource(env, ch, url, fileName, dir, timeout);
ensureModel.Wait();
var errorResult = ResourceManagerUtils.GetErrorMessage(out var errorMessage, ensureModel.Result);
if (errorResult != null)
{
var directory = Path.GetDirectoryName(errorResult.FileName);
var name = Path.GetFileName(errorResult.FileName);
throw ch.Except($"{errorMessage}\nMeta file could not be downloaded! " +
$@"Please copy the model file '{name}' from '{url}' to '{directory}'.");
}
}
}
internal static Graph LoadMetaGraph(string path)
{
var graph = new Graph();
graph = graph.as_default();
tf.train.import_meta_graph(path);
return graph;
}
internal static Session LoadTFSessionByModelFilePath(IExceptionContext ectx, string modelFile, bool metaGraph = false)
{
if (string.IsNullOrEmpty(modelFile))
throw ectx.Except($"TensorFlow exception triggered while loading model from '{modelFile}'");
Graph graph;
try
{
if (metaGraph)
graph = LoadMetaGraph(modelFile);
else
{
graph = new Graph();
graph.Import(modelFile, "");
}
}
catch (Exception ex)
{
#pragma warning disable MSML_NoMessagesForLoadContext
throw ectx.ExceptDecode(ex, "Tensorflow exception triggered while loading model.");
#pragma warning restore MSML_NoMessagesForLoadContext
}
return new Session(graph);
}
private static Session LoadTFSession(IHostEnvironment env, string exportDirSavedModel)
{
Contracts.Check(env != null, nameof(env));
env.CheckValue(exportDirSavedModel, nameof(exportDirSavedModel));
return Session.LoadFromSavedModel(exportDirSavedModel);
}
// A TensorFlow frozen model is a single file. An un-frozen (SavedModel) on the other hand has a well-defined folder structure.
// Given a modelPath, this utility method determines if we should treat it as a SavedModel or not
internal static bool IsSavedModel(IHostEnvironment env, string modelPath)
{
Contracts.Check(env != null, nameof(env));
env.CheckNonWhiteSpace(modelPath, nameof(modelPath));
FileAttributes attr = File.GetAttributes(modelPath);
return attr.HasFlag(FileAttributes.Directory);
}
// Currently used in TensorFlowTransform to protect temporary folders used when working with TensorFlow's SavedModel format.
// Models are considered executable code, so we need to ACL tthe temp folders for high-rights process (so low-rights process can’t access it).
/// <summary>
/// Given a folder path, create it with proper ACL if it doesn't exist.
/// Fails if the folder name is empty, or can't create the folder.
/// </summary>
internal static void CreateFolderWithAclIfNotExists(IHostEnvironment env, string folder)
{
Contracts.Check(env != null, nameof(env));
env.CheckNonWhiteSpace(folder, nameof(folder));
//if directory exists, do nothing.
if (Directory.Exists(folder))
return;
WindowsIdentity currentIdentity = null;
try
{
currentIdentity = WindowsIdentity.GetCurrent();
}
catch (PlatformNotSupportedException)
{ }
if (currentIdentity != null && new WindowsPrincipal(currentIdentity).IsInRole(WindowsBuiltInRole.Administrator))
{
// Create high integrity dir and set no delete policy for all files under the directory.
// In case of failure, throw exception.
CreateTempDirectoryWithAcl(folder, currentIdentity.User.ToString());
}
else
{
try
{
Directory.CreateDirectory(folder);
}
catch (Exception exc)
{
throw Contracts.ExceptParam(nameof(folder), $"Failed to create folder for the provided path: {folder}. \nException: {exc.Message}");
}
}
}
internal static void DeleteFolderWithRetries(IHostEnvironment env, string folder)
{
Contracts.Check(env != null, nameof(env));
int currentRetry = 0;
int maxRetryCount = 10;
using (var ch = env.Start("Delete folder"))
{
for (; ; )
{
try
{
currentRetry++;
Directory.Delete(folder, true);
break;
}
catch (IOException e)
{
if (currentRetry > maxRetryCount)
throw;
ch.Info("Error deleting folder. {0}. Retry,", e.Message);
}
}
}
}
private static void CreateTempDirectoryWithAcl(string folder, string identity)
{
// Dacl Sddl string:
// D: Dacl type
// D; Deny access
// OI; Object inherit ace
// SD; Standard delete function
// wIdentity.User Sid of the given user.
// A; Allow access
// OICI; Object inherit, container inherit
// FA File access
// BA Built-in administrators
// S: Sacl type
// ML;; Mandatory Label
// NW;;; No write policy
// HI High integrity processes only
string sddl = "D:(D;OI;SD;;;" + identity + ")(A;OICI;FA;;;BA)S:(ML;OI;NW;;;HI)";
try
{
var dir = Directory.CreateDirectory(folder);
DirectorySecurity dirSec = new DirectorySecurity();
dirSec.SetSecurityDescriptorSddlForm(sddl);
dirSec.SetAccessRuleProtection(true, false); // disable inheritance
dir.SetAccessControl(dirSec);
// Cleaning out the directory, in case someone managed to sneak in between creation and setting ACL.
DirectoryInfo dirInfo = new DirectoryInfo(folder);
foreach (FileInfo file in dirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subDirInfo in dirInfo.GetDirectories())
{
subDirInfo.Delete(true);
}
}
catch (Exception exc)
{
throw Contracts.ExceptParam(nameof(folder), $"Failed to create folder for the provided path: {folder}. \nException: {exc.Message}");
}
}
/// <summary>
/// Load TensorFlow model into memory.
/// </summary>
/// <param name="env">The environment to use.</param>
/// <param name="modelPath">The model to load.</param>
/// <param name="metaGraph"></param>
/// <returns></returns>
internal static TensorFlowSessionWrapper LoadDnnModel(IHostEnvironment env, string modelPath, bool metaGraph = false) =>
new TensorFlowSessionWrapper(GetSession(env, modelPath, metaGraph), modelPath);
internal static Session GetSession(IHostEnvironment env, string modelPath, bool metaGraph = false)
{
Contracts.Check(env != null, nameof(env));
if (IsSavedModel(env, modelPath))
{
env.CheckUserArg(Directory.Exists(modelPath), nameof(modelPath));
return LoadTFSession(env, modelPath);
}
env.CheckUserArg(File.Exists(modelPath), nameof(modelPath));
return LoadTFSessionByModelFilePath(env, modelPath, metaGraph);
}
internal static unsafe void FetchStringData<T>(Tensor tensor, Span<T> result)
{
if (tensor == null)
throw Contracts.ExceptEmpty(nameof(tensor));
var buffer = tensor.StringData();
for (int i = 0; i < buffer.Length; i++)
result[i] = (T)(object)buffer[i].AsMemory();
}
internal static bool IsTypeSupported(TF_DataType tfoutput)
{
switch (tfoutput)
{
case TF_DataType.TF_FLOAT:
case TF_DataType.TF_DOUBLE:
case TF_DataType.TF_UINT8:
case TF_DataType.TF_UINT16:
case TF_DataType.TF_UINT32:
case TF_DataType.TF_UINT64:
case TF_DataType.TF_INT8:
case TF_DataType.TF_INT16:
case TF_DataType.TF_INT32:
case TF_DataType.TF_INT64:
case TF_DataType.TF_BOOL:
case TF_DataType.TF_STRING:
return true;
default:
return false;
}
}
/// <summary>
/// Use the runner class to easily configure inputs, outputs and targets to be passed to the session runner.
/// </summary>
public class Runner : IDisposable
{
private TF_Output[] _inputs;
private TF_Output[] _outputs;
private IntPtr[] _outputValues;
private IntPtr[] _inputValues;
private Tensor[] _inputTensors;
private IntPtr[] _operations;
private Session _session;
private Tensor[] _outputTensors;
private Status _status;
internal Runner(Session session, TF_Output[] inputs = null, TF_Output[] outputs = null, IntPtr[] operations = null)
{
_session = session;
_inputs = inputs ?? new TF_Output[0];
_outputs = outputs ?? new TF_Output[0];
_operations = operations ?? new IntPtr[0];
_inputValues = new IntPtr[_inputs.Length];
_inputTensors = new Tensor[_inputs.Length];
_outputValues = new IntPtr[_outputs.Length];
_outputTensors = new Tensor[_outputs.Length];
_status = new Status();
}
internal Runner(Session session, string[] inputs = null, string[] outputs = null, string[] operations = null)
{
_session = session;
_inputs = inputs?.Select(x => ParseOutput(session, x)).ToArray() ?? new TF_Output[0];
_outputs = outputs?.Select(x => ParseOutput(session, x)).ToArray() ?? new TF_Output[0];
_operations = operations?.Select(x => c_api.TF_GraphOperationByName(session.graph, x)).ToArray() ?? new IntPtr[0];
_inputValues = new IntPtr[_inputs.Length];
_inputTensors = new Tensor[_inputs.Length];
_outputValues = new IntPtr[_outputs.Length];
_outputTensors = new Tensor[_outputs.Length];
_status = new Status();
}
public Runner AddInput(Tensor value, int index)
{
_inputTensors[index]?.Dispose();
_inputTensors[index] = value;
_inputValues[index] = value;
return this;
}
// Parses user strings that contain both the operation name and an index.
public static TF_Output ParseOutput(Session session, string operation)
{
var p = operation.IndexOf(':');
if (p != -1 && p != operation.Length - 1)
{
var op = operation.Substring(0, p);
if (int.TryParse(operation.Substring(p + 1), out var idx))
{
return new TF_Output(session.graph.OperationByName(op), idx);
}
}
return new TF_Output(session.graph.OperationByName(operation), 0);
}
/// <summary>
/// Executes a pipeline given the specified inputs, inputValues, outputs, targetOpers, runMetadata and runOptions.
/// A simpler API is available by calling the <see cref="M:GetRunner"/> method which performs all the bookkeeping
/// necessary.
/// </summary>
/// <returns>An array of tensors fetched from the requested outputs.</returns>
public Tensor[] Run()
{
if (_session == IntPtr.Zero)
new ObjectDisposedException(nameof(_session));
unsafe
{
try
{
c_api.TF_SessionRun(_session, null, _inputs, _inputValues,
_inputs.Length, _outputs, _outputValues, _outputValues.Length, _operations,
_operations.Length, IntPtr.Zero, _status);
}
catch (Exception ex)
{
try
{
_status.Check(throwException: true);
}
catch (Exception statusException)
{
throw new AggregateException(statusException, ex);
}
// _status didn't provide more information, so just rethrow the original exception
throw;
}
}
_status.Check(true);
for (int i = 0; i < _outputs.Length; i++)
_outputTensors[i] = new Tensor(_outputValues[i]);
return _outputTensors;
}
public void Dispose()
{
foreach (var tensor in _inputTensors)
{
if (!tensor.IsDisposed)
tensor.Dispose();
}
_status.Dispose();
}
}
internal static string GetTemporaryDirectory()
{
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
return tempDirectory;
}
}
}
| 44.664815 | 157 | 0.561093 | [
"MIT"
] | pieths/dotnet_machinelearning | src/Microsoft.ML.TensorFlow/TensorflowUtils.cs | 24,123 | C# |
using System;
using System.Linq;
using System.Diagnostics;
using StackExchange.Redis;
using System.Threading;
namespace Redists.Tests.Fixtures
{
public class RedisServerFixture : IDisposable
{
private Process server;
private ConnectionMultiplexer mux;
private bool wasStarted = false;
public RedisServerFixture()
{
if (!IsRunning)
{
this.server = Process.Start(@"..\..\..\..\packages\Redis-64.2.8.21\redis-server.exe");
wasStarted = true;
}
Thread.Sleep(1000);
this.mux = ConnectionMultiplexer.Connect("localhost:6379,allowAdmin=true");
}
public void Dispose()
{
if (this.mux != null && this.mux.IsConnected)
this.mux.Close(false);
if (server != null && !server.HasExited && wasStarted)
server.Kill();
}
public IDatabase GetDatabase(int db)
{
return this.mux.GetDatabase(db);
}
public static bool IsRunning
{
get
{
return Process.GetProcessesByName("redis-server").Count() > 0;
}
}
public void Reset()
{
this.mux.GetServer("localhost:6379").FlushAllDatabases();
}
public static void Kill()
{
foreach (var p in Process.GetProcessesByName(@"redis-server"))
{
p.Kill();
}
}
//public static bool Watch()
//{
// if (IsRunning)
// {
// ProcessStartInfo info = new ProcessStartInfo();
// info.FileName = @"..\..\..\..\packages\Redis-64.2.8.19\redis-cli.exe";
// info.Arguments = "MONITOR";
// info.CreateNoWindow = true;
// info.UseShellExecute = false;
// info.RedirectStandardOutput = true;
// var cli = new Process();
// cli.StartInfo = info;
// cli.EnableRaisingEvents = true;
// cli.Start();
// }
// return false;
//}
//public static string GetInfo(string key=null)
//{
// if (IsRunning)
// {
// using (var cnx = new RedisConnection("localhost", allowAdmin: true))
// {
// cnx.Wait(cnx.Open());
// var infos = cnx.Server.GetInfo().Result;
// if (infos.ContainsKey(key))
// return key+":"+infos[key];
// else
// return string.Join(System.Environment.NewLine, infos.Select((k, v) => { return k.Key + ":" + k.Value; }));
// }
// }
// return string.Empty;
//}
}
}
| 28.81 | 132 | 0.471017 | [
"MIT"
] | Cybermaxs/Redists | tests/Redists.Tests/Fixtures/RedisServerFixture.cs | 2,883 | 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.Device.Spi;
using Iot.Device.Adc;
public class Volume : IDisposable
{
public static Volume EnableVolume()
{
var connection = new SpiConnectionSettings(0,0);
connection.ClockFrequency = 1000000;
connection.Mode = SpiMode.Mode0;
var spi = SpiDevice.Create(connection);
var mcp3008 = new Mcp3008(spi);
var volume = new Volume(mcp3008);
volume.Init();
return volume;
}
private Mcp3008 _mcp3008;
private int _lastValue = 0;
public Volume(Mcp3008 mcp3008)
{
_mcp3008 = mcp3008;
}
public int GetVolumeValue()
{
double value = _mcp3008.Read(0);
value = value / 10.24;
value = Math.Round(value);
return (int)value;
}
public void Dispose()
{
if (_mcp3008 != null)
{
_mcp3008.Dispose();
}
}
private void Init()
{
_lastValue = GetVolumeValue();
}
public (bool update, int value) GetSleepforVolume(int sleep)
{
var value = GetVolumeValue();
if (value > _lastValue - 2 && value < _lastValue +2)
{
return (false,0);
}
_lastValue = value;
Console.WriteLine($"Volume: {value}");
var tenth = value / 10;
if (tenth == 5)
{
return (true, sleep);
}
double factor = 5 - tenth;
factor = factor * 2;
factor = Math.Abs(factor);
var newValue = 0;
if (tenth < 5)
{
factor = 1 / factor;
}
newValue = (int)(sleep / factor);
if (newValue >=10 && newValue <=1000)
{
return (true,newValue);
}
return (true, sleep);
}
}
| 21.989011 | 71 | 0.54023 | [
"MIT"
] | HakanL/iot | samples/led-more-blinking-lights/Volume.cs | 2,003 | 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.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting
{
internal abstract class RazorFormattingService
{
public abstract Task<TextEdit[]> FormatAsync(Uri uri, RazorCodeDocument codeDocument, Range range, FormattingOptions options);
}
}
| 38.470588 | 134 | 0.796636 | [
"Apache-2.0"
] | devlead/aspnetcore-tooling | src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Formatting/RazorFormattingService.cs | 656 | C# |
using AspNetScaffolding.Controllers;
using AspNetScaffolding.Extensions.RoutePrefix;
using Microsoft.AspNetCore.Mvc;
namespace AspNetScaffolding3.DemoApi.Controllers
{
[IgnoreRoutePrefix]
public class ProxyController : BaseController
{
[HttpGet, HttpPost, HttpPut, HttpPatch, HttpDelete, HttpHead, HttpOptions]
[ProducesResponseType(200)]
[ProducesResponseType(201)]
[ProducesResponseType(401)]
[ProducesResponseType(409)]
[ProducesResponseType(412)]
[ProducesResponseType(422)]
[ProducesResponseType(500)]
public IActionResult HandleAllRequests()
{
return Ok();
}
}
}
| 28.625 | 82 | 0.684134 | [
"MIT"
] | ThiagoBarradas/aspnet-scaffolding3 | AspNetScaffolding3.DemoApi/Controllers/ProxyController.cs | 689 | C# |
using UniLife.Shared.DataModels;
using UniLife.Shared.Dto.Sample;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace UniLife.Shared.DataInterfaces
{
public interface IToDoStore
{
Task<List<TodoDto>> GetAll();
Task<TodoDto> GetById(long id);
Task<Todo> Create(TodoDto todoDto);
Task<Todo> Update(TodoDto todoDto);
Task DeleteById(long id);
}
} | 21.15 | 43 | 0.687943 | [
"MIT"
] | ahmetsekmen/UniLife | src/UniLife.Shared/DataInterfaces/IToDoStore.cs | 425 | C# |
// ***************************************************************************
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org>
// ***************************************************************************
using Newtonsoft.Json;
namespace MyStromRestApiCSharp.DTOs.Switch
{
public class WifiDetailed
{
/// <summary>
/// The name of the WiFi
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// The signal strength
/// </summary>
[JsonProperty("signal")]
public int SignalStrength { get; set; }
/// <summary>
/// Whether or not the wifi signal is encrypted
/// </summary>
[JsonProperty("encryption-on")]
public bool IsEncrypted { get; set; }
/// <summary>
/// The encryption standard used
/// </summary>
[JsonProperty("encryption")]
public string EncryptionType { get; set; }
}
} | 36.431034 | 79 | 0.659252 | [
"Unlicense"
] | UnterrainerInformatik/MyStromRestApiCSharp | MyStromRestApiCSharp/DTOs/Switch/WifiDetailed.cs | 2,115 | C# |
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license
*/
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace Thinktecture.IdentityServer.Core.Assets
{
class EmbeddedHtmlResult : IHttpActionResult
{
HttpRequestMessage request;
LayoutModel model;
public EmbeddedHtmlResult(HttpRequestMessage request, LayoutModel model)
{
this.request = request;
this.model = model;
}
public Task<System.Net.Http.HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
{
return Task.FromResult(GetResponseMessage(this.request, this.model));
}
public static HttpResponseMessage GetResponseMessage(HttpRequestMessage request, LayoutModel model)
{
var root = request.GetRequestContext().VirtualPathRoot;
var html = AssetManager.GetLayoutHtml(model, root);
return new HttpResponseMessage()
{
Content = new StringContent(html, Encoding.UTF8, "text/html")
};
}
}
}
| 30.128205 | 123 | 0.657021 | [
"BSD-3-Clause"
] | AscendXYZ/Thinktecture.IdentityServer.v3 | source/Core/Assets/EmbeddedHtmlResult.cs | 1,177 | C# |
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using TMDb.Client.Api;
using TMDb.Client.Builders;
using TMDb.Client.Configurations;
using TMDb.Client.Logging;
using TMDb.Client.Validators;
namespace TMDb.Client
{
public abstract class HttpClientWrapper : IDisposable
{
private static readonly LogManager _logger;
private readonly IRestClientConfiguration _clientConfiguration;
private readonly IRequestBuilder _requestBuilder;
private readonly IStatusCodeValidator _statusCodeValidator;
static HttpClientWrapper()
{
_logger = LogManager.GetLogger<HttpClientWrapper>();
}
public HttpClientWrapper(Uri baseUrl) : this(RestClientConfiguration.Instance, baseUrl)
{
}
public HttpClientWrapper(IRestClientConfiguration config, Uri baseUrl)
: this(new RequestBuilder(), config, new StatusCodeValidator(), baseUrl)
{
}
public HttpClientWrapper(
IRequestBuilder requestBuilder,
IRestClientConfiguration clientConfiguration,
IStatusCodeValidator statusCodeValidator,
Uri baseUrl)
{
_requestBuilder = requestBuilder;
_clientConfiguration = clientConfiguration;
_statusCodeValidator = statusCodeValidator;
var handler = new HttpClientHandler { SslProtocols = SslProtocols.Tls12 };
Client = new HttpClient(handler)
{
BaseAddress = baseUrl,
MaxResponseContentBufferSize = _clientConfiguration.MaxResponseContentBufferSize,
Timeout = clientConfiguration.Timeout,
};
Client.DefaultRequestHeaders.Accept.Add(clientConfiguration.ApplicationJsonHeader);
Client.DefaultRequestHeaders.Accept.Add(clientConfiguration.TextJsonHeader);
}
internal HttpClient Client { get; set; }
internal Uri BaseAddress { get; set; }
internal virtual async Task<TResponse> SendAsync<TResponse>(RequestBase request) //where TResponse : TMDbResponse
{
var expectedStatusCodes = new int[] { 200, 201 };
var httpRequestMessage = _requestBuilder.BuildRequest(Client.BaseAddress, request, _clientConfiguration);
var responseResult = new HttpResponseResult<TResponse>
{
ExpectedStatusCodes = expectedStatusCodes,
Request = httpRequestMessage,
Timer = Stopwatch.StartNew()
};
try
{
responseResult.Response = await Client.SendAsync(httpRequestMessage);
_statusCodeValidator.ValidateStatusCode(responseResult.Response, httpRequestMessage.RequestUri, expectedStatusCodes);
var responseText = await responseResult.Response.Content.ReadAsStringAsync();
responseResult.Result = responseText.ToObject<TResponse>(_clientConfiguration.ResponseSerializationSettings, true);
}
catch (Exception ex)
{
responseResult.Exception = ex;
_logger.LogException(ex);
if (ex.InnerException != null)
throw ex.InnerException;
throw;
}
finally
{
responseResult.Timer.Stop();
_logger.LogInfo(responseResult);
}
return responseResult.Result;
}
public void Dispose()
{
if (Client != null)
{
Client.Dispose();
Client = null;
}
GC.SuppressFinalize(this);
}
}
} | 34.581818 | 133 | 0.62408 | [
"MIT"
] | joshuajones02/TMDb | TMDb.Client/HttpClientWrapper.cs | 3,806 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ShopWebAPI.Models
{
public class Rating
{
public int Id { get; set; }
public int ProductId { get; set; }
public string UserId { get; set; }
public string Username { get; set; }
public int Rate { get; set; }
public string Comment { get; set; }
public DateTime DateCreated { get; set; }
public virtual Product Product { get; set; }
}
} | 24.190476 | 52 | 0.610236 | [
"MIT"
] | kdadun/ShopAngular | ShopWebAPI/ShopWebAPI/Models/Rating.cs | 510 | C# |
// <auto-generated />
using System;
using Fakebook.Posts.DataAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Fakebook.Posts.DataAccess.Migrations
{
[DbContext(typeof(FakebookPostsContext))]
partial class FakebookPostsContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityByDefaultColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.1");
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.Comment", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<int>("PostId")
.HasColumnType("integer");
b.Property<string>("UserEmail")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PostId");
b.ToTable("Comment", "Fakebook");
b.HasData(
new
{
Id = 1,
Content = "Nice",
CreatedAt = new DateTimeOffset(new DateTime(2021, 1, 13, 13, 51, 44, 564, DateTimeKind.Unspecified).AddTicks(4627), new TimeSpan(0, -8, 0, 0, 0)),
PostId = 1,
UserEmail = "testaccount@gmail.com"
});
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.CommentLike", b =>
{
b.Property<string>("LikerEmail")
.HasColumnType("text");
b.Property<int>("CommentId")
.HasColumnType("integer");
b.HasKey("LikerEmail", "CommentId")
.HasName("PK_CommentLikes");
b.HasIndex("CommentId");
b.ToTable("CommentLikes", "Fakebook");
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.Follow", b =>
{
b.Property<string>("FollowerEmail")
.HasColumnType("text");
b.Property<string>("FollowedEmail")
.HasColumnType("text");
b.HasKey("FollowerEmail", "FollowedEmail")
.HasName("PK_UserFollows");
b.ToTable("UserFollows", "Fakebook");
b.HasData(
new
{
FollowerEmail = "david.barnes@revature.net",
FollowedEmail = "testaccount@gmail.com"
},
new
{
FollowerEmail = "testaccount@gmail.com",
FollowedEmail = "david.barnes@revature.net"
});
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.Post", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.UseIdentityByDefaultColumn();
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("Picture")
.HasColumnType("text");
b.Property<string>("UserEmail")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Post", "Fakebook");
b.HasData(
new
{
Id = 1,
Content = "Just made my first post!",
CreatedAt = new DateTimeOffset(new DateTime(2021, 1, 13, 13, 51, 44, 561, DateTimeKind.Unspecified).AddTicks(3560), new TimeSpan(0, -8, 0, 0, 0)),
UserEmail = "david.barnes@revature.net"
},
new
{
Id = 2,
Content = "Fakebook is really cool.",
CreatedAt = new DateTimeOffset(new DateTime(2021, 1, 13, 13, 51, 44, 563, DateTimeKind.Unspecified).AddTicks(4657), new TimeSpan(0, -8, 0, 0, 0)),
UserEmail = "testaccount@gmail.com"
});
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.PostLike", b =>
{
b.Property<string>("LikerEmail")
.HasColumnType("text");
b.Property<int>("PostId")
.HasColumnType("integer");
b.HasKey("LikerEmail", "PostId")
.HasName("PK_PostLikes");
b.HasIndex("PostId");
b.ToTable("PostLikes", "Fakebook");
b.HasData(
new
{
LikerEmail = "testaccount@gmail.com",
PostId = 1
});
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.Comment", b =>
{
b.HasOne("Fakebook.Posts.DataAccess.Models.Post", "Post")
.WithMany("Comments")
.HasForeignKey("PostId")
.HasConstraintName("FK_Comment_Post")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Post");
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.CommentLike", b =>
{
b.HasOne("Fakebook.Posts.DataAccess.Models.Comment", "Comment")
.WithMany("CommentLikes")
.HasForeignKey("CommentId")
.HasConstraintName("FK_Like_Comment")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.PostLike", b =>
{
b.HasOne("Fakebook.Posts.DataAccess.Models.Post", "Post")
.WithMany("PostLikes")
.HasForeignKey("PostId")
.HasConstraintName("FK_Like_Post")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Post");
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.Comment", b =>
{
b.Navigation("CommentLikes");
});
modelBuilder.Entity("Fakebook.Posts.DataAccess.Models.Post", b =>
{
b.Navigation("Comments");
b.Navigation("PostLikes");
});
#pragma warning restore 612, 618
}
}
}
| 37.702703 | 174 | 0.435603 | [
"MIT"
] | revaturelabs/fakebook-posts | Fakebook.Posts/Fakebook.Posts.DataAccess/Migrations/FakebookPostsContextModelSnapshot.cs | 8,372 | C# |
using RSDKv5;
namespace ManiacEditor.Entity_Renders
{
public class TimeAttackGate : EntityRenderer
{
public override void Draw(Structures.EntityRenderProp Properties)
{
DevicePanel d = Properties.Graphics;
Classes.Scene.EditorEntity e = Properties.EditorObject;
int x = Properties.DrawX;
int y = Properties.DrawY;
int Transparency = Properties.Transparency;
bool finish = e.attributesMap["finishLine"].ValueBool;
var Animation1 = LoadAnimation("Global/SpeedGate.bin", d, 0, 0);
DrawTexturePivotNormal(Properties.Graphics, Animation1, Animation1.RequestedAnimID, Animation1.RequestedFrameID, x, y, Transparency);
var Animation2 = LoadAnimation("Global/SpeedGate.bin", d, 1, 0);
DrawTexturePivotNormal(Properties.Graphics, Animation2, Animation2.RequestedAnimID, Animation2.RequestedFrameID, x, y, Transparency);
var Animation3 = LoadAnimation("Global/SpeedGate.bin", d, (finish ? 4 : 3), 0);
for (int FrameID = 0; FrameID < Animation3.RequestedAnimation.Frames.Count; FrameID++)
{
DrawTexturePivotNormal(Properties.Graphics, Animation3, Animation3.RequestedAnimID, FrameID, x, y, Transparency);
}
}
public override string GetObjectName()
{
return "TimeAttackGate";
}
}
}
| 39.081081 | 145 | 0.644537 | [
"MIT"
] | CarJem/ManiacEditor | ManiacEditor/Entity Renders/Normal Renders/Generic/TimeAttackGate.cs | 1,448 | C# |
using ChartJs.Blazor.Common.Enums;
namespace ChartJs.Blazor.Common
{
/// <summary>
/// The model of the legend items which are displayed in the chart-legend.
/// <para>
/// As per documentation here:
/// <a href="https://www.chartjs.org/docs/latest/configuration/legend.html#legend-item-interface"/>
/// </para>
/// </summary>
public class LegendItem
{
/// <summary>
/// Gets or sets the index of the dataset this legend item corresponds to.
/// DO NOT set this value when returning an instance of this class to Chart.js.
/// Only use this property when retrieving the index in a legend-event.
/// This value might not be set in charts that have legend labels per value
/// (instead of per dataset) like pie-chart.
/// </summary>
public int? DatasetIndex { get; set; }
/// <summary>
/// Gets or sets the index of the value this legend item corresponds to.
/// DO NOT set this value when returning an instance of this class to Chart.js.
/// Only use this property when retrieving the index in a legend-event.
/// This value is only set in charts that have legend labels per value
/// (instead of per dataset) like pie-chart.
/// </summary>
public int? Index { get; set; }
/// <summary>
/// Gets or sets the label-text that will be displayed.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Gets or sets the color (style) of the legend box.
/// <para>See <see cref="Util.ColorUtil"/> for working with colors.</para>
/// </summary>
public string FillStyle { get; set; }
/// <summary>
/// Gets or sets a value indicating whether or not this legend-item represents a
/// hidden dataset. Label will be rendered with a strike-through effect if <see langword="true"/>.
/// </summary>
public bool? Hidden { get; set; }
/// <summary>
/// Gets or sets the <see cref="BorderCapStyle"/> for the legend box border.
/// </summary>
public BorderCapStyle LineCap { get; set; }
/// <summary>
/// Gets or sets the line dash segments for the legend box border.
/// Details on
/// <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash"/>.
/// </summary>
public double[] LineDash { get; set; }
/// <summary>
/// Gets or sets the line dash offset.
/// Details on
/// <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset"/>.
/// </summary>
public double? LineDashOffset { get; set; }
/// <summary>
/// Gets or sets the <see cref="BorderJoinStyle"/> of the legend box border.
/// </summary>
public BorderJoinStyle LineJoin { get; set; }
/// <summary>
/// Gets or sets the width of the box border.
/// </summary>
public double? LineWidth { get; set; }
/// <summary>
/// Gets or sets the color (style) of the legend box border.
/// <para>See <see cref="Util.ColorUtil"/> for working with colors.</para>
/// </summary>
public string StrokeStyle { get; set; }
/// <summary>
/// Gets or sets the <see cref="Enums.PointStyle"/> of the legend box
/// (only used if <see cref="LegendLabels.UsePointStyle"/> is <see langword="true"/>).
/// </summary>
public PointStyle PointStyle { get; set; }
/// <summary>
/// Gets or sets the rotation of the point in degrees
/// (only used if <see cref="LegendLabels.UsePointStyle"/> is <see langword="true"/>).
/// </summary>
public double? Rotation { get; set; }
}
}
| 40.020619 | 113 | 0.585265 | [
"MIT"
] | Franz1960/ChartJs.Blazor | src/ChartJs.Blazor/Common/LegendItem.cs | 3,884 | C# |
using UnityEngine;
using System.Collections;
public class SpriteCollection {
public Sprite[] sprites;
private string[] names;
public SpriteCollection(string spritesheet) {
sprites = Resources.LoadAll<Sprite>(spritesheet);
names = new string[sprites.Length];
for (var i = 0; i < names.Length; i++) {
names[i] = sprites[i].name;
//UtilFunctions.Alert("" + i + " " + names[i]);
}
}
public Sprite GetSprite(string name) {
return sprites[System.Array.IndexOf(names, name)];
}
public string GetSpriteName(int i) {
return sprites[i].name;
}
}
| 21.846154 | 52 | 0.68662 | [
"Apache-2.0"
] | nerl/Biber17-lecker | Assets/SpriteCollection.cs | 570 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace VKSaver.Core.Services.Interfaces
{
public interface IEmailService
{
Task SendSupportEmail();
}
}
| 17.384615 | 42 | 0.734513 | [
"Apache-2.0"
] | RomanGL/VKSaver | VKSaver2/Core/VKSaver.Core.Services.Shared/Interfaces/IEmailService.cs | 228 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.ContractsLight;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BuildXL.FrontEnd.CMake.Failures;
using BuildXL.FrontEnd.CMake.Serialization;
using BuildXL.FrontEnd.Ninja;
using BuildXL.FrontEnd.Sdk;
using BuildXL.FrontEnd.Utilities;
using BuildXL.FrontEnd.Workspaces;
using BuildXL.FrontEnd.Workspaces.Core;
using BuildXL.Native.IO;
using BuildXL.Processes;
using BuildXL.Utilities;
using BuildXL.Utilities.Collections;
using BuildXL.Utilities.Configuration;
using BuildXL.Utilities.Configuration.Mutable;
using BuildXL.Utilities.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using TypeScript.Net.DScript;
using TypeScript.Net.Types;
using static BuildXL.Utilities.FormattableStringEx;
namespace BuildXL.FrontEnd.CMake
{
/// <summary>
/// Workspace resolver using a custom JSON generator from CMake specs
/// </summary>
public class CMakeWorkspaceResolver : IWorkspaceModuleResolver
{
internal const string CMakeResolverName = "CMake";
/// <inheritdoc />
public string Name { get; }
private FrontEndContext m_context;
private FrontEndHost m_host;
private IConfiguration m_configuration;
private ICMakeResolverSettings m_resolverSettings;
private AbsolutePath ProjectRoot => m_resolverSettings.ProjectRoot;
private AbsolutePath m_buildDirectory;
private QualifierId[] m_requestedQualifiers;
private const string DefaultBuildTarget = "all";
// AsyncLazy graph
private readonly ConcurrentDictionary<AbsolutePath, SourceFile> m_createdSourceFiles =
new ConcurrentDictionary<AbsolutePath, SourceFile>();
/// <summary>
/// Keep in sync with the BuildXL deployment spec that places the tool (\Public\Src\Deployment\buildXL.dsc)
/// </summary>
private const string CMakeRunnerRelativePath = @"tools\CMakeRunner\CMakeRunner.exe";
private AbsolutePath m_pathToTool;
internal readonly NinjaWorkspaceResolver EmbeddedNinjaWorkspaceResolver;
private readonly Lazy<NinjaResolverSettings> m_embeddedResolverSettings;
private bool m_ninjaWorkspaceResolverInitialized;
internal Possible<NinjaGraphWithModuleDefinition> ComputedGraph => EmbeddedNinjaWorkspaceResolver.ComputedGraph;
/// <inheritdoc/>
public CMakeWorkspaceResolver()
{
Name = nameof(CMakeWorkspaceResolver);
EmbeddedNinjaWorkspaceResolver = new NinjaWorkspaceResolver();
m_embeddedResolverSettings = new Lazy<NinjaResolverSettings>(CreateEmbeddedResolverSettings);
}
/// <inheritdoc cref="Script.DScriptInterpreterBase" />
public Task<Possible<ISourceFile>> TryParseAsync(
AbsolutePath pathToParse,
AbsolutePath moduleOrConfigPathPromptingParse,
ParsingOptions parsingOptions = null)
{
return Task.FromResult(Possible.Create((ISourceFile)GetOrCreateSourceFile(pathToParse)));
}
private SourceFile GetOrCreateSourceFile(AbsolutePath path)
{
Contract.Assert(path.IsValid);
if (m_createdSourceFiles.TryGetValue(path, out SourceFile sourceFile))
{
return sourceFile;
}
// This is the interop point to advertise values to other DScript specs
// For now we just return an empty SourceFile
sourceFile = SourceFile.Create(path.ToString(m_context.PathTable));
// We need the binder to recurse
sourceFile.ExternalModuleIndicator = sourceFile;
sourceFile.SetLineMap(new int[0] { });
m_createdSourceFiles.Add(path, sourceFile);
return sourceFile;
}
/// <inheritdoc/>
public string DescribeExtent()
{
Possible<HashSet<ModuleDescriptor>> maybeModules = GetAllKnownModuleDescriptorsAsync().GetAwaiter().GetResult();
if (!maybeModules.Succeeded)
{
return I($"Module extent could not be computed. {maybeModules.Failure.Describe()}");
}
return string.Join(", ", maybeModules.Result.Select(module => module.Name));
}
/// <inheritdoc/>
public virtual string Kind => KnownResolverKind.CMakeResolverKind;
/// <inheritdoc/>
public async ValueTask<Possible<HashSet<ModuleDescriptor>>> GetAllKnownModuleDescriptorsAsync()
{
Contract.Assert(EmbeddedNinjaWorkspaceResolver != null);
Possible<Unit> maybeSuccess = await GenerateBuildDirectoryAsync();
if (!maybeSuccess.Succeeded)
{
return maybeSuccess.Failure;
}
if (!TryInitializeNinjaWorkspaceResolverIfNeeded())
{
return new NinjaWorkspaceResolverInitializationFailure();
}
var maybeResult = await EmbeddedNinjaWorkspaceResolver.GetAllKnownModuleDescriptorsAsync();
if (!maybeResult.Succeeded)
{
return new InnerNinjaFailure(maybeResult.Failure);
}
return maybeResult;
}
private bool TryInitializeNinjaWorkspaceResolverIfNeeded()
{
if (m_ninjaWorkspaceResolverInitialized)
{
return true;
}
return (m_ninjaWorkspaceResolverInitialized = EmbeddedNinjaWorkspaceResolver.TryInitialize(
m_host,
m_context,
m_configuration,
m_embeddedResolverSettings.Value,
m_requestedQualifiers));
}
private async Task<Possible<Unit>> GenerateBuildDirectoryAsync()
{
Contract.Assert(m_buildDirectory.IsValid);
AbsolutePath outputDirectory = m_host.GetFolderForFrontEnd(CMakeFrontEnd.Name);
AbsolutePath argumentsFile = outputDirectory.Combine(m_context.PathTable, Guid.NewGuid().ToString());
if (!TryRetrieveCMakeSearchLocations(out IEnumerable<AbsolutePath> searchLocations))
{
return new CMakeGenerationError(m_resolverSettings.ModuleName, m_buildDirectory.ToString(m_context.PathTable));
}
SandboxedProcessResult result = await ExecuteCMakeRunner(argumentsFile, searchLocations);
string standardError = result.StandardError.CreateReader().ReadToEndAsync().GetAwaiter().GetResult();
if (result.ExitCode != 0)
{
if (!m_context.CancellationToken.IsCancellationRequested)
{
Tracing.Logger.Log.CMakeRunnerInternalError(
m_context.LoggingContext,
m_resolverSettings.Location(m_context.PathTable),
standardError);
}
return new CMakeGenerationError(m_resolverSettings.ModuleName, m_buildDirectory.ToString(m_context.PathTable));
}
FrontEndUtilities.TrackToolFileAccesses(m_host.Engine, m_context, CMakeFrontEnd.Name, result.AllUnexpectedFileAccesses, outputDirectory);
return Possible.Create(Unit.Void);
}
private Task<SandboxedProcessResult> ExecuteCMakeRunner(AbsolutePath argumentsFile, IEnumerable<AbsolutePath> searchLocations)
{
string rootString = ProjectRoot.ToString(m_context.PathTable);
AbsolutePath outputDirectory = argumentsFile.GetParent(m_context.PathTable);
FileUtilities.CreateDirectory(outputDirectory.ToString(m_context.PathTable)); // Ensure it exists
SerializeToolArguments(argumentsFile, searchLocations);
void CleanUpOnResult()
{
try
{
FileUtilities.DeleteFile(argumentsFile.ToString(m_context.PathTable));
}
catch (BuildXLException e)
{
Tracing.Logger.Log.CouldNotDeleteToolArgumentsFile(
m_context.LoggingContext,
m_resolverSettings.Location(m_context.PathTable),
argumentsFile.ToString(m_context.PathTable),
e.Message);
}
}
var environment = FrontEndUtilities.GetEngineEnvironment(m_host.Engine, CMakeFrontEnd.Name);
// TODO: This manual configuration is temporary. Remove after the cloud builders have the correct configuration
var pathToManuallyDroppedTools = m_configuration.Layout.BuildEngineDirectory.Combine(m_context.PathTable, RelativePath.Create(m_context.StringTable, @"tools\CmakeNinjaPipEnvironment"));
if (FileUtilities.Exists(pathToManuallyDroppedTools.ToString(m_context.PathTable)))
{
environment = SpecialCloudConfiguration.OverrideEnvironmentForCloud(environment, pathToManuallyDroppedTools, m_context);
}
var buildParameters = BuildParameters.GetFactory().PopulateFromDictionary(new ReadOnlyDictionary<string, string>(environment));
return FrontEndUtilities.RunSandboxedToolAsync(
m_context,
m_pathToTool.ToString(m_context.PathTable),
buildStorageDirectory: outputDirectory.ToString(m_context.PathTable),
fileAccessManifest: GenerateFileAccessManifest(m_pathToTool.GetParent(m_context.PathTable)),
arguments: I($@"""{argumentsFile.ToString(m_context.PathTable)}"""),
workingDirectory: rootString,
description: "CMakeRunner",
buildParameters,
onResult: CleanUpOnResult);
}
private void SerializeToolArguments(in AbsolutePath argumentsFile, IEnumerable<AbsolutePath> searchLocations)
{
var arguments = new CMakeRunnerArguments()
{
ProjectRoot = ProjectRoot.ToString(m_context.PathTable),
BuildDirectory = m_buildDirectory.ToString(m_context.PathTable),
CMakeSearchLocations = searchLocations.Select(l => l.ToString(m_context.PathTable)),
CacheEntries = m_resolverSettings.CacheEntries
// TODO: Output file
};
var serializer = JsonSerializer.Create(new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Include,
});
using (var sw = new StreamWriter(argumentsFile.ToString(m_context.PathTable)))
using (var writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, arguments);
}
}
/// <summary>
/// Retrieves a list of search locations for CMake.exe using the resolver settings or, the PATH
/// </summary>
private bool TryRetrieveCMakeSearchLocations(out IEnumerable<AbsolutePath> searchLocations)
{
// TODO: This manual configuration is temporary. Remove after the cloud builders have the correct configuration
var pathTable = m_context.PathTable;
IReadOnlyList<AbsolutePath> cmakeSearchLocations = m_resolverSettings.CMakeSearchLocations?.SelectList(directoryLocation => directoryLocation.Path);
var pathToManuallyDroppedTools = m_configuration.Layout.BuildEngineDirectory.Combine(pathTable, RelativePath.Create(m_context.StringTable, @"tools\CmakeNinjaPipEnvironment"));
if (FileUtilities.Exists(pathToManuallyDroppedTools.ToString(pathTable)))
{
var cloudCmakeSearchLocations = new[] { pathToManuallyDroppedTools.Combine(pathTable, "cmake").Combine(pathTable, "bin") };
if (cmakeSearchLocations == null)
{
cmakeSearchLocations = cloudCmakeSearchLocations;
}
else
{
cmakeSearchLocations = cmakeSearchLocations.Union(cloudCmakeSearchLocations).ToList();
}
}
return FrontEndUtilities.TryRetrieveExecutableSearchLocations(
CMakeFrontEnd.Name,
m_context,
m_host.Engine,
cmakeSearchLocations,
out searchLocations,
() => Tracing.Logger.Log.NoSearchLocationsSpecified(m_context.LoggingContext, m_resolverSettings.Location(m_context.PathTable)),
paths => Tracing.Logger.Log.CannotParseBuildParameterPath(m_context.LoggingContext, m_resolverSettings.Location(m_context.PathTable), paths)
);
}
private NinjaResolverSettings CreateEmbeddedResolverSettings()
{
Contract.Assert(m_resolverSettings != null);
Contract.Assert(m_buildDirectory.IsValid);
var settings = new NinjaResolverSettings
{
ModuleName = m_resolverSettings.ModuleName,
ProjectRoot = m_buildDirectory,
// The "file in which this resolver was configured"
File = m_resolverSettings.File,
// TODO: Different targets
Targets = new[] { DefaultBuildTarget }
};
return settings;
}
/// <inheritdoc/>
public ValueTask<Possible<ModuleDefinition>> TryGetModuleDefinitionAsync(ModuleDescriptor moduleDescriptor)
{
return EmbeddedNinjaWorkspaceResolver.TryGetModuleDefinitionAsync(moduleDescriptor);
}
/// <inheritdoc/>
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public ValueTask<Possible<IReadOnlyCollection<ModuleDescriptor>>> TryGetModuleDescriptorsAsync(ModuleReferenceWithProvenance moduleReference)
{
return EmbeddedNinjaWorkspaceResolver.TryGetModuleDescriptorsAsync(moduleReference);
}
/// <inheritdoc/>
public ValueTask<Possible<ModuleDescriptor>> TryGetOwningModuleDescriptorAsync(AbsolutePath specPath)
{
return EmbeddedNinjaWorkspaceResolver.TryGetOwningModuleDescriptorAsync(specPath);
}
/// <inheritdoc/>
public Task ReinitializeResolver() => Task.FromResult<object>(null);
/// <inheritdoc />
public ISourceFile[] GetAllModuleConfigurationFiles()
{
return CollectionUtilities.EmptyArray<ISourceFile>();
}
/// <inheritdoc />
public bool TryInitialize([NotNull] FrontEndHost host, [NotNull] FrontEndContext context, [NotNull] IConfiguration configuration, [NotNull] IResolverSettings resolverSettings, [NotNull] QualifierId[] requestedQualifiers)
{
m_host = host;
m_context = context;
m_configuration = configuration;
m_resolverSettings = resolverSettings as ICMakeResolverSettings;
Contract.Assert(m_resolverSettings != null);
var relativePathToCMakeRunner = RelativePath.Create(context.StringTable, CMakeRunnerRelativePath);
m_pathToTool = configuration.Layout.BuildEngineDirectory.Combine(m_context.PathTable, relativePathToCMakeRunner);
m_buildDirectory = m_configuration.Layout.OutputDirectory.Combine(m_context.PathTable, m_resolverSettings.BuildDirectory);
m_requestedQualifiers = requestedQualifiers;
return true;
}
private FileAccessManifest GenerateFileAccessManifest(AbsolutePath toolDirectory)
{
// Get base FileAccessManifest
var fileAccessManifest = FrontEndUtilities.GenerateToolFileAccessManifest(m_context, toolDirectory);
fileAccessManifest.AddScope(
AbsolutePath.Create(m_context.PathTable, SpecialFolderUtilities.GetFolderPath(Environment.SpecialFolder.UserProfile)),
FileAccessPolicy.MaskAll,
FileAccessPolicy.AllowAllButSymlinkCreation);
fileAccessManifest.AddScope(
m_resolverSettings.ProjectRoot.Combine(m_context.PathTable, ".git"),
FileAccessPolicy.MaskAll,
FileAccessPolicy.AllowAllButSymlinkCreation);
return fileAccessManifest;
}
}
}
| 43.455471 | 229 | 0.645567 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/FrontEnd/CMake/CMakeWorkspaceResolver.cs | 17,078 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
namespace Workday.Inventory
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Goods_Delivery_Ticket_Request_CriteriaType : INotifyPropertyChanged
{
private CompanyObjectType company_ReferenceField;
private string goods_Delivery_Ticket_IDField;
private DateTime delivery_Ticket_Created_On_or_AfterField;
private bool delivery_Ticket_Created_On_or_AfterFieldSpecified;
private DateTime delivery_Ticket_Created_On_or_BeforeField;
private bool delivery_Ticket_Created_On_or_BeforeFieldSpecified;
private Document_StatusObjectType[] delivery_Ticket_Status_ReferenceField;
private LocationObjectType[] deliver_To_Location_ReferenceField;
private WorkerObjectType[] created_By_Worker_ReferenceField;
private WorkerObjectType requester_Worker_ReferenceField;
private Inventory_Stock_Request_OriginObjectType delivery_Ticket_Origin_ReferenceField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement(Order = 0)]
public CompanyObjectType Company_Reference
{
get
{
return this.company_ReferenceField;
}
set
{
this.company_ReferenceField = value;
this.RaisePropertyChanged("Company_Reference");
}
}
[XmlElement(Order = 1)]
public string Goods_Delivery_Ticket_ID
{
get
{
return this.goods_Delivery_Ticket_IDField;
}
set
{
this.goods_Delivery_Ticket_IDField = value;
this.RaisePropertyChanged("Goods_Delivery_Ticket_ID");
}
}
[XmlElement(DataType = "date", Order = 2)]
public DateTime Delivery_Ticket_Created_On_or_After
{
get
{
return this.delivery_Ticket_Created_On_or_AfterField;
}
set
{
this.delivery_Ticket_Created_On_or_AfterField = value;
this.RaisePropertyChanged("Delivery_Ticket_Created_On_or_After");
}
}
[XmlIgnore]
public bool Delivery_Ticket_Created_On_or_AfterSpecified
{
get
{
return this.delivery_Ticket_Created_On_or_AfterFieldSpecified;
}
set
{
this.delivery_Ticket_Created_On_or_AfterFieldSpecified = value;
this.RaisePropertyChanged("Delivery_Ticket_Created_On_or_AfterSpecified");
}
}
[XmlElement(DataType = "date", Order = 3)]
public DateTime Delivery_Ticket_Created_On_or_Before
{
get
{
return this.delivery_Ticket_Created_On_or_BeforeField;
}
set
{
this.delivery_Ticket_Created_On_or_BeforeField = value;
this.RaisePropertyChanged("Delivery_Ticket_Created_On_or_Before");
}
}
[XmlIgnore]
public bool Delivery_Ticket_Created_On_or_BeforeSpecified
{
get
{
return this.delivery_Ticket_Created_On_or_BeforeFieldSpecified;
}
set
{
this.delivery_Ticket_Created_On_or_BeforeFieldSpecified = value;
this.RaisePropertyChanged("Delivery_Ticket_Created_On_or_BeforeSpecified");
}
}
[XmlElement("Delivery_Ticket_Status_Reference", Order = 4)]
public Document_StatusObjectType[] Delivery_Ticket_Status_Reference
{
get
{
return this.delivery_Ticket_Status_ReferenceField;
}
set
{
this.delivery_Ticket_Status_ReferenceField = value;
this.RaisePropertyChanged("Delivery_Ticket_Status_Reference");
}
}
[XmlElement("Deliver_To_Location_Reference", Order = 5)]
public LocationObjectType[] Deliver_To_Location_Reference
{
get
{
return this.deliver_To_Location_ReferenceField;
}
set
{
this.deliver_To_Location_ReferenceField = value;
this.RaisePropertyChanged("Deliver_To_Location_Reference");
}
}
[XmlElement("Created_By_Worker_Reference", Order = 6)]
public WorkerObjectType[] Created_By_Worker_Reference
{
get
{
return this.created_By_Worker_ReferenceField;
}
set
{
this.created_By_Worker_ReferenceField = value;
this.RaisePropertyChanged("Created_By_Worker_Reference");
}
}
[XmlElement(Order = 7)]
public WorkerObjectType Requester_Worker_Reference
{
get
{
return this.requester_Worker_ReferenceField;
}
set
{
this.requester_Worker_ReferenceField = value;
this.RaisePropertyChanged("Requester_Worker_Reference");
}
}
[XmlElement(Order = 8)]
public Inventory_Stock_Request_OriginObjectType Delivery_Ticket_Origin_Reference
{
get
{
return this.delivery_Ticket_Origin_ReferenceField;
}
set
{
this.delivery_Ticket_Origin_ReferenceField = value;
this.RaisePropertyChanged("Delivery_Ticket_Origin_Reference");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 24.436275 | 136 | 0.7667 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Inventory/Goods_Delivery_Ticket_Request_CriteriaType.cs | 4,985 | C# |
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using GraphProcessor;
using UnityEditor.Experimental.SceneManagement;
using UnityEditor.SceneManagement;
namespace Mixture
{
[NodeCustomEditor(typeof(PrefabCaptureNode))]
public class PrefabCaptureNodeView : MixtureNodeView
{
PrefabCaptureNode sceneNode => nodeTarget as PrefabCaptureNode;
GameObject openedPrefabRoot;
string openedPrefabPath;
public override void Enable(bool fromInspector)
{
base.Enable(fromInspector);
var openPrefabButton = new Button(OpenPrefab) { text = "Open Prefab"};
controlsContainer.Add(openPrefabButton);
controlsContainer.Add(new Button(SaveView) { text = "Save Current View"});
if (!fromInspector)
{
EditorApplication.update -= RenderPrefabScene;
EditorApplication.update += RenderPrefabScene;
PrefabStage.prefabStageOpened -= PrefabOpened;
PrefabStage.prefabStageOpened += PrefabOpened;
PrefabStage.prefabStageClosing -= PrefabClosed;
PrefabStage.prefabStageClosing += PrefabClosed;
void PrefabOpened(PrefabStage stage) => OnPrefabOpened(stage, openPrefabButton);
void PrefabClosed(PrefabStage stage) => OnPrefabClosed(stage, openPrefabButton);
var stage = PrefabStageUtility.GetCurrentPrefabStage();
if (stage != null && stage.assetPath == AssetDatabase.GetAssetPath(sceneNode.prefab))
PrefabOpened(stage);
ObjectField debugTextureField = new ObjectField("Saved Texture") { value = sceneNode.savedTexture };
debugContainer.Add(debugTextureField);
nodeTarget.onProcessed += () => debugTextureField.SetValueWithoutNotify(sceneNode.savedTexture);
}
}
~PrefabCaptureNodeView()
{
EditorApplication.update -= RenderPrefabScene;
}
void RenderPrefabScene()
{
var stage = PrefabStageUtility.GetCurrentPrefabStage();
if (sceneNode.prefabCamera != null && stage != null)
{
sceneNode.prefabCamera.scene = stage.scene;
sceneNode.Render(sceneNode.prefabCamera);
}
}
void OnPrefabOpened(PrefabStage stage, Button openPrefabButton)
{
if (stage.assetPath != AssetDatabase.GetAssetPath(sceneNode.prefab))
return;
// Prefabs can only have one root GO (i guess?)
var root = stage.scene.GetRootGameObjects()[0];
openPrefabButton.text = "Close Prefab";
sceneNode.prefabOpened = true;
sceneNode.prefabCamera = root.GetComponentInChildren<Camera>();
sceneNode.bufferOutput = root.GetComponentInChildren<MixtureBufferOutput>();
if (sceneNode.prefabCamera == null)
Debug.LogError("No camera found in prefab, Please add one and re-open the prefab");
openedPrefabRoot = stage.prefabContentsRoot;
openedPrefabPath = stage.assetPath;
}
void OnPrefabClosed(PrefabStage stage, Button openPrefabButton)
{
if (stage.assetPath != AssetDatabase.GetAssetPath(sceneNode.prefab))
return;
openPrefabButton.text = "Open Prefab";
sceneNode.prefabOpened = false;
sceneNode.prefabCamera = null;
sceneNode.bufferOutput = null;
owner.graph.NotifyNodeChanged(nodeTarget);
}
void OpenPrefab()
{
if (!sceneNode.prefabOpened)
{
var path = AssetDatabase.GetAssetPath(sceneNode.prefab);
AssetDatabase.OpenAsset(sceneNode.prefab);
}
else
{
if (openedPrefabRoot != null)
PrefabUtility.SaveAsPrefabAsset(openedPrefabRoot, openedPrefabPath);
StageUtility.GoBackToPreviousStage();
}
owner.graph.NotifyNodeChanged(nodeTarget);
}
void SaveView() => sceneNode.SaveCurrentViewToImage();
public override void OnRemoved()
{
owner.graph.RemoveObjectFromGraph(sceneNode.savedTexture);
}
}
} | 36.122951 | 116 | 0.618334 | [
"MIT"
] | felixcantet/Mixture | Packages/com.alelievr.mixture/Editor/Views/PrefabCaptureNodeView.cs | 4,407 | C# |
using System.Collections.Generic;
namespace FluiTec.DatevSharp.Helpers
{
/// <summary> A string helper. </summary>
public static class StringHelper
{
private static readonly Dictionary<string, string> ReplaceMap = new Dictionary<string, string>
{
{"\r\n", " "},
{"\n", " "},
{"\"", "\"\""},
{";", ","}
};
private static readonly string Regex = string.Join("|", ReplaceMap.Keys);
/// <summary> A string extension method that converts a str to a datev string. </summary>
/// <param name="str"> The str to act on. </param>
/// <returns> str as a string. </returns>
public static string ToDatev(this string str)
{
return string.IsNullOrWhiteSpace(str)
? "\"\""
: $"\"{System.Text.RegularExpressions.Regex.Replace(str, Regex, m => ReplaceMap[m.Value])}\"";
}
}
} | 34.142857 | 110 | 0.536611 | [
"MIT"
] | IInvocation/DatevSharp | src/FluiTec.DatevSharp/Helpers/StringHelper.cs | 958 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PersonDB
{
public class PersonDAO_JSON_Ex : APersonDao
{
private string pathToFile;
public override string ConnectionString
{
get
{
return pathToFile;
}
set
{
pathToFile = value;
}
}
public PersonDAO_JSON_Ex()
{
pathToFile = Environment.CurrentDirectory + "\\PersonDB\\" + "personDB_Ex.json";
}
#region Additional functions
public override List<Person> Reader()
{
StreamReader fs = new StreamReader(pathToFile);
string jsonString = fs.ReadToEnd();
fs.Dispose();
List<Person> personList = JsonConvert.DeserializeObject<List<Person>>(jsonString);
if (personList == null)
{
personList = new List<Person>();
}
return personList;
}
public override void Writer(List<Person> personList)
{
StreamWriter fs = new StreamWriter(pathToFile);
fs.Write(JsonConvert.SerializeObject(personList));
fs.Dispose();
}
#endregion
}
}
| 22.721311 | 94 | 0.546898 | [
"BSD-3-Clause"
] | OlehMarchenko95/ort_csharp_js | PersonDB/DAO/File/PersonDAO_JSON_Ex.cs | 1,388 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StateMechanic;
namespace Samples
{
/// <summary>
/// Examples from the README
/// </summary>
public static class Scenario1
{
[Description("Quick Start")]
public static void QuickStart()
{
// We will first create our state machine by the name of "Machine"
var stateMachine = new StateMachine("Machine");
// Asign that machine an initial starting state
// We'll start with a state where we are awaiting a mission
var awaitingMission = stateMachine.CreateInitialState("Awaiting Mission");
// Add the rest of the possible states we have
var flyingToSearchArea = stateMachine.CreateState("Flying to Search Area");
var searchingForMobileLaunchers = stateMachine.CreateState("Searcing for Mobile Launchers");
var scanning = stateMachine.CreateState("Scanning");
var identifyingMobileLauncher = stateMachine.CreateState("Identifying Mobile Launcer");
var fixingMobileLauncher = stateMachine.CreateState("Fixing Mobile Launcher");
var returningToBase = stateMachine.CreateState("Returning To Base");
//Now we will add our transitions from states which will represent our events
var missionStarted = new Event("Mission Started");
var arrivedToSearchArea = new Event("Arrived to Search Area");
var startingMobileLauncherSearch = new Event("Starting Mobile Launcher Search");
var mobileLauncherDetected = new Event("Mobile Launcher Detected");
var mobileLauncherNotIdentified = new Event("Mobile Launcher Not Identified");
var mobileLauncherIdentified = new Event("Mobile Launcher Identified");
var positionFixed = new Event("Position Fixed");
var lowFuelDetected = new Event("Low Fuel Detected");
var missionCompleted = new Event("Mission Completed");
//Transitions from state to state based on legal events
awaitingMission.TransitionOn(missionStarted).To(flyingToSearchArea);
flyingToSearchArea.TransitionOn(arrivedToSearchArea).To(searchingForMobileLaunchers);
searchingForMobileLaunchers.TransitionOn(startingMobileLauncherSearch).To(scanning);
scanning.TransitionOn(mobileLauncherDetected).To(identifyingMobileLauncher);
identifyingMobileLauncher.TransitionOn(mobileLauncherNotIdentified).To(scanning);
identifyingMobileLauncher.TransitionOn(mobileLauncherIdentified).To(fixingMobileLauncher);
fixingMobileLauncher.TransitionOn(positionFixed).To(scanning);
// Return to Base on all states where Low Fuel is detected
flyingToSearchArea.TransitionOn(lowFuelDetected).To(returningToBase);
searchingForMobileLaunchers.TransitionOn(lowFuelDetected).To(returningToBase);
scanning.TransitionOn(lowFuelDetected).To(returningToBase);
identifyingMobileLauncher.TransitionOn(lowFuelDetected).To(returningToBase);
fixingMobileLauncher.TransitionOn(lowFuelDetected).To(returningToBase);
awaitingMission.TransitionOn(lowFuelDetected).To(returningToBase);
//Return to Base when mission is completed under the Searchingf for Mobile Launcher Hierarchy
scanning.TransitionOn(missionCompleted).To(returningToBase);
identifyingMobileLauncher.TransitionOn(missionCompleted).To(returningToBase);
fixingMobileLauncher.TransitionOn(missionCompleted).To(returningToBase);
//Signify where our machine is starting (initial state)
Assert.AreEqual(awaitingMission, stateMachine.CurrentState);
Assert.True(awaitingMission.IsCurrent);
// Fire events directly. This will throw an exception if there is no transition from the current state.
missionStarted.Fire();
Assert.AreEqual(flyingToSearchArea, stateMachine.CurrentState);
}
[Description("State Entry/Exit Handlers")]
public static void EntryExitHandlers()
{
var stateMachine = new StateMachine();
var initial = stateMachine.CreateInitialState("Initial");
var someState = stateMachine.CreateState("Some State")
.WithEntry(info => Console.WriteLine($"Entry from {info.From} to {info.To} on {info.Event}"))
.WithExit(info => Console.WriteLine($"Exit from {info.From} to {info.To} on {info.Event}"));
// You can also set the EntryHandler and ExitHandler properties directly
someState.EntryHandler = info => Console.WriteLine($"Entry from {info.From} to {info.To} on {info.Event}");
someState.ExitHandler = info => Console.WriteLine($"Exit from {info.From} to {info.To} on {info.Event}");
///////////////////////
var evt = new Event("event");
initial.TransitionOn(evt).To(someState);
someState.TransitionOn(evt).To(initial);
evt.Fire();
evt.Fire();
}
[Description("Transition Handlers")]
public static void TransitionHandlers()
{
var stateMachine = new StateMachine();
var someState = stateMachine.CreateInitialState("Some State");
var someOtherState = stateMachine.CreateState("Some Other State");
var someEvent = new Event("Some Event");
///////////////////////
someState.TransitionOn(someEvent).To(someOtherState)
.WithHandler(info => Console.WriteLine($"Transition from {info.From} to {info.To} on {info.Event}"));
// You can also set the Handler property directly
var transition = someState.TransitionOn(someEvent).To(someOtherState);
transition.Handler = info => Console.WriteLine($"Transition from {info.From} to {info.To} on {info.Event}");
///////////////////////
someEvent.Fire();
}
[Description("Inner Self Transitions")]
public static void InnerSelfTransitions()
{
var stateMachine = new StateMachine();
var event1 = new Event("Event 1");
var event2 = new Event("Event 2");
///////////////////////
var state = stateMachine.CreateInitialState("State")
.WithEntry(i => Console.WriteLine("Entry"))
.WithExit(i => Console.WriteLine("Exit"));
state.TransitionOn(event1).To(state).WithHandler(i => Console.WriteLine("Handler"));
state.InnerSelfTransitionOn(event2).WithHandler(i => Console.WriteLine("Handler"));
event1.Fire();
// Prints: Exit, Handler, Entry
event2.Fire();
// Prints: Handler
///////////////////////
}
[Description("Event Data")]
public static void EventData()
{
var stateMachine = new StateMachine();
var state = stateMachine.CreateInitialState("Initial State");
var anotherState = stateMachine.CreateState("Another State");
///////////////////////
// This is an event which takes a string argument (but you can use any data type)
var eventWithData = new Event<string>();
state.TransitionOn(eventWithData).To(anotherState)
.WithHandler(info => Console.WriteLine($"Data: {info.EventData}"));
// Provide the data when you fire the event
eventWithData.Fire("Some Data");
// Prints: "Data: Some Data"
///////////////////////
}
[Description("Transition Guards")]
public static void TransitionGuards()
{
var stateMachine = new StateMachine();
var stateA = stateMachine.CreateInitialState("State A");
var stateB = stateMachine.CreateState("State B");
var stateC = stateMachine.CreateState("State C");
var eventE = new Event("Event E");
///////////////////////
bool allowTransitionToStateB = false;
stateA.TransitionOn(eventE).To(stateB).WithGuard(info => allowTransitionToStateB);
stateA.TransitionOn(eventE).To(stateC);
eventE.Fire();
Assert.AreEqual(stateC, stateMachine.CurrentState);
///////////////////////
stateMachine.Reset();
///////////////////////
// Alternatively...
allowTransitionToStateB = true;
eventE.Fire();
Assert.AreEqual(stateB, stateMachine.CurrentState);
///////////////////////
}
[Description("Dynamic Transitions")]
public static void DynamicTransitions()
{
var stateMachine = new StateMachine();
var stateA = stateMachine.CreateInitialState("State A");
var stateB = stateMachine.CreateState("State B");
var stateC = stateMachine.CreateState("State C");
var eventE = new Event("Event E");
///////////////////////
State stateToTransitionTo = stateB;
stateA.TransitionOn(eventE).ToDynamic(info => stateToTransitionTo);
eventE.Fire();
Assert.AreEqual(stateB, stateMachine.CurrentState);
///////////////////////
stateMachine.Reset();
///////////////////////
// Alternatively...
stateToTransitionTo = stateC;
eventE.Fire();
Assert.AreEqual(stateC, stateMachine.CurrentState);
}
[Description("State Groups")]
public static void StateGroups()
{
var stateMachine = new StateMachine();
var initial = stateMachine.CreateInitialState("Initial");
var evt = new Event("evt");
///////////////////////
var stateA = stateMachine.CreateState("State A");
var stateB = stateMachine.CreateState("State B");
// You can create state groups, and add states to them
var statesAAndB = new StateGroup("States A and B")
.WithEntry(info => Console.WriteLine($"Entering group from {info.From} to {info.To} on {info.Event}"))
.WithExit(info => Console.WriteLine($"Exiting group from {info.From} to {info.To} on {info.Event}"));
statesAAndB.AddStates(stateA, stateB);
// You can also add states to groups
stateA.AddToGroup(statesAAndB);
///////////////////////
initial.TransitionOn(evt).To(stateA);
stateA.TransitionOn(evt).To(stateB);
stateB.TransitionOn(evt).To(initial);
evt.Fire();
evt.Fire();
evt.Fire();
}
[Description("Child State Machines")]
public static void ChildStateMachines()
{
var parentStateMachine = new StateMachine("Parent");
parentStateMachine.Transition += (o, e) => Console.WriteLine($"Transition: {e.From.Name} -> {e.To.Name} ({e.Event.Name})");
var disconnected = parentStateMachine.CreateInitialState("Disconnected")
.WithEntry(i => Console.WriteLine($"Disconnected entered: {i}"))
.WithExit(i => Console.WriteLine($"Disconnected exited: {i}"));
var connectingSuperState = parentStateMachine.CreateState("ConnectingSuperState")
.WithEntry(i => Console.WriteLine($"ConnectingSuperState entered: {i}"))
.WithExit(i => Console.WriteLine($"ConnectingSuperState exited: {i}"));
var connectedSuperState = parentStateMachine.CreateState("ConnectedSuperState")
.WithEntry(i => Console.WriteLine($"ConnectedSuperState entered: {i}"))
.WithExit(i => Console.WriteLine($"ConnectedSuperState exited: {i}"));
// 'Connecting' child state machine
var connectingStateMachine = connectingSuperState.CreateChildStateMachine("ConnectingSM");
var connectingInitialise = connectingStateMachine.CreateInitialState("ConnectingInitialisation")
.WithEntry(i => Console.WriteLine($"ConnectingInitialisation entered: {i}"))
.WithExit(i => Console.WriteLine($"ConnectingInitialisation exited: {i}"));
var connecting = connectingStateMachine.CreateState("Connecting")
.WithEntry(i => Console.WriteLine($"Connecting entered: {i}"))
.WithExit(i => Console.WriteLine($"Connecting exited: {i}"));
var handshaking = connectingStateMachine.CreateState("Handshaking")
.WithEntry(i => Console.WriteLine($"Handshaking entered: {i}"))
.WithExit(i => Console.WriteLine($"Handshaking exited: {i}"));
// 'Connected' child state machine
var connectedStateMachine = connectedSuperState.CreateChildStateMachine("ConnectedSM");
var authorising = connectedStateMachine.CreateInitialState("Authorising")
.WithEntry(i => Console.WriteLine($"Authorising entered: {i}"))
.WithExit(i => Console.WriteLine($"Authorising exited: {i}"));
var connected = connectedStateMachine.CreateState("Connected")
.WithEntry(i => Console.WriteLine($"Connected entered: {i}"))
.WithExit(i => Console.WriteLine($"Connected exited: {i}"));
var eventConnect = new Event("Connect");
var eventConnectionInitialised = new Event("Connecting Initialised");
var eventConnected = new Event("Connected");
var eventHandshakingCompleted = new Event("Handshaking Completed");
var eventAuthorisingCompleted = new Event("Authorising Completed");
var eventDisconnected = new Event("Disconnected");
disconnected.TransitionOn(eventConnect).To(connectingSuperState)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
connectingInitialise.TransitionOn(eventConnectionInitialised).To(connecting)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
connecting.TransitionOn(eventConnected).To(handshaking)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
handshaking.TransitionOn(eventDisconnected).To(connecting)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
connectingSuperState.TransitionOn(eventHandshakingCompleted).To(connectedSuperState)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
authorising.TransitionOn(eventAuthorisingCompleted).To(connected)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}")); ;
connectingSuperState.TransitionOn(eventDisconnected).To(disconnected)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
connectedSuperState.TransitionOn(eventDisconnected).To(disconnected)
.WithHandler(i => Console.WriteLine($"Transition Handler: {i}"));
// This is a "successful" path through the system
// We start off in the initial state
Assert.AreEqual(disconnected, parentStateMachine.CurrentState);
// And the child state machines are not active
Assert.False(connectingStateMachine.IsActive);
// This causes a transition from disconnected -> connectingSuperState. Since connectingSuperState
// has a child state machine, this is activated and its initial state connectingInitialise is entered.
// The following events therefore occur:
// 1. Disconnected's Exit Handler is called. From=Disconnected, To=ConnectingSuperState
// 2. The transition handler from Disconnected to ConnectingSuperState is called. From=Disconnected,
// To=ConnectingSuperState
// 3. ConnectingSuperState's Entry Handler is called. From=Disconnected, To=ConnectingSuperState
// 4. ConnectingInitialisation's Entry Handler is called. From=Disconnected, To=ConnectingInitialisation
// 5. The Transition event on the parentStateMachine is raised
eventConnect.Fire();
// The parent state machine's 'CurrentState' is the topmost current state
Assert.AreEqual(connectingSuperState, parentStateMachine.CurrentState);
// While its 'CurrentChildState' property indicates the currently-active child state machine's state
Assert.AreEqual(connectingInitialise, parentStateMachine.CurrentChildState);
// The child state machine knows that it is active
Assert.True(connectingStateMachine.IsActive);
// And knows what its current state is
Assert.AreEqual(connectingInitialise, connectingStateMachine.CurrentState);
// When this event is fired, the currently active child state machine (which is connectingStateMachine)
// is given the chance to handle the event. Since there's a valid transition (from connectingInitialise
// to connecting), this transition takes place
eventConnectionInitialised.Fire();
// As before, this indicates the currently-active child state
Assert.AreEqual(connecting, parentStateMachine.CurrentChildState);
// Again, this is handled by the child state machine
eventConnected.Fire();
Assert.AreEqual(handshaking, parentStateMachine.CurrentChildState);
// This is passed to the child state machine, but that does not know how to handle it, so it bubbles
// up to the parent state machine. This causes a transition from connectingSuperState to
// connectedSuperState. This causes a number of things, in order:
// 1. Handshaking's Exit Handler is called. From=Handshaking, To=ConnectedSuperState
// 2. ConnectingSuperState's Exit Handler is called. From=ConnectingSuperState, To=ConnectedSuperState
// 3. The transition handler for the transition between ConnectingSuperState and ConnectedSuperState
// is called
// 4. ConnectedSuperState's Entry Handler is called. From=ConnectingSuperState, To=ConnectedSuperState
// 5. Authorising's Entry Handler is called. From=ConnectingSuperState, To=Authorising
// 6. The Transition event on the parentStateMachine is raised
eventHandshakingCompleted.Fire();
Assert.True(authorising.IsCurrent);
// This is another transition solely inside a child state machine, from authorising to connected
eventAuthorisingCompleted.Fire();
// This is another event which is first sent to the child state machine, then bubbled up to its parent
// state machine. It causes the following things to occur:
// 1. Connected's Exit Handler is called. From=Connected, To=Disconnected
// 2. ConnectedSuperState's Exit Handler is called. From=ConnectedSuperState, To=Disconnected
// 3. The transition handler from ConnectedSuperState to Disconnected is called.
// From=ConnectedSuperState, To=Disconnected
// 4. Disconnected's Entry Handler is called. From=ConnectedSuperState, To=Disconnected
// 5. The Transition event on the parentStateMachine is raised
eventDisconnected.Fire();
Assert.AreEqual(disconnected, parentStateMachine.CurrentState);
// Here we show that firing 'disconnected' while in 'connecting' transitions to 'disconnected'.
// I won't go into as much detail as the previous example.
eventConnect.Fire();
eventConnectionInitialised.Fire();
eventConnected.Fire();
// This will be handled by the child state machine
eventDisconnected.Fire();
Assert.AreEqual(connecting, parentStateMachine.CurrentChildState);
}
[Description("Serialization and Deserialization")]
public static void SerializationAndDeserialization()
{
var stateMachine = new StateMachine();
var stateA = stateMachine.CreateInitialState("StateA");
var stateB = stateMachine.CreateState("StateB");
var evt = new Event();
stateA.TransitionOn(evt).To(stateB);
// Move us out of the default state
evt.Fire();
Assert.AreEqual(stateB, stateMachine.CurrentState);
string serialized = stateMachine.Serialize();
// Reset the state machine
stateMachine.Reset();
Assert.AreEqual(stateA, stateMachine.CurrentState);
// Deserialize into it
stateMachine.Deserialize(serialized);
Assert.AreEqual(stateB, stateMachine.CurrentState);
}
[Description("Custom State Base Subclasses")]
public static void CustomStateBaseSubclasses()
{
// Create a state machine where all states are CustomState (or subclasses)
var stateMachine = new StateMachine<CustomBaseState>();
CustomBaseState intiial = stateMachine.CreateInitialState("Initial");
// Properties on stateMachine refer to CustomStates
CustomBaseState currentState = stateMachine.CurrentState;
}
[Description("Custom Specific State Subclasses")]
public static void CustomSpecificStateSubclasses()
{
var stateMachine = new StateMachine();
CustomSpecificState normalInitial = stateMachine.CreateInitialState<CustomSpecificState>("Initial");
}
}
}
| 47.119247 | 136 | 0.61617 | [
"MIT"
] | edwincervantes/StateMechanic | Samples/Scenario3.cs | 22,046 | C# |
using System;
namespace SoftFluent.Windows
{
public interface ITypeResolver
{
Type ResolveType(string fullName, bool throwOnError);
}
}
| 15.8 | 61 | 0.696203 | [
"MIT"
] | SoftFluent/SoftFluent.Windows | SoftFluent.Windows/SoftFluent.Windows/ITypeResolver.cs | 160 | C# |
using System;
using AGXUnity;
using AGXUnity.Collide;
using UnityEditor;
namespace AGXUnityEditor.Editors
{
[CustomEditor( typeof( AGXUnity.Rendering.CableRenderer ) )]
[CanEditMultipleObjects]
public class AGXUnityRenderingCableRendererEditor : InspectorEditor
{ }
} | 21.307692 | 69 | 0.801444 | [
"Apache-2.0"
] | Algoryx/AGXUnity | Editor/CustomEditors/AGXUnity+Rendering+CableRendererEditor.cs | 277 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Dingtalkyida_1_0.Models
{
public class LoginCodeGenResponse : TeaModel {
[NameInMap("headers")]
[Validation(Required=true)]
public Dictionary<string, string> Headers { get; set; }
[NameInMap("body")]
[Validation(Required=true)]
public LoginCodeGenResponseBody Body { get; set; }
}
}
| 21.869565 | 63 | 0.673956 | [
"Apache-2.0"
] | aliyun/dingtalk-sdk | dingtalk/csharp/core/yida_1_0/Models/LoginCodeGenResponse.cs | 503 | C# |
using System;
namespace PodcastRadio.Core.Exceptions
{
public class NoInternetException : Exception
{
public NoInternetException() {}
public NoInternetException(string message) : base(message) {}
public NoInternetException(string message, Exception inner) : base(message, inner) {}
}
}
| 29.363636 | 93 | 0.702786 | [
"MIT"
] | joaowd/PodcastRadio | PodcastRadio.Core/Exceptions/NoInternetException.cs | 325 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by wsdl, Version=4.0.30319.17929.
//
namespace EbiWS.FastaWs {
using System;
using System.Web.Services;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.ComponentModel;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="JDispatcherServiceHttpBinding", Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class JDispatcherService : System.Web.Services.Protocols.SoapHttpClientProtocol {
private System.Threading.SendOrPostCallback runOperationCompleted;
private System.Threading.SendOrPostCallback getStatusOperationCompleted;
private System.Threading.SendOrPostCallback getResultTypesOperationCompleted;
private System.Threading.SendOrPostCallback getResultOperationCompleted;
private System.Threading.SendOrPostCallback getParametersOperationCompleted;
private System.Threading.SendOrPostCallback getParameterDetailsOperationCompleted;
/// <remarks/>
public JDispatcherService() {
this.Url = "http://www.ebi.ac.uk/Tools/services/soap/fasta";
}
/// <remarks/>
public event runCompletedEventHandler runCompleted;
/// <remarks/>
public event getStatusCompletedEventHandler getStatusCompleted;
/// <remarks/>
public event getResultTypesCompletedEventHandler getResultTypesCompleted;
/// <remarks/>
public event getResultCompletedEventHandler getResultCompleted;
/// <remarks/>
public event getParametersCompletedEventHandler getParametersCompleted;
/// <remarks/>
public event getParameterDetailsCompletedEventHandler getParameterDetailsCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:Run", RequestNamespace="http://soap.jdispatcher.ebi.ac.uk", ResponseNamespace="http://soap.jdispatcher.ebi.ac.uk", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("jobId", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string run([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string email, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)] string title, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] InputParameters parameters) {
object[] results = this.Invoke("run", new object[] {
email,
title,
parameters});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult Beginrun(string email, string title, InputParameters parameters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("run", new object[] {
email,
title,
parameters}, callback, asyncState);
}
/// <remarks/>
public string Endrun(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void runAsync(string email, string title, InputParameters parameters) {
this.runAsync(email, title, parameters, null);
}
/// <remarks/>
public void runAsync(string email, string title, InputParameters parameters, object userState) {
if ((this.runOperationCompleted == null)) {
this.runOperationCompleted = new System.Threading.SendOrPostCallback(this.OnrunOperationCompleted);
}
this.InvokeAsync("run", new object[] {
email,
title,
parameters}, this.runOperationCompleted, userState);
}
private void OnrunOperationCompleted(object arg) {
if ((this.runCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.runCompleted(this, new runCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:GetStatus", RequestNamespace="http://soap.jdispatcher.ebi.ac.uk", ResponseNamespace="http://soap.jdispatcher.ebi.ac.uk", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("status", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string getStatus([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string jobId) {
object[] results = this.Invoke("getStatus", new object[] {
jobId});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BegingetStatus(string jobId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("getStatus", new object[] {
jobId}, callback, asyncState);
}
/// <remarks/>
public string EndgetStatus(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void getStatusAsync(string jobId) {
this.getStatusAsync(jobId, null);
}
/// <remarks/>
public void getStatusAsync(string jobId, object userState) {
if ((this.getStatusOperationCompleted == null)) {
this.getStatusOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetStatusOperationCompleted);
}
this.InvokeAsync("getStatus", new object[] {
jobId}, this.getStatusOperationCompleted, userState);
}
private void OngetStatusOperationCompleted(object arg) {
if ((this.getStatusCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getStatusCompleted(this, new getStatusCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:GetResultTypes", RequestNamespace="http://soap.jdispatcher.ebi.ac.uk", ResponseNamespace="http://soap.jdispatcher.ebi.ac.uk", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlArrayAttribute("resultTypes", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[return: System.Xml.Serialization.XmlArrayItemAttribute("type", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public wsResultType[] getResultTypes([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string jobId) {
object[] results = this.Invoke("getResultTypes", new object[] {
jobId});
return ((wsResultType[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BegingetResultTypes(string jobId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("getResultTypes", new object[] {
jobId}, callback, asyncState);
}
/// <remarks/>
public wsResultType[] EndgetResultTypes(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((wsResultType[])(results[0]));
}
/// <remarks/>
public void getResultTypesAsync(string jobId) {
this.getResultTypesAsync(jobId, null);
}
/// <remarks/>
public void getResultTypesAsync(string jobId, object userState) {
if ((this.getResultTypesOperationCompleted == null)) {
this.getResultTypesOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetResultTypesOperationCompleted);
}
this.InvokeAsync("getResultTypes", new object[] {
jobId}, this.getResultTypesOperationCompleted, userState);
}
private void OngetResultTypesOperationCompleted(object arg) {
if ((this.getResultTypesCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getResultTypesCompleted(this, new getResultTypesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:GetResult", RequestNamespace="http://soap.jdispatcher.ebi.ac.uk", ResponseNamespace="http://soap.jdispatcher.ebi.ac.uk", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("output", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="base64Binary", IsNullable=true)]
public byte[] getResult([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string jobId, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string type, [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)] [System.Xml.Serialization.XmlArrayItemAttribute("parameter", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] wsRawOutputParameter[] parameters) {
object[] results = this.Invoke("getResult", new object[] {
jobId,
type,
parameters});
return ((byte[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BegingetResult(string jobId, string type, wsRawOutputParameter[] parameters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("getResult", new object[] {
jobId,
type,
parameters}, callback, asyncState);
}
/// <remarks/>
public byte[] EndgetResult(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((byte[])(results[0]));
}
/// <remarks/>
public void getResultAsync(string jobId, string type, wsRawOutputParameter[] parameters) {
this.getResultAsync(jobId, type, parameters, null);
}
/// <remarks/>
public void getResultAsync(string jobId, string type, wsRawOutputParameter[] parameters, object userState) {
if ((this.getResultOperationCompleted == null)) {
this.getResultOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetResultOperationCompleted);
}
this.InvokeAsync("getResult", new object[] {
jobId,
type,
parameters}, this.getResultOperationCompleted, userState);
}
private void OngetResultOperationCompleted(object arg) {
if ((this.getResultCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getResultCompleted(this, new getResultCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:GetParameters", RequestNamespace="http://soap.jdispatcher.ebi.ac.uk", ResponseNamespace="http://soap.jdispatcher.ebi.ac.uk", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlArrayAttribute("parameters", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[return: System.Xml.Serialization.XmlArrayItemAttribute("id", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public string[] getParameters() {
object[] results = this.Invoke("getParameters", new object[0]);
return ((string[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BegingetParameters(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("getParameters", new object[0], callback, asyncState);
}
/// <remarks/>
public string[] EndgetParameters(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string[])(results[0]));
}
/// <remarks/>
public void getParametersAsync() {
this.getParametersAsync(null);
}
/// <remarks/>
public void getParametersAsync(object userState) {
if ((this.getParametersOperationCompleted == null)) {
this.getParametersOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetParametersOperationCompleted);
}
this.InvokeAsync("getParameters", new object[0], this.getParametersOperationCompleted, userState);
}
private void OngetParametersOperationCompleted(object arg) {
if ((this.getParametersCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getParametersCompleted(this, new getParametersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:GetParameterDetails", RequestNamespace="http://soap.jdispatcher.ebi.ac.uk", ResponseNamespace="http://soap.jdispatcher.ebi.ac.uk", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("parameterDetails", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public wsParameterDetails getParameterDetails([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string parameterId) {
object[] results = this.Invoke("getParameterDetails", new object[] {
parameterId});
return ((wsParameterDetails)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BegingetParameterDetails(string parameterId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("getParameterDetails", new object[] {
parameterId}, callback, asyncState);
}
/// <remarks/>
public wsParameterDetails EndgetParameterDetails(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((wsParameterDetails)(results[0]));
}
/// <remarks/>
public void getParameterDetailsAsync(string parameterId) {
this.getParameterDetailsAsync(parameterId, null);
}
/// <remarks/>
public void getParameterDetailsAsync(string parameterId, object userState) {
if ((this.getParameterDetailsOperationCompleted == null)) {
this.getParameterDetailsOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetParameterDetailsOperationCompleted);
}
this.InvokeAsync("getParameterDetails", new object[] {
parameterId}, this.getParameterDetailsOperationCompleted, userState);
}
private void OngetParameterDetailsOperationCompleted(object arg) {
if ((this.getParameterDetailsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getParameterDetailsCompleted(this, new getParameterDetailsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class InputParameters {
private string programField;
private string stypeField;
private string matrixField;
private string match_scoresField;
private System.Nullable<int> gapopenField;
private bool gapopenFieldSpecified;
private System.Nullable<int> gapextField;
private bool gapextFieldSpecified;
private System.Nullable<bool> hspsField;
private bool hspsFieldSpecified;
private System.Nullable<double> expupperlimField;
private bool expupperlimFieldSpecified;
private System.Nullable<double> explowlimField;
private bool explowlimFieldSpecified;
private string strandField;
private System.Nullable<bool> histField;
private bool histFieldSpecified;
private System.Nullable<int> scoresField;
private bool scoresFieldSpecified;
private System.Nullable<int> alignmentsField;
private bool alignmentsFieldSpecified;
private string scoreformatField;
private string statsField;
private System.Nullable<bool> annotfeatsField;
private bool annotfeatsFieldSpecified;
private string annotsymField;
private string seqrangeField;
private string dbrangeField;
private string filterField;
private System.Nullable<int> transltableField;
private bool transltableFieldSpecified;
private string sequenceField;
private string[] databaseField;
private System.Nullable<int> ktupField;
private bool ktupFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string program {
get {
return this.programField;
}
set {
this.programField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string stype {
get {
return this.stypeField;
}
set {
this.stypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string matrix {
get {
return this.matrixField;
}
set {
this.matrixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string match_scores {
get {
return this.match_scoresField;
}
set {
this.match_scoresField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<int> gapopen {
get {
return this.gapopenField;
}
set {
this.gapopenField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool gapopenSpecified {
get {
return this.gapopenFieldSpecified;
}
set {
this.gapopenFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<int> gapext {
get {
return this.gapextField;
}
set {
this.gapextField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool gapextSpecified {
get {
return this.gapextFieldSpecified;
}
set {
this.gapextFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<bool> hsps {
get {
return this.hspsField;
}
set {
this.hspsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool hspsSpecified {
get {
return this.hspsFieldSpecified;
}
set {
this.hspsFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<double> expupperlim {
get {
return this.expupperlimField;
}
set {
this.expupperlimField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool expupperlimSpecified {
get {
return this.expupperlimFieldSpecified;
}
set {
this.expupperlimFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<double> explowlim {
get {
return this.explowlimField;
}
set {
this.explowlimField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool explowlimSpecified {
get {
return this.explowlimFieldSpecified;
}
set {
this.explowlimFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string strand {
get {
return this.strandField;
}
set {
this.strandField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<bool> hist {
get {
return this.histField;
}
set {
this.histField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool histSpecified {
get {
return this.histFieldSpecified;
}
set {
this.histFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<int> scores {
get {
return this.scoresField;
}
set {
this.scoresField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool scoresSpecified {
get {
return this.scoresFieldSpecified;
}
set {
this.scoresFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<int> alignments {
get {
return this.alignmentsField;
}
set {
this.alignmentsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool alignmentsSpecified {
get {
return this.alignmentsFieldSpecified;
}
set {
this.alignmentsFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string scoreformat {
get {
return this.scoreformatField;
}
set {
this.scoreformatField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string stats {
get {
return this.statsField;
}
set {
this.statsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<bool> annotfeats {
get {
return this.annotfeatsField;
}
set {
this.annotfeatsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool annotfeatsSpecified {
get {
return this.annotfeatsFieldSpecified;
}
set {
this.annotfeatsFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string annotsym {
get {
return this.annotsymField;
}
set {
this.annotsymField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string seqrange {
get {
return this.seqrangeField;
}
set {
this.seqrangeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string dbrange {
get {
return this.dbrangeField;
}
set {
this.dbrangeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string filter {
get {
return this.filterField;
}
set {
this.filterField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<int> transltable {
get {
return this.transltableField;
}
set {
this.transltableField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool transltableSpecified {
get {
return this.transltableFieldSpecified;
}
set {
this.transltableFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string sequence {
get {
return this.sequenceField;
}
set {
this.sequenceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string[] database {
get {
return this.databaseField;
}
set {
this.databaseField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public System.Nullable<int> ktup {
get {
return this.ktupField;
}
set {
this.ktupField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ktupSpecified {
get {
return this.ktupFieldSpecified;
}
set {
this.ktupFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class wsProperty {
private string keyField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string key {
get {
return this.keyField;
}
set {
this.keyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class wsParameterValue {
private string labelField;
private string valueField;
private bool defaultValueField;
private wsProperty[] propertiesField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string label {
get {
return this.labelField;
}
set {
this.labelField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public bool defaultValue {
get {
return this.defaultValueField;
}
set {
this.defaultValueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("property", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public wsProperty[] properties {
get {
return this.propertiesField;
}
set {
this.propertiesField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class wsParameterDetails {
private string nameField;
private string descriptionField;
private string typeField;
private wsParameterValue[] valuesField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string description {
get {
return this.descriptionField;
}
set {
this.descriptionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("value", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public wsParameterValue[] values {
get {
return this.valuesField;
}
set {
this.valuesField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class wsRawOutputParameter {
private string nameField;
private string[] valueField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string[] value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://soap.jdispatcher.ebi.ac.uk")]
public partial class wsResultType {
private string descriptionField;
private string fileSuffixField;
private string identifierField;
private string labelField;
private string mediaTypeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string description {
get {
return this.descriptionField;
}
set {
this.descriptionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string fileSuffix {
get {
return this.fileSuffixField;
}
set {
this.fileSuffixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string identifier {
get {
return this.identifierField;
}
set {
this.identifierField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public string label {
get {
return this.labelField;
}
set {
this.labelField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string mediaType {
get {
return this.mediaTypeField;
}
set {
this.mediaTypeField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
public delegate void runCompletedEventHandler(object sender, runCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class runCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal runCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
public delegate void getStatusCompletedEventHandler(object sender, getStatusCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getStatusCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getStatusCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
public delegate void getResultTypesCompletedEventHandler(object sender, getResultTypesCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getResultTypesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getResultTypesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public wsResultType[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((wsResultType[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
public delegate void getResultCompletedEventHandler(object sender, getResultCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getResultCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getResultCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public byte[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((byte[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
public delegate void getParametersCompletedEventHandler(object sender, getParametersCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getParametersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getParametersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((string[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
public delegate void getParameterDetailsCompletedEventHandler(object sender, getParameterDetailsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.17929")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class getParameterDetailsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal getParameterDetailsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public wsParameterDetails Result {
get {
this.RaiseExceptionIfNecessary();
return ((wsParameterDetails)(this.results[0]));
}
}
}
}
| 38.924837 | 531 | 0.592205 | [
"Apache-2.0"
] | SamFent/webservice-clients | deprecated/csharp/EBIWS2_CSharp/EbiWS/WebReferences/FastaWs/Reference.cs | 47,646 | 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 auditmanager-2017-07-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.AuditManager.Model;
namespace Amazon.AuditManager
{
/// <summary>
/// Interface for accessing AuditManager
///
/// Welcome to the AWS Audit Manager API reference. This guide is for developers who need
/// detailed information about the AWS Audit Manager API operations, data types, and errors.
///
///
///
/// <para>
/// AWS Audit Manager is a service that provides automated evidence collection so that
/// you can continuously audit your AWS usage, and assess the effectiveness of your controls
/// to better manage risk and simplify compliance.
/// </para>
///
/// <para>
/// AWS Audit Manager provides pre-built frameworks that structure and automate assessments
/// for a given compliance standard. Frameworks include a pre-built collection of controls
/// with descriptions and testing procedures, which are grouped according to the requirements
/// of the specified compliance standard or regulation. You can also customize frameworks
/// and controls to support internal audits with unique requirements.
/// </para>
///
/// <para>
/// Use the following links to get started with the AWS Audit Manager API:
/// </para>
/// <ul> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Operations.html">Actions</a>:
/// An alphabetical list of all AWS Audit Manager API operations.
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/API_Types.html">Data
/// types</a>: An alphabetical list of all AWS Audit Manager data types.
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonParameters.html">Common
/// parameters</a>: Parameters that all Query operations can use.
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/audit-manager/latest/APIReference/CommonErrors.html">Common
/// errors</a>: Client and server errors that all operations can return.
/// </para>
/// </li> </ul>
/// <para>
/// If you're new to AWS Audit Manager, we recommend that you review the <a href="https://docs.aws.amazon.com/audit-manager/latest/userguide/what-is.html">
/// AWS Audit Manager User Guide</a>.
/// </para>
/// </summary>
public partial interface IAmazonAuditManager : IAmazonService, IDisposable
{
#if BCL45 || AWS_ASYNC_ENUMERABLES_API
/// <summary>
/// Paginators for the service
/// </summary>
IAuditManagerPaginatorFactory Paginators { get; }
#endif
#region AssociateAssessmentReportEvidenceFolder
/// <summary>
/// Associates an evidence folder to the specified assessment report in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateAssessmentReportEvidenceFolder service method.</param>
///
/// <returns>The response from the AssociateAssessmentReportEvidenceFolder service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder">REST API Reference for AssociateAssessmentReportEvidenceFolder Operation</seealso>
AssociateAssessmentReportEvidenceFolderResponse AssociateAssessmentReportEvidenceFolder(AssociateAssessmentReportEvidenceFolderRequest request);
/// <summary>
/// Initiates the asynchronous execution of the AssociateAssessmentReportEvidenceFolder operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AssociateAssessmentReportEvidenceFolder operation on AmazonAuditManagerClient.</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 EndAssociateAssessmentReportEvidenceFolder
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder">REST API Reference for AssociateAssessmentReportEvidenceFolder Operation</seealso>
IAsyncResult BeginAssociateAssessmentReportEvidenceFolder(AssociateAssessmentReportEvidenceFolderRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the AssociateAssessmentReportEvidenceFolder operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAssociateAssessmentReportEvidenceFolder.</param>
///
/// <returns>Returns a AssociateAssessmentReportEvidenceFolderResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder">REST API Reference for AssociateAssessmentReportEvidenceFolder Operation</seealso>
AssociateAssessmentReportEvidenceFolderResponse EndAssociateAssessmentReportEvidenceFolder(IAsyncResult asyncResult);
#endregion
#region BatchAssociateAssessmentReportEvidence
/// <summary>
/// Associates a list of evidence to an assessment report in an AWS Audit Manager assessment.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchAssociateAssessmentReportEvidence service method.</param>
///
/// <returns>The response from the BatchAssociateAssessmentReportEvidence service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchAssociateAssessmentReportEvidence">REST API Reference for BatchAssociateAssessmentReportEvidence Operation</seealso>
BatchAssociateAssessmentReportEvidenceResponse BatchAssociateAssessmentReportEvidence(BatchAssociateAssessmentReportEvidenceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the BatchAssociateAssessmentReportEvidence operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchAssociateAssessmentReportEvidence operation on AmazonAuditManagerClient.</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 EndBatchAssociateAssessmentReportEvidence
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchAssociateAssessmentReportEvidence">REST API Reference for BatchAssociateAssessmentReportEvidence Operation</seealso>
IAsyncResult BeginBatchAssociateAssessmentReportEvidence(BatchAssociateAssessmentReportEvidenceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the BatchAssociateAssessmentReportEvidence operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchAssociateAssessmentReportEvidence.</param>
///
/// <returns>Returns a BatchAssociateAssessmentReportEvidenceResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchAssociateAssessmentReportEvidence">REST API Reference for BatchAssociateAssessmentReportEvidence Operation</seealso>
BatchAssociateAssessmentReportEvidenceResponse EndBatchAssociateAssessmentReportEvidence(IAsyncResult asyncResult);
#endregion
#region BatchCreateDelegationByAssessment
/// <summary>
/// Create a batch of delegations for a specified assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchCreateDelegationByAssessment service method.</param>
///
/// <returns>The response from the BatchCreateDelegationByAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessment">REST API Reference for BatchCreateDelegationByAssessment Operation</seealso>
BatchCreateDelegationByAssessmentResponse BatchCreateDelegationByAssessment(BatchCreateDelegationByAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the BatchCreateDelegationByAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchCreateDelegationByAssessment operation on AmazonAuditManagerClient.</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 EndBatchCreateDelegationByAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessment">REST API Reference for BatchCreateDelegationByAssessment Operation</seealso>
IAsyncResult BeginBatchCreateDelegationByAssessment(BatchCreateDelegationByAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the BatchCreateDelegationByAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchCreateDelegationByAssessment.</param>
///
/// <returns>Returns a BatchCreateDelegationByAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessment">REST API Reference for BatchCreateDelegationByAssessment Operation</seealso>
BatchCreateDelegationByAssessmentResponse EndBatchCreateDelegationByAssessment(IAsyncResult asyncResult);
#endregion
#region BatchDeleteDelegationByAssessment
/// <summary>
/// Deletes the delegations in the specified AWS Audit Manager assessment.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchDeleteDelegationByAssessment service method.</param>
///
/// <returns>The response from the BatchDeleteDelegationByAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDeleteDelegationByAssessment">REST API Reference for BatchDeleteDelegationByAssessment Operation</seealso>
BatchDeleteDelegationByAssessmentResponse BatchDeleteDelegationByAssessment(BatchDeleteDelegationByAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the BatchDeleteDelegationByAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchDeleteDelegationByAssessment operation on AmazonAuditManagerClient.</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 EndBatchDeleteDelegationByAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDeleteDelegationByAssessment">REST API Reference for BatchDeleteDelegationByAssessment Operation</seealso>
IAsyncResult BeginBatchDeleteDelegationByAssessment(BatchDeleteDelegationByAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the BatchDeleteDelegationByAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchDeleteDelegationByAssessment.</param>
///
/// <returns>Returns a BatchDeleteDelegationByAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDeleteDelegationByAssessment">REST API Reference for BatchDeleteDelegationByAssessment Operation</seealso>
BatchDeleteDelegationByAssessmentResponse EndBatchDeleteDelegationByAssessment(IAsyncResult asyncResult);
#endregion
#region BatchDisassociateAssessmentReportEvidence
/// <summary>
/// Disassociates a list of evidence from the specified assessment report in AWS Audit
/// Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchDisassociateAssessmentReportEvidence service method.</param>
///
/// <returns>The response from the BatchDisassociateAssessmentReportEvidence service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence">REST API Reference for BatchDisassociateAssessmentReportEvidence Operation</seealso>
BatchDisassociateAssessmentReportEvidenceResponse BatchDisassociateAssessmentReportEvidence(BatchDisassociateAssessmentReportEvidenceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the BatchDisassociateAssessmentReportEvidence operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchDisassociateAssessmentReportEvidence operation on AmazonAuditManagerClient.</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 EndBatchDisassociateAssessmentReportEvidence
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence">REST API Reference for BatchDisassociateAssessmentReportEvidence Operation</seealso>
IAsyncResult BeginBatchDisassociateAssessmentReportEvidence(BatchDisassociateAssessmentReportEvidenceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the BatchDisassociateAssessmentReportEvidence operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchDisassociateAssessmentReportEvidence.</param>
///
/// <returns>Returns a BatchDisassociateAssessmentReportEvidenceResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence">REST API Reference for BatchDisassociateAssessmentReportEvidence Operation</seealso>
BatchDisassociateAssessmentReportEvidenceResponse EndBatchDisassociateAssessmentReportEvidence(IAsyncResult asyncResult);
#endregion
#region BatchImportEvidenceToAssessmentControl
/// <summary>
/// Uploads one or more pieces of evidence to the specified control in the assessment
/// in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchImportEvidenceToAssessmentControl service method.</param>
///
/// <returns>The response from the BatchImportEvidenceToAssessmentControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchImportEvidenceToAssessmentControl">REST API Reference for BatchImportEvidenceToAssessmentControl Operation</seealso>
BatchImportEvidenceToAssessmentControlResponse BatchImportEvidenceToAssessmentControl(BatchImportEvidenceToAssessmentControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the BatchImportEvidenceToAssessmentControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchImportEvidenceToAssessmentControl operation on AmazonAuditManagerClient.</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 EndBatchImportEvidenceToAssessmentControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchImportEvidenceToAssessmentControl">REST API Reference for BatchImportEvidenceToAssessmentControl Operation</seealso>
IAsyncResult BeginBatchImportEvidenceToAssessmentControl(BatchImportEvidenceToAssessmentControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the BatchImportEvidenceToAssessmentControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchImportEvidenceToAssessmentControl.</param>
///
/// <returns>Returns a BatchImportEvidenceToAssessmentControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchImportEvidenceToAssessmentControl">REST API Reference for BatchImportEvidenceToAssessmentControl Operation</seealso>
BatchImportEvidenceToAssessmentControlResponse EndBatchImportEvidenceToAssessmentControl(IAsyncResult asyncResult);
#endregion
#region CreateAssessment
/// <summary>
/// Creates an assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAssessment service method.</param>
///
/// <returns>The response from the CreateAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessment">REST API Reference for CreateAssessment Operation</seealso>
CreateAssessmentResponse CreateAssessment(CreateAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAssessment operation on AmazonAuditManagerClient.</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 EndCreateAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessment">REST API Reference for CreateAssessment Operation</seealso>
IAsyncResult BeginCreateAssessment(CreateAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAssessment.</param>
///
/// <returns>Returns a CreateAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessment">REST API Reference for CreateAssessment Operation</seealso>
CreateAssessmentResponse EndCreateAssessment(IAsyncResult asyncResult);
#endregion
#region CreateAssessmentFramework
/// <summary>
/// Creates a custom framework in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAssessmentFramework service method.</param>
///
/// <returns>The response from the CreateAssessmentFramework service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentFramework">REST API Reference for CreateAssessmentFramework Operation</seealso>
CreateAssessmentFrameworkResponse CreateAssessmentFramework(CreateAssessmentFrameworkRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateAssessmentFramework operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAssessmentFramework operation on AmazonAuditManagerClient.</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 EndCreateAssessmentFramework
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentFramework">REST API Reference for CreateAssessmentFramework Operation</seealso>
IAsyncResult BeginCreateAssessmentFramework(CreateAssessmentFrameworkRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateAssessmentFramework operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAssessmentFramework.</param>
///
/// <returns>Returns a CreateAssessmentFrameworkResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentFramework">REST API Reference for CreateAssessmentFramework Operation</seealso>
CreateAssessmentFrameworkResponse EndCreateAssessmentFramework(IAsyncResult asyncResult);
#endregion
#region CreateAssessmentReport
/// <summary>
/// Creates an assessment report for the specified assessment.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAssessmentReport service method.</param>
///
/// <returns>The response from the CreateAssessmentReport service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentReport">REST API Reference for CreateAssessmentReport Operation</seealso>
CreateAssessmentReportResponse CreateAssessmentReport(CreateAssessmentReportRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateAssessmentReport operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAssessmentReport operation on AmazonAuditManagerClient.</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 EndCreateAssessmentReport
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentReport">REST API Reference for CreateAssessmentReport Operation</seealso>
IAsyncResult BeginCreateAssessmentReport(CreateAssessmentReportRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateAssessmentReport operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAssessmentReport.</param>
///
/// <returns>Returns a CreateAssessmentReportResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateAssessmentReport">REST API Reference for CreateAssessmentReport Operation</seealso>
CreateAssessmentReportResponse EndCreateAssessmentReport(IAsyncResult asyncResult);
#endregion
#region CreateControl
/// <summary>
/// Creates a new custom control in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateControl service method.</param>
///
/// <returns>The response from the CreateControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControl">REST API Reference for CreateControl Operation</seealso>
CreateControlResponse CreateControl(CreateControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateControl operation on AmazonAuditManagerClient.</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 EndCreateControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControl">REST API Reference for CreateControl Operation</seealso>
IAsyncResult BeginCreateControl(CreateControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateControl.</param>
///
/// <returns>Returns a CreateControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/CreateControl">REST API Reference for CreateControl Operation</seealso>
CreateControlResponse EndCreateControl(IAsyncResult asyncResult);
#endregion
#region DeleteAssessment
/// <summary>
/// Deletes an assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteAssessment service method.</param>
///
/// <returns>The response from the DeleteAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessment">REST API Reference for DeleteAssessment Operation</seealso>
DeleteAssessmentResponse DeleteAssessment(DeleteAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteAssessment operation on AmazonAuditManagerClient.</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 EndDeleteAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessment">REST API Reference for DeleteAssessment Operation</seealso>
IAsyncResult BeginDeleteAssessment(DeleteAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAssessment.</param>
///
/// <returns>Returns a DeleteAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessment">REST API Reference for DeleteAssessment Operation</seealso>
DeleteAssessmentResponse EndDeleteAssessment(IAsyncResult asyncResult);
#endregion
#region DeleteAssessmentFramework
/// <summary>
/// Deletes a custom framework in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentFramework service method.</param>
///
/// <returns>The response from the DeleteAssessmentFramework service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFramework">REST API Reference for DeleteAssessmentFramework Operation</seealso>
DeleteAssessmentFrameworkResponse DeleteAssessmentFramework(DeleteAssessmentFrameworkRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteAssessmentFramework operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentFramework operation on AmazonAuditManagerClient.</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 EndDeleteAssessmentFramework
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFramework">REST API Reference for DeleteAssessmentFramework Operation</seealso>
IAsyncResult BeginDeleteAssessmentFramework(DeleteAssessmentFrameworkRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteAssessmentFramework operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAssessmentFramework.</param>
///
/// <returns>Returns a DeleteAssessmentFrameworkResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentFramework">REST API Reference for DeleteAssessmentFramework Operation</seealso>
DeleteAssessmentFrameworkResponse EndDeleteAssessmentFramework(IAsyncResult asyncResult);
#endregion
#region DeleteAssessmentReport
/// <summary>
/// Deletes an assessment report from an assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentReport service method.</param>
///
/// <returns>The response from the DeleteAssessmentReport service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentReport">REST API Reference for DeleteAssessmentReport Operation</seealso>
DeleteAssessmentReportResponse DeleteAssessmentReport(DeleteAssessmentReportRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteAssessmentReport operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteAssessmentReport operation on AmazonAuditManagerClient.</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 EndDeleteAssessmentReport
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentReport">REST API Reference for DeleteAssessmentReport Operation</seealso>
IAsyncResult BeginDeleteAssessmentReport(DeleteAssessmentReportRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteAssessmentReport operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAssessmentReport.</param>
///
/// <returns>Returns a DeleteAssessmentReportResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteAssessmentReport">REST API Reference for DeleteAssessmentReport Operation</seealso>
DeleteAssessmentReportResponse EndDeleteAssessmentReport(IAsyncResult asyncResult);
#endregion
#region DeleteControl
/// <summary>
/// Deletes a custom control in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteControl service method.</param>
///
/// <returns>The response from the DeleteControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteControl">REST API Reference for DeleteControl Operation</seealso>
DeleteControlResponse DeleteControl(DeleteControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteControl operation on AmazonAuditManagerClient.</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 EndDeleteControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteControl">REST API Reference for DeleteControl Operation</seealso>
IAsyncResult BeginDeleteControl(DeleteControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteControl.</param>
///
/// <returns>Returns a DeleteControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeleteControl">REST API Reference for DeleteControl Operation</seealso>
DeleteControlResponse EndDeleteControl(IAsyncResult asyncResult);
#endregion
#region DeregisterAccount
/// <summary>
/// Deregisters an account in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeregisterAccount service method.</param>
///
/// <returns>The response from the DeregisterAccount service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterAccount">REST API Reference for DeregisterAccount Operation</seealso>
DeregisterAccountResponse DeregisterAccount(DeregisterAccountRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeregisterAccount operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeregisterAccount operation on AmazonAuditManagerClient.</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 EndDeregisterAccount
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterAccount">REST API Reference for DeregisterAccount Operation</seealso>
IAsyncResult BeginDeregisterAccount(DeregisterAccountRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeregisterAccount operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeregisterAccount.</param>
///
/// <returns>Returns a DeregisterAccountResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterAccount">REST API Reference for DeregisterAccount Operation</seealso>
DeregisterAccountResponse EndDeregisterAccount(IAsyncResult asyncResult);
#endregion
#region DeregisterOrganizationAdminAccount
/// <summary>
/// Deregisters the delegated AWS administrator account from the AWS organization.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeregisterOrganizationAdminAccount service method.</param>
///
/// <returns>The response from the DeregisterOrganizationAdminAccount service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterOrganizationAdminAccount">REST API Reference for DeregisterOrganizationAdminAccount Operation</seealso>
DeregisterOrganizationAdminAccountResponse DeregisterOrganizationAdminAccount(DeregisterOrganizationAdminAccountRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeregisterOrganizationAdminAccount operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeregisterOrganizationAdminAccount operation on AmazonAuditManagerClient.</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 EndDeregisterOrganizationAdminAccount
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterOrganizationAdminAccount">REST API Reference for DeregisterOrganizationAdminAccount Operation</seealso>
IAsyncResult BeginDeregisterOrganizationAdminAccount(DeregisterOrganizationAdminAccountRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeregisterOrganizationAdminAccount operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeregisterOrganizationAdminAccount.</param>
///
/// <returns>Returns a DeregisterOrganizationAdminAccountResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DeregisterOrganizationAdminAccount">REST API Reference for DeregisterOrganizationAdminAccount Operation</seealso>
DeregisterOrganizationAdminAccountResponse EndDeregisterOrganizationAdminAccount(IAsyncResult asyncResult);
#endregion
#region DisassociateAssessmentReportEvidenceFolder
/// <summary>
/// Disassociates an evidence folder from the specified assessment report in AWS Audit
/// Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisassociateAssessmentReportEvidenceFolder service method.</param>
///
/// <returns>The response from the DisassociateAssessmentReportEvidenceFolder service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder">REST API Reference for DisassociateAssessmentReportEvidenceFolder Operation</seealso>
DisassociateAssessmentReportEvidenceFolderResponse DisassociateAssessmentReportEvidenceFolder(DisassociateAssessmentReportEvidenceFolderRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DisassociateAssessmentReportEvidenceFolder operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisassociateAssessmentReportEvidenceFolder operation on AmazonAuditManagerClient.</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 EndDisassociateAssessmentReportEvidenceFolder
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder">REST API Reference for DisassociateAssessmentReportEvidenceFolder Operation</seealso>
IAsyncResult BeginDisassociateAssessmentReportEvidenceFolder(DisassociateAssessmentReportEvidenceFolderRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DisassociateAssessmentReportEvidenceFolder operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisassociateAssessmentReportEvidenceFolder.</param>
///
/// <returns>Returns a DisassociateAssessmentReportEvidenceFolderResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder">REST API Reference for DisassociateAssessmentReportEvidenceFolder Operation</seealso>
DisassociateAssessmentReportEvidenceFolderResponse EndDisassociateAssessmentReportEvidenceFolder(IAsyncResult asyncResult);
#endregion
#region GetAccountStatus
/// <summary>
/// Returns the registration status of an account in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAccountStatus service method.</param>
///
/// <returns>The response from the GetAccountStatus service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAccountStatus">REST API Reference for GetAccountStatus Operation</seealso>
GetAccountStatusResponse GetAccountStatus(GetAccountStatusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetAccountStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAccountStatus operation on AmazonAuditManagerClient.</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 EndGetAccountStatus
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAccountStatus">REST API Reference for GetAccountStatus Operation</seealso>
IAsyncResult BeginGetAccountStatus(GetAccountStatusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetAccountStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAccountStatus.</param>
///
/// <returns>Returns a GetAccountStatusResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAccountStatus">REST API Reference for GetAccountStatus Operation</seealso>
GetAccountStatusResponse EndGetAccountStatus(IAsyncResult asyncResult);
#endregion
#region GetAssessment
/// <summary>
/// Returns an assessment from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAssessment service method.</param>
///
/// <returns>The response from the GetAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessment">REST API Reference for GetAssessment Operation</seealso>
GetAssessmentResponse GetAssessment(GetAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAssessment operation on AmazonAuditManagerClient.</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 EndGetAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessment">REST API Reference for GetAssessment Operation</seealso>
IAsyncResult BeginGetAssessment(GetAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAssessment.</param>
///
/// <returns>Returns a GetAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessment">REST API Reference for GetAssessment Operation</seealso>
GetAssessmentResponse EndGetAssessment(IAsyncResult asyncResult);
#endregion
#region GetAssessmentFramework
/// <summary>
/// Returns a framework from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAssessmentFramework service method.</param>
///
/// <returns>The response from the GetAssessmentFramework service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentFramework">REST API Reference for GetAssessmentFramework Operation</seealso>
GetAssessmentFrameworkResponse GetAssessmentFramework(GetAssessmentFrameworkRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetAssessmentFramework operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAssessmentFramework operation on AmazonAuditManagerClient.</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 EndGetAssessmentFramework
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentFramework">REST API Reference for GetAssessmentFramework Operation</seealso>
IAsyncResult BeginGetAssessmentFramework(GetAssessmentFrameworkRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetAssessmentFramework operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAssessmentFramework.</param>
///
/// <returns>Returns a GetAssessmentFrameworkResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentFramework">REST API Reference for GetAssessmentFramework Operation</seealso>
GetAssessmentFrameworkResponse EndGetAssessmentFramework(IAsyncResult asyncResult);
#endregion
#region GetAssessmentReportUrl
/// <summary>
/// Returns the URL of a specified assessment report in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAssessmentReportUrl service method.</param>
///
/// <returns>The response from the GetAssessmentReportUrl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentReportUrl">REST API Reference for GetAssessmentReportUrl Operation</seealso>
GetAssessmentReportUrlResponse GetAssessmentReportUrl(GetAssessmentReportUrlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetAssessmentReportUrl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAssessmentReportUrl operation on AmazonAuditManagerClient.</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 EndGetAssessmentReportUrl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentReportUrl">REST API Reference for GetAssessmentReportUrl Operation</seealso>
IAsyncResult BeginGetAssessmentReportUrl(GetAssessmentReportUrlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetAssessmentReportUrl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAssessmentReportUrl.</param>
///
/// <returns>Returns a GetAssessmentReportUrlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetAssessmentReportUrl">REST API Reference for GetAssessmentReportUrl Operation</seealso>
GetAssessmentReportUrlResponse EndGetAssessmentReportUrl(IAsyncResult asyncResult);
#endregion
#region GetChangeLogs
/// <summary>
/// Returns a list of changelogs from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetChangeLogs service method.</param>
///
/// <returns>The response from the GetChangeLogs service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetChangeLogs">REST API Reference for GetChangeLogs Operation</seealso>
GetChangeLogsResponse GetChangeLogs(GetChangeLogsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetChangeLogs operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetChangeLogs operation on AmazonAuditManagerClient.</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 EndGetChangeLogs
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetChangeLogs">REST API Reference for GetChangeLogs Operation</seealso>
IAsyncResult BeginGetChangeLogs(GetChangeLogsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetChangeLogs operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetChangeLogs.</param>
///
/// <returns>Returns a GetChangeLogsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetChangeLogs">REST API Reference for GetChangeLogs Operation</seealso>
GetChangeLogsResponse EndGetChangeLogs(IAsyncResult asyncResult);
#endregion
#region GetControl
/// <summary>
/// Returns a control from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetControl service method.</param>
///
/// <returns>The response from the GetControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetControl">REST API Reference for GetControl Operation</seealso>
GetControlResponse GetControl(GetControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetControl operation on AmazonAuditManagerClient.</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 EndGetControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetControl">REST API Reference for GetControl Operation</seealso>
IAsyncResult BeginGetControl(GetControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetControl.</param>
///
/// <returns>Returns a GetControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetControl">REST API Reference for GetControl Operation</seealso>
GetControlResponse EndGetControl(IAsyncResult asyncResult);
#endregion
#region GetDelegations
/// <summary>
/// Returns a list of delegations from an audit owner to a delegate.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetDelegations service method.</param>
///
/// <returns>The response from the GetDelegations service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetDelegations">REST API Reference for GetDelegations Operation</seealso>
GetDelegationsResponse GetDelegations(GetDelegationsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetDelegations operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDelegations operation on AmazonAuditManagerClient.</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 EndGetDelegations
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetDelegations">REST API Reference for GetDelegations Operation</seealso>
IAsyncResult BeginGetDelegations(GetDelegationsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetDelegations operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetDelegations.</param>
///
/// <returns>Returns a GetDelegationsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetDelegations">REST API Reference for GetDelegations Operation</seealso>
GetDelegationsResponse EndGetDelegations(IAsyncResult asyncResult);
#endregion
#region GetEvidence
/// <summary>
/// Returns evidence from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEvidence service method.</param>
///
/// <returns>The response from the GetEvidence service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidence">REST API Reference for GetEvidence Operation</seealso>
GetEvidenceResponse GetEvidence(GetEvidenceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetEvidence operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetEvidence operation on AmazonAuditManagerClient.</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 EndGetEvidence
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidence">REST API Reference for GetEvidence Operation</seealso>
IAsyncResult BeginGetEvidence(GetEvidenceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetEvidence operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetEvidence.</param>
///
/// <returns>Returns a GetEvidenceResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidence">REST API Reference for GetEvidence Operation</seealso>
GetEvidenceResponse EndGetEvidence(IAsyncResult asyncResult);
#endregion
#region GetEvidenceByEvidenceFolder
/// <summary>
/// Returns all evidence from a specified evidence folder in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceByEvidenceFolder service method.</param>
///
/// <returns>The response from the GetEvidenceByEvidenceFolder service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder">REST API Reference for GetEvidenceByEvidenceFolder Operation</seealso>
GetEvidenceByEvidenceFolderResponse GetEvidenceByEvidenceFolder(GetEvidenceByEvidenceFolderRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetEvidenceByEvidenceFolder operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceByEvidenceFolder operation on AmazonAuditManagerClient.</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 EndGetEvidenceByEvidenceFolder
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder">REST API Reference for GetEvidenceByEvidenceFolder Operation</seealso>
IAsyncResult BeginGetEvidenceByEvidenceFolder(GetEvidenceByEvidenceFolderRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetEvidenceByEvidenceFolder operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetEvidenceByEvidenceFolder.</param>
///
/// <returns>Returns a GetEvidenceByEvidenceFolderResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder">REST API Reference for GetEvidenceByEvidenceFolder Operation</seealso>
GetEvidenceByEvidenceFolderResponse EndGetEvidenceByEvidenceFolder(IAsyncResult asyncResult);
#endregion
#region GetEvidenceFolder
/// <summary>
/// Returns an evidence folder from the specified assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceFolder service method.</param>
///
/// <returns>The response from the GetEvidenceFolder service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFolder">REST API Reference for GetEvidenceFolder Operation</seealso>
GetEvidenceFolderResponse GetEvidenceFolder(GetEvidenceFolderRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetEvidenceFolder operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceFolder operation on AmazonAuditManagerClient.</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 EndGetEvidenceFolder
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFolder">REST API Reference for GetEvidenceFolder Operation</seealso>
IAsyncResult BeginGetEvidenceFolder(GetEvidenceFolderRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetEvidenceFolder operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetEvidenceFolder.</param>
///
/// <returns>Returns a GetEvidenceFolderResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFolder">REST API Reference for GetEvidenceFolder Operation</seealso>
GetEvidenceFolderResponse EndGetEvidenceFolder(IAsyncResult asyncResult);
#endregion
#region GetEvidenceFoldersByAssessment
/// <summary>
/// Returns the evidence folders from a specified assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceFoldersByAssessment service method.</param>
///
/// <returns>The response from the GetEvidenceFoldersByAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment">REST API Reference for GetEvidenceFoldersByAssessment Operation</seealso>
GetEvidenceFoldersByAssessmentResponse GetEvidenceFoldersByAssessment(GetEvidenceFoldersByAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetEvidenceFoldersByAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceFoldersByAssessment operation on AmazonAuditManagerClient.</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 EndGetEvidenceFoldersByAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment">REST API Reference for GetEvidenceFoldersByAssessment Operation</seealso>
IAsyncResult BeginGetEvidenceFoldersByAssessment(GetEvidenceFoldersByAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetEvidenceFoldersByAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetEvidenceFoldersByAssessment.</param>
///
/// <returns>Returns a GetEvidenceFoldersByAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment">REST API Reference for GetEvidenceFoldersByAssessment Operation</seealso>
GetEvidenceFoldersByAssessmentResponse EndGetEvidenceFoldersByAssessment(IAsyncResult asyncResult);
#endregion
#region GetEvidenceFoldersByAssessmentControl
/// <summary>
/// Returns a list of evidence folders associated with a specified control of an assessment
/// in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceFoldersByAssessmentControl service method.</param>
///
/// <returns>The response from the GetEvidenceFoldersByAssessmentControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessmentControl">REST API Reference for GetEvidenceFoldersByAssessmentControl Operation</seealso>
GetEvidenceFoldersByAssessmentControlResponse GetEvidenceFoldersByAssessmentControl(GetEvidenceFoldersByAssessmentControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetEvidenceFoldersByAssessmentControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetEvidenceFoldersByAssessmentControl operation on AmazonAuditManagerClient.</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 EndGetEvidenceFoldersByAssessmentControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessmentControl">REST API Reference for GetEvidenceFoldersByAssessmentControl Operation</seealso>
IAsyncResult BeginGetEvidenceFoldersByAssessmentControl(GetEvidenceFoldersByAssessmentControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetEvidenceFoldersByAssessmentControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetEvidenceFoldersByAssessmentControl.</param>
///
/// <returns>Returns a GetEvidenceFoldersByAssessmentControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetEvidenceFoldersByAssessmentControl">REST API Reference for GetEvidenceFoldersByAssessmentControl Operation</seealso>
GetEvidenceFoldersByAssessmentControlResponse EndGetEvidenceFoldersByAssessmentControl(IAsyncResult asyncResult);
#endregion
#region GetOrganizationAdminAccount
/// <summary>
/// Returns the name of the delegated AWS administrator account for the AWS organization.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetOrganizationAdminAccount service method.</param>
///
/// <returns>The response from the GetOrganizationAdminAccount service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetOrganizationAdminAccount">REST API Reference for GetOrganizationAdminAccount Operation</seealso>
GetOrganizationAdminAccountResponse GetOrganizationAdminAccount(GetOrganizationAdminAccountRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetOrganizationAdminAccount operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetOrganizationAdminAccount operation on AmazonAuditManagerClient.</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 EndGetOrganizationAdminAccount
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetOrganizationAdminAccount">REST API Reference for GetOrganizationAdminAccount Operation</seealso>
IAsyncResult BeginGetOrganizationAdminAccount(GetOrganizationAdminAccountRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetOrganizationAdminAccount operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetOrganizationAdminAccount.</param>
///
/// <returns>Returns a GetOrganizationAdminAccountResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetOrganizationAdminAccount">REST API Reference for GetOrganizationAdminAccount Operation</seealso>
GetOrganizationAdminAccountResponse EndGetOrganizationAdminAccount(IAsyncResult asyncResult);
#endregion
#region GetServicesInScope
/// <summary>
/// Returns a list of the in-scope AWS services for the specified assessment.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetServicesInScope service method.</param>
///
/// <returns>The response from the GetServicesInScope service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetServicesInScope">REST API Reference for GetServicesInScope Operation</seealso>
GetServicesInScopeResponse GetServicesInScope(GetServicesInScopeRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetServicesInScope operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetServicesInScope operation on AmazonAuditManagerClient.</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 EndGetServicesInScope
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetServicesInScope">REST API Reference for GetServicesInScope Operation</seealso>
IAsyncResult BeginGetServicesInScope(GetServicesInScopeRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetServicesInScope operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetServicesInScope.</param>
///
/// <returns>Returns a GetServicesInScopeResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetServicesInScope">REST API Reference for GetServicesInScope Operation</seealso>
GetServicesInScopeResponse EndGetServicesInScope(IAsyncResult asyncResult);
#endregion
#region GetSettings
/// <summary>
/// Returns the settings for the specified AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetSettings service method.</param>
///
/// <returns>The response from the GetSettings service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetSettings">REST API Reference for GetSettings Operation</seealso>
GetSettingsResponse GetSettings(GetSettingsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetSettings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSettings operation on AmazonAuditManagerClient.</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 EndGetSettings
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetSettings">REST API Reference for GetSettings Operation</seealso>
IAsyncResult BeginGetSettings(GetSettingsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the GetSettings operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSettings.</param>
///
/// <returns>Returns a GetSettingsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/GetSettings">REST API Reference for GetSettings Operation</seealso>
GetSettingsResponse EndGetSettings(IAsyncResult asyncResult);
#endregion
#region ListAssessmentFrameworks
/// <summary>
/// Returns a list of the frameworks available in the AWS Audit Manager framework library.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAssessmentFrameworks service method.</param>
///
/// <returns>The response from the ListAssessmentFrameworks service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworks">REST API Reference for ListAssessmentFrameworks Operation</seealso>
ListAssessmentFrameworksResponse ListAssessmentFrameworks(ListAssessmentFrameworksRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListAssessmentFrameworks operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAssessmentFrameworks operation on AmazonAuditManagerClient.</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 EndListAssessmentFrameworks
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworks">REST API Reference for ListAssessmentFrameworks Operation</seealso>
IAsyncResult BeginListAssessmentFrameworks(ListAssessmentFrameworksRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListAssessmentFrameworks operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAssessmentFrameworks.</param>
///
/// <returns>Returns a ListAssessmentFrameworksResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentFrameworks">REST API Reference for ListAssessmentFrameworks Operation</seealso>
ListAssessmentFrameworksResponse EndListAssessmentFrameworks(IAsyncResult asyncResult);
#endregion
#region ListAssessmentReports
/// <summary>
/// Returns a list of assessment reports created in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAssessmentReports service method.</param>
///
/// <returns>The response from the ListAssessmentReports service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentReports">REST API Reference for ListAssessmentReports Operation</seealso>
ListAssessmentReportsResponse ListAssessmentReports(ListAssessmentReportsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListAssessmentReports operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAssessmentReports operation on AmazonAuditManagerClient.</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 EndListAssessmentReports
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentReports">REST API Reference for ListAssessmentReports Operation</seealso>
IAsyncResult BeginListAssessmentReports(ListAssessmentReportsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListAssessmentReports operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAssessmentReports.</param>
///
/// <returns>Returns a ListAssessmentReportsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessmentReports">REST API Reference for ListAssessmentReports Operation</seealso>
ListAssessmentReportsResponse EndListAssessmentReports(IAsyncResult asyncResult);
#endregion
#region ListAssessments
/// <summary>
/// Returns a list of current and past assessments from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAssessments service method.</param>
///
/// <returns>The response from the ListAssessments service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessments">REST API Reference for ListAssessments Operation</seealso>
ListAssessmentsResponse ListAssessments(ListAssessmentsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListAssessments operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAssessments operation on AmazonAuditManagerClient.</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 EndListAssessments
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessments">REST API Reference for ListAssessments Operation</seealso>
IAsyncResult BeginListAssessments(ListAssessmentsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListAssessments operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAssessments.</param>
///
/// <returns>Returns a ListAssessmentsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListAssessments">REST API Reference for ListAssessments Operation</seealso>
ListAssessmentsResponse EndListAssessments(IAsyncResult asyncResult);
#endregion
#region ListControls
/// <summary>
/// Returns a list of controls from AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListControls service method.</param>
///
/// <returns>The response from the ListControls service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControls">REST API Reference for ListControls Operation</seealso>
ListControlsResponse ListControls(ListControlsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListControls operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListControls operation on AmazonAuditManagerClient.</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 EndListControls
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControls">REST API Reference for ListControls Operation</seealso>
IAsyncResult BeginListControls(ListControlsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListControls operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListControls.</param>
///
/// <returns>Returns a ListControlsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListControls">REST API Reference for ListControls Operation</seealso>
ListControlsResponse EndListControls(IAsyncResult asyncResult);
#endregion
#region ListKeywordsForDataSource
/// <summary>
/// Returns a list of keywords that pre-mapped to the specified control data source.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListKeywordsForDataSource service method.</param>
///
/// <returns>The response from the ListKeywordsForDataSource service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListKeywordsForDataSource">REST API Reference for ListKeywordsForDataSource Operation</seealso>
ListKeywordsForDataSourceResponse ListKeywordsForDataSource(ListKeywordsForDataSourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListKeywordsForDataSource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListKeywordsForDataSource operation on AmazonAuditManagerClient.</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 EndListKeywordsForDataSource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListKeywordsForDataSource">REST API Reference for ListKeywordsForDataSource Operation</seealso>
IAsyncResult BeginListKeywordsForDataSource(ListKeywordsForDataSourceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListKeywordsForDataSource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListKeywordsForDataSource.</param>
///
/// <returns>Returns a ListKeywordsForDataSourceResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListKeywordsForDataSource">REST API Reference for ListKeywordsForDataSource Operation</seealso>
ListKeywordsForDataSourceResponse EndListKeywordsForDataSource(IAsyncResult asyncResult);
#endregion
#region ListNotifications
/// <summary>
/// Returns a list of all AWS Audit Manager notifications.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListNotifications service method.</param>
///
/// <returns>The response from the ListNotifications service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListNotifications">REST API Reference for ListNotifications Operation</seealso>
ListNotificationsResponse ListNotifications(ListNotificationsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListNotifications operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListNotifications operation on AmazonAuditManagerClient.</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 EndListNotifications
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListNotifications">REST API Reference for ListNotifications Operation</seealso>
IAsyncResult BeginListNotifications(ListNotificationsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListNotifications operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListNotifications.</param>
///
/// <returns>Returns a ListNotificationsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListNotifications">REST API Reference for ListNotifications Operation</seealso>
ListNotificationsResponse EndListNotifications(IAsyncResult asyncResult);
#endregion
#region ListTagsForResource
/// <summary>
/// Returns a list of tags for the specified resource in AWS Audit Manager.
/// </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 AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonAuditManagerClient.</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/auditmanager-2017-07-25/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object 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 AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult);
#endregion
#region RegisterAccount
/// <summary>
/// Enables AWS Audit Manager for the specified AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterAccount service method.</param>
///
/// <returns>The response from the RegisterAccount service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterAccount">REST API Reference for RegisterAccount Operation</seealso>
RegisterAccountResponse RegisterAccount(RegisterAccountRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RegisterAccount operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RegisterAccount operation on AmazonAuditManagerClient.</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 EndRegisterAccount
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterAccount">REST API Reference for RegisterAccount Operation</seealso>
IAsyncResult BeginRegisterAccount(RegisterAccountRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RegisterAccount operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRegisterAccount.</param>
///
/// <returns>Returns a RegisterAccountResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterAccount">REST API Reference for RegisterAccount Operation</seealso>
RegisterAccountResponse EndRegisterAccount(IAsyncResult asyncResult);
#endregion
#region RegisterOrganizationAdminAccount
/// <summary>
/// Enables an AWS account within the organization as the delegated administrator for
/// AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterOrganizationAdminAccount service method.</param>
///
/// <returns>The response from the RegisterOrganizationAdminAccount service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterOrganizationAdminAccount">REST API Reference for RegisterOrganizationAdminAccount Operation</seealso>
RegisterOrganizationAdminAccountResponse RegisterOrganizationAdminAccount(RegisterOrganizationAdminAccountRequest request);
/// <summary>
/// Initiates the asynchronous execution of the RegisterOrganizationAdminAccount operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RegisterOrganizationAdminAccount operation on AmazonAuditManagerClient.</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 EndRegisterOrganizationAdminAccount
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterOrganizationAdminAccount">REST API Reference for RegisterOrganizationAdminAccount Operation</seealso>
IAsyncResult BeginRegisterOrganizationAdminAccount(RegisterOrganizationAdminAccountRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the RegisterOrganizationAdminAccount operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRegisterOrganizationAdminAccount.</param>
///
/// <returns>Returns a RegisterOrganizationAdminAccountResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/RegisterOrganizationAdminAccount">REST API Reference for RegisterOrganizationAdminAccount Operation</seealso>
RegisterOrganizationAdminAccountResponse EndRegisterOrganizationAdminAccount(IAsyncResult asyncResult);
#endregion
#region TagResource
/// <summary>
/// Tags the specified resource in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/TagResource">REST API Reference for TagResource Operation</seealso>
TagResourceResponse TagResource(TagResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonAuditManagerClient.</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 EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/TagResource">REST API Reference for TagResource Operation</seealso>
IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/TagResource">REST API Reference for TagResource Operation</seealso>
TagResourceResponse EndTagResource(IAsyncResult asyncResult);
#endregion
#region UntagResource
/// <summary>
/// Removes a tag from a resource in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UntagResource">REST API Reference for UntagResource Operation</seealso>
UntagResourceResponse UntagResource(UntagResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonAuditManagerClient.</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 EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UntagResource">REST API Reference for UntagResource Operation</seealso>
IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UntagResource">REST API Reference for UntagResource Operation</seealso>
UntagResourceResponse EndUntagResource(IAsyncResult asyncResult);
#endregion
#region UpdateAssessment
/// <summary>
/// Edits an AWS Audit Manager assessment.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessment service method.</param>
///
/// <returns>The response from the UpdateAssessment service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessment">REST API Reference for UpdateAssessment Operation</seealso>
UpdateAssessmentResponse UpdateAssessment(UpdateAssessmentRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateAssessment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessment operation on AmazonAuditManagerClient.</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 EndUpdateAssessment
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessment">REST API Reference for UpdateAssessment Operation</seealso>
IAsyncResult BeginUpdateAssessment(UpdateAssessmentRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateAssessment operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateAssessment.</param>
///
/// <returns>Returns a UpdateAssessmentResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessment">REST API Reference for UpdateAssessment Operation</seealso>
UpdateAssessmentResponse EndUpdateAssessment(IAsyncResult asyncResult);
#endregion
#region UpdateAssessmentControl
/// <summary>
/// Updates a control within an assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentControl service method.</param>
///
/// <returns>The response from the UpdateAssessmentControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControl">REST API Reference for UpdateAssessmentControl Operation</seealso>
UpdateAssessmentControlResponse UpdateAssessmentControl(UpdateAssessmentControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateAssessmentControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentControl operation on AmazonAuditManagerClient.</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 EndUpdateAssessmentControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControl">REST API Reference for UpdateAssessmentControl Operation</seealso>
IAsyncResult BeginUpdateAssessmentControl(UpdateAssessmentControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateAssessmentControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateAssessmentControl.</param>
///
/// <returns>Returns a UpdateAssessmentControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControl">REST API Reference for UpdateAssessmentControl Operation</seealso>
UpdateAssessmentControlResponse EndUpdateAssessmentControl(IAsyncResult asyncResult);
#endregion
#region UpdateAssessmentControlSetStatus
/// <summary>
/// Updates the status of a control set in an AWS Audit Manager assessment.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentControlSetStatus service method.</param>
///
/// <returns>The response from the UpdateAssessmentControlSetStatus service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControlSetStatus">REST API Reference for UpdateAssessmentControlSetStatus Operation</seealso>
UpdateAssessmentControlSetStatusResponse UpdateAssessmentControlSetStatus(UpdateAssessmentControlSetStatusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateAssessmentControlSetStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentControlSetStatus operation on AmazonAuditManagerClient.</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 EndUpdateAssessmentControlSetStatus
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControlSetStatus">REST API Reference for UpdateAssessmentControlSetStatus Operation</seealso>
IAsyncResult BeginUpdateAssessmentControlSetStatus(UpdateAssessmentControlSetStatusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateAssessmentControlSetStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateAssessmentControlSetStatus.</param>
///
/// <returns>Returns a UpdateAssessmentControlSetStatusResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentControlSetStatus">REST API Reference for UpdateAssessmentControlSetStatus Operation</seealso>
UpdateAssessmentControlSetStatusResponse EndUpdateAssessmentControlSetStatus(IAsyncResult asyncResult);
#endregion
#region UpdateAssessmentFramework
/// <summary>
/// Updates a custom framework in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentFramework service method.</param>
///
/// <returns>The response from the UpdateAssessmentFramework service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework">REST API Reference for UpdateAssessmentFramework Operation</seealso>
UpdateAssessmentFrameworkResponse UpdateAssessmentFramework(UpdateAssessmentFrameworkRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateAssessmentFramework operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentFramework operation on AmazonAuditManagerClient.</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 EndUpdateAssessmentFramework
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework">REST API Reference for UpdateAssessmentFramework Operation</seealso>
IAsyncResult BeginUpdateAssessmentFramework(UpdateAssessmentFrameworkRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateAssessmentFramework operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateAssessmentFramework.</param>
///
/// <returns>Returns a UpdateAssessmentFrameworkResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework">REST API Reference for UpdateAssessmentFramework Operation</seealso>
UpdateAssessmentFrameworkResponse EndUpdateAssessmentFramework(IAsyncResult asyncResult);
#endregion
#region UpdateAssessmentStatus
/// <summary>
/// Updates the status of an assessment in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentStatus service method.</param>
///
/// <returns>The response from the UpdateAssessmentStatus service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentStatus">REST API Reference for UpdateAssessmentStatus Operation</seealso>
UpdateAssessmentStatusResponse UpdateAssessmentStatus(UpdateAssessmentStatusRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateAssessmentStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateAssessmentStatus operation on AmazonAuditManagerClient.</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 EndUpdateAssessmentStatus
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentStatus">REST API Reference for UpdateAssessmentStatus Operation</seealso>
IAsyncResult BeginUpdateAssessmentStatus(UpdateAssessmentStatusRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateAssessmentStatus operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateAssessmentStatus.</param>
///
/// <returns>Returns a UpdateAssessmentStatusResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentStatus">REST API Reference for UpdateAssessmentStatus Operation</seealso>
UpdateAssessmentStatusResponse EndUpdateAssessmentStatus(IAsyncResult asyncResult);
#endregion
#region UpdateControl
/// <summary>
/// Updates a custom control in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateControl service method.</param>
///
/// <returns>The response from the UpdateControl service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateControl">REST API Reference for UpdateControl Operation</seealso>
UpdateControlResponse UpdateControl(UpdateControlRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateControl operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateControl operation on AmazonAuditManagerClient.</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 EndUpdateControl
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateControl">REST API Reference for UpdateControl Operation</seealso>
IAsyncResult BeginUpdateControl(UpdateControlRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateControl operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateControl.</param>
///
/// <returns>Returns a UpdateControlResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateControl">REST API Reference for UpdateControl Operation</seealso>
UpdateControlResponse EndUpdateControl(IAsyncResult asyncResult);
#endregion
#region UpdateSettings
/// <summary>
/// Updates AWS Audit Manager settings for the current user account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateSettings service method.</param>
///
/// <returns>The response from the UpdateSettings service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateSettings">REST API Reference for UpdateSettings Operation</seealso>
UpdateSettingsResponse UpdateSettings(UpdateSettingsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateSettings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateSettings operation on AmazonAuditManagerClient.</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 EndUpdateSettings
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateSettings">REST API Reference for UpdateSettings Operation</seealso>
IAsyncResult BeginUpdateSettings(UpdateSettingsRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateSettings operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateSettings.</param>
///
/// <returns>Returns a UpdateSettingsResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateSettings">REST API Reference for UpdateSettings Operation</seealso>
UpdateSettingsResponse EndUpdateSettings(IAsyncResult asyncResult);
#endregion
#region ValidateAssessmentReportIntegrity
/// <summary>
/// Validates the integrity of an assessment report in AWS Audit Manager.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ValidateAssessmentReportIntegrity service method.</param>
///
/// <returns>The response from the ValidateAssessmentReportIntegrity service method, as returned by AuditManager.</returns>
/// <exception cref="Amazon.AuditManager.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.InternalServerException">
/// An internal service error occurred during the processing of your request. Try again
/// later.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ResourceNotFoundException">
/// The resource specified in the request cannot be found.
/// </exception>
/// <exception cref="Amazon.AuditManager.Model.ValidationException">
/// The request has invalid or missing parameters.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ValidateAssessmentReportIntegrity">REST API Reference for ValidateAssessmentReportIntegrity Operation</seealso>
ValidateAssessmentReportIntegrityResponse ValidateAssessmentReportIntegrity(ValidateAssessmentReportIntegrityRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ValidateAssessmentReportIntegrity operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ValidateAssessmentReportIntegrity operation on AmazonAuditManagerClient.</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 EndValidateAssessmentReportIntegrity
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ValidateAssessmentReportIntegrity">REST API Reference for ValidateAssessmentReportIntegrity Operation</seealso>
IAsyncResult BeginValidateAssessmentReportIntegrity(ValidateAssessmentReportIntegrityRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ValidateAssessmentReportIntegrity operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginValidateAssessmentReportIntegrity.</param>
///
/// <returns>Returns a ValidateAssessmentReportIntegrityResult from AuditManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/ValidateAssessmentReportIntegrity">REST API Reference for ValidateAssessmentReportIntegrity Operation</seealso>
ValidateAssessmentReportIntegrityResponse EndValidateAssessmentReportIntegrity(IAsyncResult asyncResult);
#endregion
}
} | 61.093784 | 219 | 0.694762 | [
"Apache-2.0"
] | diegodias/aws-sdk-net | sdk/src/Services/AuditManager/Generated/_bcl35/IAmazonAuditManager.cs | 168,069 | C# |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FilterLists.Archival.Infrastructure.Scheduling;
using FilterLists.Directory.Api.Contracts;
using MediatR;
using Microsoft.Extensions.Logging;
namespace FilterLists.Archival.Application.Commands
{
public static class EnqueueArchiveAllLists
{
public class Command : IRequest
{
}
public class Handler : IRequestHandler<Command, Unit>
{
private readonly IDirectoryApi _directory;
private readonly ILogger _logger;
public Handler(IDirectoryApi directory, ILogger<Handler> logger)
{
_directory = directory;
_logger = logger;
}
public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
var r = new Random();
var lists = (await _directory.GetListsAsync(cancellationToken)).OrderBy(_ => r.Next()).ToList();
int archiveCount;
TimeSpan spacing;
#if DEBUG
archiveCount = 25;
spacing = TimeSpan.FromSeconds(5);
#else
archiveCount = lists.Count;
spacing = TimeSpan.FromSeconds((double)86400 / lists.Count);
#endif
_logger.LogInformation("Enqueuing archival of {ArchiveCount} lists spaced {Spacing} seconds apart.", archiveCount, spacing.Seconds);
for (var i = 0; i < archiveCount; i++)
{
new ArchiveList.Command(lists[i].Id).ScheduleBackgroundJob(i * spacing);
}
return Unit.Value;
}
}
}
}
| 30.767857 | 148 | 0.595473 | [
"MIT"
] | XY158/FilterLists | services/Archival/FilterLists.Archival.Application/Commands/EnqueueArchiveAllLists.cs | 1,725 | C# |
using ColossalFramework.UI;
using com.github.TheCSUser.HideItBobby.Features.Menu.Base;
using com.github.TheCSUser.HideItBobby.Features.Menu.Shared;
using com.github.TheCSUser.Shared.Common;
namespace com.github.TheCSUser.HideItBobby.Features.Menu
{
internal sealed class HideMainMenuNewsPanel : HideMainMenuElement
{
public override FeatureKey Key => FeatureKey.HideMainMenuNewsPanel;
public HideMainMenuNewsPanel(IModContext context) : base(context, "NewsFeedPanel") { }
protected override bool OnInitialize()
{
Patcher.Patch(MainMenuProxy.Patches);
MainMenuProxy.OnVisibilityChanged += OnMainMenuVisibilityChanged;
MainMenuProxy.OnCreditsEnded += OnMainMenuCreditsEnded;
return true;
}
protected override bool OnTerminate()
{
MainMenuProxy.OnCreditsEnded -= OnMainMenuCreditsEnded;
MainMenuProxy.OnVisibilityChanged -= OnMainMenuVisibilityChanged;
Patcher.Unpatch(MainMenuProxy.Patches);
return true;
}
private void OnMainMenuVisibilityChanged(MainMenu mainMenu, bool isVisible)
{
if (!IsEnabled) return;
var isPanelVisible = (mainMenu.GetField("m_NewsFeedPanel") as UIComponent)?.isVisible ?? false;
if (isPanelVisible) Enable(true);
}
private void OnMainMenuCreditsEnded(MainMenu mainMenu)
{
if (!IsEnabled) return;
var isPanelVisible = (mainMenu.GetField("m_NewsFeedPanel") as UIComponent)?.isVisible ?? false;
if (isPanelVisible) Enable(true);
}
}
} | 39.333333 | 107 | 0.675545 | [
"MIT"
] | TheCSUser/HideItBOB | Features/Menu/HideMainMenuNewsPanel.cs | 1,654 | C# |
using MemoScope.Core.Data;
using MemoScope.Modules.Instances;
using System;
using WeifenLuo.WinFormsUI.Docking;
using WinFwk.UICommands;
using WinFwk.UIModules;
namespace MemoScope.Modules.InstanceDetails
{
public class InstanceDetailsCommand : AbstractDataUICommand<ClrDumpObject>
{
public InstanceDetailsCommand() : base("Instance", "Display instance details", "Dump", Properties.Resources.elements)
{
}
protected override void HandleData(ClrDumpObject data)
{
if( data == null)
{
throw new InvalidOperationException("Can't show instance details: nothing selected !");
}
Display(selectedModule, data);
}
public static void Display(UIModule parentModule, ClrDumpObject data)
{
if (data.ClrType?.IsArray ?? false)
{
var elementsAddresses = new ArrayElementsAddressContainer(data);
var addresses = new AddressList(data.ClrDump, data.ClrType.ComponentType, elementsAddresses);
string name = $"{data.ClrDump.Id} - Elements: {data.Address:X} [{data.ClrType.ComponentType.Name}]";
InstancesModule.Create(addresses, parentModule, mod => DockModule(parentModule.MessageBus, mod), name);
}
else
{
UIModuleFactory.CreateModule<InstanceDetailsModule>(
mod => { mod.UIModuleParent = parentModule; mod.Setup(data); },
mod => DockModule(parentModule.MessageBus, mod, DockState.DockRight)
);
}
}
}
}
| 36.644444 | 125 | 0.615525 | [
"Unlicense"
] | user2291296/MemoScope.Net | MemoScope/Modules/InstanceDetails/InstanceDetailsCommand.cs | 1,651 | C# |
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using EF6TempTableKit.DbContext;
using EF6TempTableKit.Extensions;
namespace EF6TempTableKit.Utilities
{
/// <summary>
/// Handles dependencies in a form of a tree. Root node doesn't exist - think of it as something imaginary.
/// Node - represent parent of children nodes.
/// Children - list of nodes that belongs to parent node.
/// Level - only two levels
/// 1. parent (temp table)
/// 2. children(dependencies - tables on which parent depends).
/// </summary>
internal class TempTableDependencyManager
{
private readonly string[] _tablesUsedInQuery;
private readonly string[] _tempSqlQueryList;
private readonly TempTableContainer _tempTableContainer;
private readonly ObjectQuery _objectQuery;
internal TempTableDependencyManager(ObjectQuery objectQuery, TempTableContainer tempTableContainer)
{
_objectQuery = objectQuery;
_tempTableContainer = tempTableContainer;
_tablesUsedInQuery = GetAllTablesInQuery();
_tempSqlQueryList = _tempTableContainer.TempSqlQueriesList.Select(t => t.Key).ToArray();
}
/// <summary>
/// Use all tables from attached query and compare with already attached temp tables.
/// Get match into a separate collection. Traverse through the first level children as they already have dependencies.
/// </summary>
/// <param name="newTempTableName"></param>
public void AddDependenciesForTable(string newTempTableName)
{
//newTempTableName = key
var alreadyAttachedTempTablesFromQuery = _tempSqlQueryList
.Where(aaTT => _tablesUsedInQuery.Any(tiQ => tiQ == aaTT))
.Select(aaTT => aaTT)
.ToArray();
var hasAlreadyAttachedTempTablesFromQuery = alreadyAttachedTempTablesFromQuery.Length > 0;
if (hasAlreadyAttachedTempTablesFromQuery)
{
_tempTableContainer
.TempOnTempDependencies
.Add(new KeyValuePair<string, HashSet<string>>(newTempTableName, new HashSet<string>()));
var childrenDependencies = new List<string>();
foreach (var item in alreadyAttachedTempTablesFromQuery)
{
if (_tempTableContainer.TempOnTempDependencies.ContainsKey(item))
{
childrenDependencies.AddRange(_tempTableContainer.TempOnTempDependencies[item]);
childrenDependencies.Add(item);
childrenDependencies.ForEach(cd => _tempTableContainer.TempOnTempDependencies[newTempTableName].AddIfNotExists(cd));
}
else
{
_tempTableContainer.TempOnTempDependencies[newTempTableName].AddIfNotExists(item);
}
}
}
}
private string[] GetAllTablesInQuery()
{
return _objectQuery.GetTables().Where(t => t.Table != null).Select(t => t.Table).ToArray(); //Take all as we can't filter out (easily) only ITempTable
}
}
}
| 44.4 | 162 | 0.624024 | [
"MIT"
] | zblago/EF6TempTableKit | src/EF6TempTableKit/Utilities/TempTableDependencyManager.cs | 3,332 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Utilities;
using Microsoft.VisualStudio.Threading;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// Implements <see cref="IThreadingContext"/>, which provides an implementation of
/// <see cref="VisualStudio.Threading.JoinableTaskFactory"/> to Roslyn code.
/// </summary>
/// <remarks>
/// <para>The <see cref="VisualStudio.Threading.JoinableTaskFactory"/> is constructed from the
/// <see cref="VisualStudio.Threading.JoinableTaskContext"/> provided by the MEF container, if available. If no
/// <see cref="VisualStudio.Threading.JoinableTaskContext"/> is available, a new instance is constructed using the
/// synchronization context of the current thread as the main thread.</para>
/// </remarks>
[Export(typeof(IThreadingContext))]
[Shared]
internal sealed partial class ThreadingContext : IThreadingContext
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContext([Import(AllowDefault = true)] JoinableTaskContext joinableTaskContext)
{
if (joinableTaskContext is null)
{
(joinableTaskContext, _) = CreateJoinableTaskContext();
}
HasMainThread = joinableTaskContext.MainThread.IsAlive;
JoinableTaskContext = joinableTaskContext;
JoinableTaskFactory = joinableTaskContext.Factory;
}
internal static (JoinableTaskContext joinableTaskContext, SynchronizationContext synchronizationContext) CreateJoinableTaskContext()
{
Thread mainThread;
SynchronizationContext synchronizationContext;
switch (ForegroundThreadDataInfo.CreateDefault(ForegroundThreadDataKind.Unknown))
{
case ForegroundThreadDataKind.JoinableTask:
throw new NotSupportedException($"A {nameof(VisualStudio.Threading.JoinableTaskContext)} already exists, but we have no way to obtain it.");
case ForegroundThreadDataKind.Wpf:
case ForegroundThreadDataKind.WinForms:
case ForegroundThreadDataKind.MonoDevelopGtk:
case ForegroundThreadDataKind.MonoDevelopXwt:
case ForegroundThreadDataKind.StaUnitTest:
// The current thread is the main thread, and provides a suitable synchronization context
mainThread = Thread.CurrentThread;
synchronizationContext = SynchronizationContext.Current;
break;
case ForegroundThreadDataKind.ForcedByPackageInitialize:
case ForegroundThreadDataKind.Unknown:
default:
// The current thread is not known to be the main thread; we have no way to know if the
// synchronization context of the current thread will behave in a manner consistent with main thread
// synchronization contexts, so we use DenyExecutionSynchronizationContext to track any attempted
// use of it.
var denyExecutionSynchronizationContext = new DenyExecutionSynchronizationContext(SynchronizationContext.Current);
mainThread = denyExecutionSynchronizationContext.MainThread;
synchronizationContext = denyExecutionSynchronizationContext;
break;
}
return (new JoinableTaskContext(mainThread, synchronizationContext), synchronizationContext);
}
/// <inheritdoc/>
public bool HasMainThread
{
get;
}
/// <inheritdoc/>
public JoinableTaskContext JoinableTaskContext
{
get;
}
/// <inheritdoc/>
public JoinableTaskFactory JoinableTaskFactory
{
get;
}
}
}
| 44.925532 | 161 | 0.662325 | [
"Apache-2.0"
] | DustinCampbell/roslyn | src/EditorFeatures/Core/Shared/Utilities/ThreadingContext.cs | 4,225 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Archivos;
using Exepciones;
namespace Entidades
{
public class Restaurant
{
#region Atributos
static List<Producto> ventas;
static List<Pedido> pedidos;
static List<Pedido> pedidosListos;
static List<Producto> menu;
public static int NumeroPedido;
#endregion
#region Constructores
/// <summary>
/// Constructor por defecto para potencialemnte serializar la clase.
/// </summary>
public Restaurant()
{
}
/// <summary>
/// Constructor statico para que inicialize todas las listas usadas y el contador numero pedido
/// </summary>
static Restaurant()
{
ventas = new List<Producto>();
menu = new List<Producto>();
pedidos = new List<Pedido>();
pedidosListos = new List<Pedido>();
Restaurant restaurant = new Restaurant();
}
#endregion
#region Metodos
/// <summary>
/// /Agrega producto a lista de tipo producto utilizada para seguir la venta.
/// </summary>
/// <param name="codigo"></param>
/// <param name="descripcion"></param>
/// <param name="precio"></param>
public static void AgregarVenta(int codigo,string descripcion,float precio)
{
Restaurant.ventas.Add(new Producto(codigo,descripcion,precio));
}
/// <summary>
/// Agrega productos a la lista utilizada para mostar el menu disponible al cajero
/// </summary>
/// <param name="codigo"></param>
/// <param name="descripcion"></param>
/// <param name="precio"></param>
public static void AgregarMenu(int codigo, string descripcion, float precio)
{
Restaurant.menu.Add(new Producto(codigo, descripcion, precio));
}
/// <summary>
/// Metodo utizado para genara un pedido al momento que se cobra la venta.envia los parametros. y genera el objeto
/// </summary>
/// <param name="importeTotal"></param>
/// <param name="descripcion"></param>
/// <param name="nombreCliente"></param>
/// <param name="numeroPedido"></param>
/// <param name="delivery"></param>
public static void AgregarPedido(float importeTotal, string descripcion, string nombreCliente, int numeroPedido,bool delivery)
{
Restaurant.pedidos.Add(new Pedido(importeTotal, descripcion, nombreCliente ,numeroPedido,delivery));
}
/// <summary>
/// sobrearga del metodo anterior agrega pedidodo a la lista de pedidos reciviendo un objeto
/// </summary>
/// <param name="pedido"></param>
public static void AgregarPedidoObjeto(Pedido pedido)
{
Restaurant.pedidos.Add(pedido);
}
/// <summary>
/// Agrega el objeto pedido a la lista de pedidos listos , para vizualizar en el Form los pedidos ya completados.
/// </summary>
/// <param name="pedido"></param>
public static void AgregarPedido(Pedido pedido)
{
Restaurant.pedidosListos.Add(pedido);
}
/// <summary>
/// Metodo Simula la entrega a los exelenticimos clientes del restaurant , en forma aleatoria simulando clientes atentos y no atentos al anuncio
/// </summary>
public static void PedidoEntregado()
{
if (pedidosListos.Count() > 0)
{
Random random = new Random();
int numero=random.Next(Restaurant.pedidosListos.FirstOrDefault().NumeroPedido,Restaurant.NumeroPedido);
foreach (Pedido item in pedidosListos)
{
if (item.NumeroPedido == numero)
{
if (item.GetDelivery())
{
Delivery.DeliveryPedido(item.NombreCliente, item.NombreCliente);
}
pedidosListos.Remove(item);
break;
}
}
}
}
/// <summary>
/// Metodo simula la fabricacion del pedido y pasado a lista para retirar. siguendo un orden primero entra y primero sale
/// </summary>
public static void PedidoListo()
{
try
{
if (Restaurant.viewPedidos().Count>0)
{
int numero = Restaurant.pedidos.FirstOrDefault().NumeroPedido;
foreach (Pedido item in pedidos)
{
if (item.NumeroPedido == numero)
{
Restaurant.pedidosListos.Add(item);
Restaurant.pedidos.Remove(item);
break;
}
}
}
}
catch (Exception e)
{
throw new HilosException (e);
}
}
/// <summary>
/// Metodo devuelve lista de producto utilizada para menu
/// </summary>
/// <returns></returns>
public static List<Producto> viewMenu()
{
return menu;
}
/// <summary>
/// Metodo devuelve lista productos utilizada para venta
/// </summary>
/// <returns></returns>
public static List<Producto> viewVentas()
{
return ventas;
}
/// <summary>
/// metodo devuelve lista pedidos utilizada por pantalla en preparacion
/// </summary>
/// <returns></returns>
public static List<Pedido> viewPedidos()
{
return pedidos;
}
/// <summary>
/// Metodo devuelve lista de pedido utilizada por pantalla pedidos a entregar
/// </summary>
/// <returns></returns>
public static List<Pedido> viewPedidosListos()
{
return pedidosListos;
}
/// <summary>
/// Metodo utilizado Limpia la pantalla de venta del cajero
/// </summary>
public static void LimpiarVentas()
{
ventas.Clear();
}
public static string DescripcionPedido()
{
StringBuilder sb = new StringBuilder();
foreach (Producto item in ventas)
{
sb.AppendLine(item.Descripcion);
}
return sb.ToString();
}
/// <summary>
/// MEtodo genera un sting con todos los datos del pedido y la direccion.
/// </summary>
/// <param name="direcion"></param>
/// <returns></returns>
public static string PedidoRepartidor(string direcion)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"Datos para Entregar :"+direcion.ToString());
foreach (Producto item in ventas)
{
sb.AppendLine(item.Descripcion+" "+item.Precio);
}
sb.AppendLine($" "+ CalculoImportePedido().ToString());
return sb.ToString();
}
/// <summary>
/// Metodo utilziado para calcular el inporte total.
/// </summary>
/// <returns>retorna un float</returns>
public static float CalculoImportePedido()
{
float ImporteTotal = 0;
foreach (Producto item in Restaurant.viewVentas())
{
ImporteTotal = item.Precio + ImporteTotal;
}
return ImporteTotal;
}
public static void Guardar(string nombreCliente,string direccion)
{
Texto texto = new Texto();
texto.Guardar(AppDomain.CurrentDomain.BaseDirectory + @nombreCliente + ".txt", PedidoRepartidor(direccion));
}
/// <summary>
/// Metodo utilizado para precargar los pedidos en la pantalla en preparacion
/// </summary>
public static void PreCargadoPedidos()
{
try
{
List<Pedido> recuperarPedidos = new List<Pedido>();
Xml<List<Pedido>> archivoXML = new Xml<List<Pedido>>();
pedidos= archivoXML.Leer(AppDomain.CurrentDomain.BaseDirectory + @"pedidosPreCarga0000.xml" , recuperarPedidos);
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Metodo utilizado una sola vez para guardar Serializar lista en preparacion .
/// </summary>
public static void GuardarXml()
{
Xml<List<Pedido>> archivoXML = new Xml<List<Pedido>>();
archivoXML.Guardar(AppDomain.CurrentDomain.BaseDirectory + @"pedidosPreCarga0000.xml",Restaurant.viewPedidos());
}
#endregion
}
}
| 32.323024 | 152 | 0.516585 | [
"Unlicense"
] | mikelanda14/Parcial-lab2D | SPProgramacion-Lab2/MiguelLandaeta_2D/Entidades/Restaurant.cs | 9,408 | C# |
// (c) Copyright Crainiate Software 2010
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
using Crainiate.Diagramming.Flowcharting;
namespace Crainiate.Diagramming.Flowcharting
{
public class FlowchartStencil: Stencil
{
#region Interface
//Constructors
public FlowchartStencil()
{
CreateStencilItems();
}
public virtual StencilItem this[FlowchartStencilType type]
{
get
{
string key = type.ToString();
return (StencilItem) Dictionary[key];
}
set
{
string key = type.ToString();
Dictionary[key] = value;
}
}
#endregion
#region Events
private void StencilItem_DrawShape(object sender, DrawShapeEventArgs e)
{
StencilItem stencil = (StencilItem) sender;
DrawStencilItem(stencil,e);
}
#endregion
#region Implementation
private void CreateStencilItems()
{
SetModifiable(true);
//Loop through each enumeration and add as a stencil item
foreach (string type in Enum.GetNames(typeof(FlowchartStencilType)))
{
StencilItem item = new StencilItem();
item.DrawShape +=new DrawShapeEventHandler(StencilItem_DrawShape);
Add(type,item);
}
SetModifiable(false);
}
private void DrawStencilItem(StencilItem stencil, DrawShapeEventArgs e)
{
GraphicsPath path = e.Path;
RectangleF rect = new Rectangle();
FlowchartStencilType stencilType = (FlowchartStencilType) Enum.Parse(typeof(FlowchartStencilType), stencil.Key);
float width = e.Width;
float height = e.Height;
float percX = 0;
float percY = 0;
float perc = 0;
float midX = 0;
float midY = 0;
rect.Width = width;
rect.Height = height;
midX = width / 2;
midY = height / 2;
if (stencilType == FlowchartStencilType.Default)
{
percX = 20;
percY = 20;
path.AddArc(0, 0, percX, percY, 180, 90);
path.AddArc(width - percX, 0, percX, percY, 270, 90);
path.AddArc(width - percX, height - percY, percX, percY, 0, 90);
path.AddArc(0, height - percY, percX, percY, 90, 90);
path.CloseFigure();
stencil.Redraw = true;
}
else if (stencilType == FlowchartStencilType.Card)
{
percX = width * 0.2F;
percY = height * 0.2F;
path.AddLine(percX, 0, width, 0);
path.AddLine(width, 0, width, height);
path.AddLine(width, height, 0, height);
path.AddLine(0, height, 0, percY);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Collate)
{
path.AddLine(0, 0, width, 0);
path.AddLine(width, 0, 0, height);
path.AddLine(0, height, width, height);
path.AddLine(width, height, 0, 0);
}
else if (stencilType == FlowchartStencilType.Connector)
{
percX = width * 0.5F;
percY = height * 0.5F;
path.AddEllipse(percX, percY, width, height);
}
else if (stencilType == FlowchartStencilType.Data)
{
path.AddLine(midX / 2, 0, width, 0);
path.AddLine(width, 0, (midX / 2) + midX, height);
path.AddLine((midX / 2) + midX, height, 0, height);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Decision)
{
path.AddLine(midX, 0, width, midY);
path.AddLine(width, midY, midX, height);
path.AddLine(midX, height, 0, midY);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Delay)
{
percX = width * 0.2F;
path.AddArc(percX, 0 , width * 0.8F, height, 270, 180);
path.AddLine(0, height, 0, 0);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Display)
{
percX = width * 0.2F;
path.AddArc(percX, 0 , width * 0.8F, height, 270, 180);
path.AddLine(percX, height, 0, height / 2);
path.AddLine(0, height / 2,percX, 0);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Direct)
{
percX = width * 0.3F;
path.AddLine(width * 0.7F, height, percX, height);
path.AddArc(0, 0, percX, height, 90, 180);
path.AddLine(width * 0.7F, 0, percX, 0);
path.AddArc(width * 0.7F, 0, percX, height, 270, -180);
path.CloseFigure();
path.StartFigure();
path.AddEllipse(width * 0.7F, 0, percX, height);
}
else if (stencilType == FlowchartStencilType.Document)
{
PointF[] points = new PointF[4];
points[0].X = 0;
points[0].Y = height * 0.95F;
points[1].X = width * 0.25F;
points[1].Y = height;
points[2].X = width * 0.75F;
points[2].Y = height * 0.85F;
points[3].X = width;
points[3].Y = height * 0.8F;
path.AddLine(new Point(0, 0), points[0]);
path.AddCurve(points);
path.AddLine(points[3], new PointF(width, 0));
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Extract)
{
percX = width * 0.25F;
percY = height * 0.75F;
path.AddLine(percX, 0, percX * 2, percY);
path.AddLine(percX * 2, percY, 0, percY);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.InternalStorage)
{
perc = width * 0.15F;
path.AddRectangle(rect);
path.AddLine(perc, 0, perc, height);
path.CloseFigure();
path.AddLine(0, perc, width, perc);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.ManualInput)
{
percY = height * 0.25F;
path.AddLine(0, percY, width, 0);
path.AddLine(width, 0, width, height);
path.AddLine(width, height, 0, height);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.ManualOperation)
{
percX = width * 0.2F;
path.AddLine(0, 0, width, 0);
path.AddLine(width, 0, width - percX, height);
path.AddLine(width - percX, height, percX, height);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.MultiDocument)
{
PointF[] points = new PointF[4];
width = width * 0.8F;
points[0].X = 0;
points[0].Y = height * 0.95F;
points[1].X = width * 0.25F;
points[1].Y = height;
points[2].X = width * 0.75F;
points[2].Y = height * 0.85F;
points[3].X = width;
points[3].Y = height * 0.8F;
path.AddLine(new PointF(0, height * 0.2F), points[0]);
path.AddCurve(points);
path.AddLine(points[3], new PointF(width, height * 0.2F));
path.CloseFigure();
width = rect.Width;
path.AddLine(width * 0.2F, height * 0.1F, width * 0.2F, 0);
path.AddLine(width * 0.2F, 0, width, 0);
path.AddLine(width, 0, width, height * 0.6F);
path.AddLine(width, height * 0.6F, width * 0.9F, height * 0.6F);
path.AddLine(width * 0.9F, height * 0.6F, width * 0.9F, height * 0.1F);
path.CloseFigure();
path.AddLine(width * 0.1F, height * 0.2F, width * 0.1F, height * 0.1F);
path.AddLine(width * 0.1F, height * 0.1F, width * 0.9F, height * 0.1F);
path.AddLine(width * 0.9F, height * 0.1F, width * 0.9F, height * 0.7F);
path.AddLine(width * 0.9F, height * 0.7F, width * 0.8F, height * 0.7F);
path.AddLine(width * 0.8F, height * 0.7F, width * 0.8F, height * 0.2F);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.OffPageConnector)
{
percX = width * 0.5F;
percY = height * 0.75F;
path.AddLine(0, 0, width, 0);
path.AddLine(width, 0, width , percY);
path.AddLine(width, percY, percX, height);
path.AddLine(percX, height, 0, percY);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.PredefinedProcess)
{
perc = width * 0.1F;
path.AddRectangle(rect);
path.CloseFigure();
path.AddLine(perc, 0, perc, height);
path.CloseFigure();
path.AddLine(width - perc, 0, width - perc, height);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Preparation)
{
percX = width * 0.2F;
path.AddLine(0, midY, percX, 0);
path.AddLine(percX, 0, width - percX, 0);
path.AddLine(width - percX, 0, width, midY);
path.AddLine(width, midY, width - percX, height);
path.AddLine(width - percX, height, percX, height);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Process)
{
path.AddRectangle(new RectangleF(0, 0, width, height));
}
else if (stencilType == FlowchartStencilType.Process2)
{
percX = width * 0.2F;
percY = height * 0.2F;
if (percX < percY)
{
percY = percX;
}
else
{
percX = percY;
}
path.AddArc(0, 0, percX, percY, 180, 90);
path.AddArc(width - percX, 0, percX, percY, 270, 90);
path.AddArc(width - percX, height - percY, percX, percY, 0, 90);
path.AddArc(0, height - percY, percX, percY, 90, 90);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Terminator)
{
percX = width * 0.5F;
percY = height * 0.20F;
path.AddArc(0, percY, percX, percY * 2, 90, 180);
path.AddArc(width - percX, percY, percX, percY * 2, 270, 180);
path.CloseFigure();
stencil.KeepAspect = true;
}
else if (stencilType == FlowchartStencilType.Tape)
{
PointF[] points = new PointF[5];
PointF[] pointsBottom = new PointF[5];
points[0].X = 0;
points[0].Y = height * 0.05F;
points[1].X = width * 0.25F;
points[1].Y = height * 0.1F;
points[2].X = width * 0.5F;
points[2].Y = height * 0.05F;
points[3].X = width * 0.75F;
points[3].Y = 0;
points[4].X = width;
points[4].Y = height * 0.05F;
pointsBottom[4].X = 0;
pointsBottom[4].Y = height * 0.95F;
pointsBottom[3].X = width * 0.25F;
pointsBottom[3].Y = height;
pointsBottom[2].X = width * 0.5F;
pointsBottom[2].Y = height * 0.95F;
pointsBottom[1].X = width * 0.75F;
pointsBottom[1].Y = height * 0.9F;
pointsBottom[0].X = width;
pointsBottom[0].Y = height * 0.95F;
path.AddCurve(points);
path.AddLine(points[4], pointsBottom[0]);
path.AddCurve(pointsBottom);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Junction)
{
percX = width * 0.25F;
percY = height * 0.25F;
if (percX > percY)
{
perc = percX;
}
else
{
perc = percY;
}
path.AddEllipse(perc, perc, perc * 2, perc * 2);
path.CloseFigure();
path.StartFigure();
path.AddLine(perc * 2, perc, perc * 2, perc * 3);
path.StartFigure();
path.AddLine(perc, perc * 2, perc * 3, perc * 2);
Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0);
//Rotate the matrix through 45 degress
perc = perc * 2;
matrix.RotateAt(45, new PointF(perc, perc));
//Transform the graphicspath object
path.Transform(matrix);
}
else if (stencilType == FlowchartStencilType.LogicalOr)
{
percX = width * 0.5F;
percY = height * 0.5F;
if (percX > percY)
{
perc = percX;
}
else
{
perc = percY;
}
path.AddEllipse(perc, perc, perc * 2, perc * 2);
path.AddLine(perc * 2, perc, perc * 2, perc * 3);
path.CloseFigure();
path.AddLine(perc, perc * 2, perc * 3, perc * 2);
}
else if (stencilType == FlowchartStencilType.Sort)
{
percX = width * 0.5F;
percY = height * 0.5F;
path.AddLine(0, percY, percX, 0);
path.AddLine(percX, 0, width, percY);
path.AddLine(width, percY, percX, height);
path.AddLine(percX, height, 0, percY);
path.CloseFigure();
path.StartFigure();
path.AddLine(0,percY, width, percY);
}
else if (stencilType == FlowchartStencilType.Merge)
{
path.AddLine(0, 0, width, 0);
path.AddLine(width, 0, width * 0.5F, height);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.StoredData)
{
percX = width * 0.3F;
path.AddArc(0, 0, percX, height, 90, 180);
path.AddArc(width * 0.85F, 0, percX, height, 270, -180);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Sequential)
{
if (width > height)
{
perc = height;
}
else
{
perc = width;
}
path.AddArc(0, 0, perc, perc, 45, -315);
path.AddLine(perc * 0.5F, perc, perc, perc);
path.AddLine(perc, perc, perc, perc * 0.85F);
path.CloseFigure();
}
else if (stencilType == FlowchartStencilType.Magnetic)
{
percY = height * 0.4F;
path.AddArc(0, - height * 0.2F, width, percY, 180, -180);
path.AddLine(width, 0, width, height * 0.8F);
path.AddArc(0, height * 0.6F, width, percY, 0, 180);
path.AddLine(0, height * 0.8F, 0, 0);
//path.CloseFigure();
//Define two shapes so that not see through
path.StartFigure();
path.AddLine(0, 0, width, 0);
path.AddArc(0, - height * 0.2F, width, percY, 0, 180);
}
}
#endregion
}
}
| 25.702041 | 116 | 0.610846 | [
"BSD-3-Clause"
] | Mohllal/FlowchartConverter | Crainiate.Diagramming/Crainiate.Diagramming.Flowcharting/FlowchartStencil.cs | 12,594 | C# |
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UniRx;
using UnityEngine;
using Random = UnityEngine.Random;
[RequireComponent(typeof(Animator))]
public class Spider : EnemyBase
{
[SerializeField, Header("一辺を移動する時間 (秒)")]
private float moveSpeed;
[SerializeField, Header("壁と垂直な法線を決める際の試行ごとの角度"), Range(0, 90)]
private int degPerInitTrial;
[SerializeField, Header("クモの巣")]
private Spiderweb web;
[SerializeField]
private Shader shader;
[SerializeField]
private Texture webTex;
[SerializeField, Header("巣を作り始めるプレイヤーとの距離")]
private float distanceFromPlayerStartingWeaving;
private Animator _animator;
private MeshRenderer _renderer;
private Material _webMaterial;
public SpiderState state;
private float _totalWeaveDistance;
private readonly List<Vector3> _passagePoints = new List<Vector3>();
private const int WallLayer = 1 << 7;
private Player _player;
private static readonly int IsMove = Animator.StringToHash("IsMove");
private static readonly int SPropAlpha = Shader.PropertyToID("Vector1_a3aa0b61c05943b686b6d48e9f569c75");
private static readonly int SPropTex = Shader.PropertyToID("Texture2D_ab101d69e96444f3a869ddd9318ad100");
public enum SpiderState
{
Idle,
RandomMoving,
Weaving,
Dead,
}
public override void OnDamaged(int damageAmount, GameObject attackedObject)
{
}
private void Start()
{
_animator = GetComponent<Animator>();
_player = Player.Instance;
if (web)
{
_renderer = web.gameObject.GetComponent<MeshRenderer>();
// アルファ値を個別に設定したいため、マテリアルを個別で作成・適用
var mat = new Material(shader);
_webMaterial = mat;
_renderer.material = mat;
_renderer.material.SetTexture(SPropTex, webTex);
}
Init();
this.ObserveEveryValueChanged(x => x.state)
.Subscribe(OnStateChanged)
.AddTo(this);
}
private void OnStateChanged(SpiderState state)
{
if (state == SpiderState.Weaving)
{
Weave();
}
}
private void Update()
{
switch (state)
{
case SpiderState.Idle:
float distanceFromPlayer = Vector3.Distance(_player.transform.position, transform.position);
if (distanceFromPlayer < distanceFromPlayerStartingWeaving)
{
state = SpiderState.Weaving;
}
break;
case SpiderState.RandomMoving:
break;
case SpiderState.Weaving:
{
break;
}
case SpiderState.Dead:
break;
}
}
/// <summary>
/// クモが巣を構築するパターン
/// </summary>
private enum WeavePattern
{
/// <summary>水平方向への移動から構築を始めるパターン</summary>
Horizon,
/// <summary>斜め方向への移動から構築を始めるパターン</summary>
Slash,
}
#region 初期化系メソッド
/// <summary>
/// 初期化処理
/// </summary>
private void Init()
{
int patternCount = Enum.GetNames(typeof(WeavePattern)).Length;
// var pattern = (WeavePattern) Random.Range(0, patternCount);
const WeavePattern pattern = WeavePattern.Slash;
CalculatePassagePoints(pattern);
state = SpiderState.Idle;
}
/// <summary>
/// 巣の構築時に移動する経路地点を算出する
/// </summary>
/// <param name="pattern">移動パターン</param>
private void CalculatePassagePoints(WeavePattern pattern)
{
Vector3 startPos = default;
Vector3 endPos = default;
// 通路に対する法線取得
Vector3 norm = GetPerpendicularDirection(ref startPos, ref endPos);
// 壁から壁までの中心座標
Vector3 centerPos = Vector3.Lerp(startPos, endPos, .5f);
var ray = new Ray
{
origin = centerPos
};
switch (pattern)
{
// TODO
case WeavePattern.Horizon:
{
break;
}
case WeavePattern.Slash:
{
// 中心から右上45°へのベクトル作成し、ray地点を次の目的地に
Vector3 dir = Quaternion.AngleAxis(60, Vector3.forward) * norm;
ray.direction = dir;
if (Physics.Raycast(ray, out RaycastHit hit1, Mathf.Infinity, WallLayer))
{
_passagePoints.Add(hit1.point);
_totalWeaveDistance += Vector3.Distance(hit1.point, transform.position);
}
// そこから法線の逆方向(開始地点真上)にrayを飛ばし、接点を次の目的地に
ray.origin = hit1.point;
ray.direction = -norm;
if (Physics.Raycast(ray, out RaycastHit hit2, Mathf.Infinity, WallLayer))
{
_passagePoints.Add(hit2.point);
_totalWeaveDistance += Vector3.Distance(hit2.point, hit1.point);
}
_passagePoints.Add(startPos);
_passagePoints.Add(endPos);
_totalWeaveDistance += Vector3.Distance(startPos, hit2.point) + Vector3.Distance(endPos, startPos);
web.SetMesh(endPos, startPos, hit2.point, hit1.point);
break;
}
}
}
/// <summary>
/// 現在地から壁への法線ベクトルを取得する
/// </summary>
/// <param name="startPoint">開始地点</param>
/// <param name="endPoint">終了地点</param>
/// <returns></returns>
private Vector3 GetPerpendicularDirection(ref Vector3 startPoint, ref Vector3 endPoint)
{
Vector3 resultDir = default;
float minDist = default;
Vector3 baseDir = transform.right;
int rotateDeg = 0;
// 試行ごとに回転する角度から試行回数を算出
int trialCount = (int) Mathf.Ceil((float) 180 / degPerInitTrial);
// 試行回数分レイを飛ばして法線となるベクトルを求める
for (int i = 0; i < trialCount; i++)
{
// 試行ごとに指定度回転
baseDir = Quaternion.AngleAxis(degPerInitTrial, Vector3.up) * baseDir;
var ray = new Ray(transform.position, baseDir);
Physics.Raycast(ray, out RaycastHit firstHit, Mathf.Infinity, WallLayer);
// 壁から壁への距離を出すため、逆方向にもレイを飛ばす
ray.direction = -baseDir;
Physics.Raycast(ray, out RaycastHit secondHit, Mathf.Infinity, WallLayer);
if (!firstHit.transform || !secondHit.transform)
{
rotateDeg += degPerInitTrial;
continue;
}
float dist = Vector3.Distance(firstHit.point, transform.position) +
Vector3.Distance(secondHit.point, transform.position);
// 計算した壁から壁への距離が最短だったら更新
if (minDist == 0 || minDist > dist)
{
resultDir = baseDir;
minDist = dist;
startPoint = firstHit.point;
endPoint = secondHit.point;
}
rotateDeg += degPerInitTrial;
}
return resultDir;
}
#endregion
#region 動作系メソッド
/// <summary>
/// クモの巣を張る処理
/// </summary>
private async void Weave()
{
if (_passagePoints.Count == 0) return;
// 移動距離
float movedDistance = 0;
_animator.SetBool(IsMove, true);
// 通過点を順番に回らせる
foreach (Vector3 point in _passagePoints)
{
Vector3 basePos = transform.position;
Vector3 oldPos = basePos;
float elapsedTime = 0; // 次の目的地へ移動時の経過時間
float movedRate = 0; // 次の目的地までの進行率 (0-1)
Turn(point);
while (movedRate < 1)
{
elapsedTime += Time.deltaTime;
movedRate = Mathf.Clamp01(elapsedTime / moveSpeed);
transform.position = Vector3.Lerp(basePos, point, movedRate);
movedDistance += Vector3.Distance(oldPos, transform.position);
oldPos = transform.position;
// 巣のマテリアルのアルファ値に透明度を進捗率で反映
SetWebAlpha(movedDistance / _totalWeaveDistance);
await UniTask.Yield(PlayerLoopTiming.Update);
}
}
// 仮で少し内側に移動させる
{
Vector3 basePos = transform.position;
Vector3 targetPos = Vector3.Lerp(_passagePoints[_passagePoints.Count - 1],
_passagePoints[_passagePoints.Count - 2], .25f);
float elapsedTime = 0;
float moveRate = 0;
Turn(targetPos);
while (moveRate < 1)
{
elapsedTime += Time.deltaTime;
moveRate = Mathf.Clamp01(elapsedTime / moveSpeed);
transform.position = Vector3.Lerp(basePos, targetPos, moveRate);
await UniTask.Yield(PlayerLoopTiming.Update);
}
}
_animator.SetBool(IsMove, false);
web.canCatch = true;
// 移動完了後はランダム移動に設定
state = SpiderState.RandomMoving;
}
/// <summary>
/// 後ろに回転する
/// TODO: アニメーションへの対応
/// </summary>
private void Turn(Vector3 target)
{
Vector3 dir = target - transform.position;
transform.rotation = Quaternion.LookRotation(dir);
}
#endregion
/// <summary>
/// 巣のアルファ値を設定する
/// </summary>
/// <param name="alpha">アルファ値 (0-1)</param>
public void SetWebAlpha(float alpha)
{
if (!_renderer) return;
_renderer.material.SetFloat(SPropAlpha, alpha);
}
}
| 27.219718 | 115 | 0.559661 | [
"MIT"
] | letconst/gimmick-field-public | Assets/Users/Endo/Scripts/Character/Enemy/Spider.cs | 10,708 | C# |
using Hevadea.Framework.Graphic;
using Hevadea.GameObjects.Entities.Components.Actions;
using Hevadea.GameObjects.Tiles;
using Hevadea.Storage;
using Hevadea.Utils;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace Hevadea.GameObjects.Entities.Components.States
{
public sealed class Health : EntityComponent, IEntityComponentDrawableOverlay, IEntityComponentUpdatable, IEntityComponentSaveLoad
{
private float _knckbckX, _knckbckY, _coolDown, _heathbarTimer = 0f;
public bool Invicible { get; set; } = false;
public bool ShowHealthBar { get; set; } = true;
public bool TakeKnockback { get; set; } = true;
public bool NaturalRegeneration { get; set; } = false;
public double NaturalregenerationSpeed { get; set; } = 1.0;
public float Value { get; private set; }
public float MaxValue { get; }
public float ValuePercent => Value / MaxValue;
public delegate void GetHurtByEntityHandle(Entity entity, float damages);
public delegate void GetHurtByTileHandler(Tile tile, float damages, int tX, int tY);
public event EventHandler Killed;
public event GetHurtByTileHandler HurtedByTile;
public event GetHurtByEntityHandle HurtedByEntity;
public Health(float maxHealth)
{
Value = maxHealth;
MaxValue = maxHealth;
}
public void DrawOverlay(SpriteBatch spriteBatch, GameTime gameTime)
{
if (ShowHealthBar && Math.Abs(Value - MaxValue) > 0.05)
{
var barY = Owner.Y + 4;
var barX = Owner.X - 15;
var rect = new Rectangle((int)barX, (int)barY, (int)(30 * ValuePercent), 2);
spriteBatch.FillRectangle(new Rectangle((int)barX + 1, (int)barY + 1, rect.Width, rect.Height),
Color.Black * 0.45f);
var red = (int)Math.Sqrt(255 * 255 * (1 - ValuePercent));
var green = (int)Math.Sqrt(255 * 255 * (ValuePercent));
spriteBatch.FillRectangle(rect, new Color(red, green, 0));
}
}
public void OnGameSave(EntityStorage store)
{
store.Value(nameof(Heal), Value);
if (NaturalRegeneration)
store.Value("natural_regeneration", _coolDown);
}
public void OnGameLoad(EntityStorage store)
{
Value = store.ValueOf(nameof(Heal), Value);
if (NaturalRegeneration)
_coolDown = store.ValueOf("natural_regeneration", 0f);
}
public void Update(GameTime gameTime)
{
_coolDown += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (NaturalRegeneration && _coolDown > 5)
{
Value = (float)Math.Min(MaxValue, Value + NaturalregenerationSpeed * gameTime.ElapsedGameTime.TotalSeconds);
}
if (_knckbckX != 0f || _knckbckY != 0f)
{
Owner.GetComponent<Move>()?.Do(_knckbckX, _knckbckY);
_knckbckX *= 0.9f;
_knckbckY *= 0.9f;
}
}
// Entity get hurt by a other entity (ex: Zombie)
public void Hurt(Entity entity, float damages, bool knockback = true)
{
if (knockback)
{
var dir = new Vector2(Owner.X - entity.X, Owner.Y - entity.Y);
if (dir.Length() > 1f)
{
dir.Normalize();
}
Hurt(entity, damages, dir.X, dir.Y);
}
else
{
Hurt(entity, damages, 0, 0);
}
}
public void Hurt(Entity entity, float damages, Direction attackDirection)
{
var dir = attackDirection.ToPoint();
Hurt(entity, damages, dir.X * damages, dir.Y * damages);
}
public void Hurt(Entity entity, float damages, float knockbackX, float knockbackY)
{
if (Invicible) return;
_coolDown = 0f;
HurtedByEntity?.Invoke(entity, damages);
Value = Math.Max(0, Value - damages);
if (TakeKnockback && Owner.HasComponent<Move>())
{
_knckbckX += knockbackX;
_knckbckY += knockbackY;
}
if (Math.Abs(Value) < 0.1f) Die();
}
// Entity get hurt by a tile (ex: lava)
public void Hurt(Tile tile, float damages, int tX, int tY)
{
if (Invicible) return;
_coolDown = 0f;
HurtedByTile?.Invoke(tile, damages, tX, tY);
Value = Math.Max(0, Value - damages);
if (Math.Abs(Value) < 0.1f) Die();
}
// The mob is heal by a mod (healing itself)
public void Heal(Entity entity, float damages, Direction attackDirection)
{
Value = Math.Min(MaxValue, Value + damages);
}
// The entity in heal b
public void Heal(Tile tile, float damages, int tileX, int tileY)
{
Value = Math.Min(MaxValue, Value + damages);
}
public void HealAll()
{
Value = MaxValue;
}
public void Die()
{
Owner.GetComponent<Pickup>()?.LayDownEntity();
Owner.GetComponent<Inventory>()?.Content.DropOnGround(Owner.Level, Owner.X, Owner.Y);
Owner.GetComponent<Dropable>()?.Drop();
Owner.Remove();
Killed?.Invoke(this, null);
}
}
} | 33.549133 | 135 | 0.5398 | [
"MIT"
] | krisz2000/hevadea | src/Hevadea/GameObjects/Entities/Components/States/Health.cs | 5,806 | C# |
using Uno.UI.Samples.Controls;
using Uno.UI.Samples.Presentation.SamplePages;
using Windows.UI.Xaml.Controls;
namespace Uno.UI.Samples.Content.UITests.ButtonTestsControl
{
[SampleControlInfo("Button", "Simple_Button_With_CanExecute_Changing", typeof(ButtonTestsViewModel), ignoreInSnapshotTests: true)]
public sealed partial class Simple_Button_With_CanExecute_Changing : UserControl
{
public Simple_Button_With_CanExecute_Changing()
{
this.InitializeComponent();
}
}
}
| 28.529412 | 131 | 0.816495 | [
"Apache-2.0"
] | 06needhamt/uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/Button/Simple_Button_With_CanExecute_Changing.xaml.cs | 485 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using agileways.usermgt.shared.server.Services;
using agileways.usermgt.shared.Models.DirectoryObjects;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace agileways.usermgt.admin.client.Server.Controllers
{
[Authorize]
[ApiController]
public class AppRoleController : ControllerBase
{
private readonly ILogger<AppRoleController> _logger;
private IGraphClient _graph;
public AppRoleController(IGraphClient graph, ILogger<AppRoleController> logger)
{
_logger = logger;
_graph = graph;
}
[HttpGet("app/{appId}/roles")]
public async Task<IEnumerable<Role>> GetRolesForAppRegistrations(string appId)
{
return await _graph.GetAppRolesForAppRegistration(appId);
}
[HttpPost("apps/{id}/roles")]
public async Task<IActionResult> AddRoleToAppRegistration(string id, [FromBody] Role role)
{
var result = await _graph.AddRoleToAppRegistration(id, role);
if (result)
{
return Ok();
}
return BadRequest("something bad happened");
}
[HttpPut("apps/{id}/roles")]
public async Task<IActionResult> UpdateAppRegistrationRole(string id, [FromBody] Role role)
{
var result = await _graph.UpdateAppRegistrationRole(id, role);
if (result)
{
return Ok();
}
return BadRequest("something bad happened");
}
[HttpGet("apps/{id}/roles/{roleId}")]
public async Task<Role> GetRoleForAppReg(string id, string roleId) =>
await _graph.GetAppRoleForAppRegistration(id, roleId);
}
}
| 32.068966 | 99 | 0.634946 | [
"MIT"
] | AgileDave/b2c-usermgt | agileways.usermgt.admin.client/Server/Controllers/DirectoryObjects/AppRoleController.cs | 1,860 | C# |
// /* **********************************************************************************
// *
// * Copyright (c) Sky Sanders. All rights reserved.
// *
// * This source code is subject to terms and conditions of the Microsoft Public
// * License (Ms-PL). A copy of the license can be found in the license.htm file
// * included in this distribution.
// *
// * You must not remove this notice, or any other, from this software.
// *
// * **********************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace Csharp.Utilities.ConsoleTools
{
/// <summary>
/// Implements a process that can be monitored and interacted with.
///
/// StandardOut and StandardError are monitored at character and line level and
/// made visible by thread safe accessors.
///
/// StandardIn is writable via SetInput.
///
/// Is there a standard implementation of this somewhere that I do not know about?
/// It seems like a common enough requirement for legacy interop.
/// </summary>
public class ControllableProcess : IDisposable
{
#region Private fields
private readonly Queue<string> _errorQueue;
private readonly Queue<string> _inputQueue;
private readonly Queue<string> _ouputQueue;
private readonly Process _process;
private string _currentErrorLine;
private string _currentOutputLine;
private bool _disposed;
private Thread _errorThread;
private Thread _inputThread;
private object _outputLock = new object();
private Thread _outputThread;
private bool _stopped;
#endregion
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
/// <param name="arguments"></param>
/// <param name="workingDirectory"></param>
public ControllableProcess(string filename, string arguments, string workingDirectory)
{
_inputQueue = new Queue<string>();
_ouputQueue = new Queue<string>();
_errorQueue = new Queue<string>();
ProcessStartInfo startInfo = new ProcessStartInfo
{
Arguments = arguments,
CreateNoWindow = true,
ErrorDialog = false,
FileName = filename,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WorkingDirectory = workingDirectory
};
_process = new Process { StartInfo = startInfo };
}
public string CurrentErrorLine
{
get
{
lock (_outputLock)
{
return _currentErrorLine;
}
}
}
public string CurrentOutputLine
{
get
{
lock (_outputLock)
{
return _currentOutputLine;
}
}
}
public event EventHandler<OutputEventArgs> HasOutputLine;
public event EventHandler<OutputEventArgs> HasOutputChar;
public event EventHandler<OutputEventArgs> HasErrorLine;
public event EventHandler<OutputEventArgs> HasErrorChar;
/// <summary>
///
/// </summary>
public void Start()
{
_process.Start();
StateObject outState = new StateObject
{
StreamOut = _process.StandardOutput,
Queue = _ouputQueue,
IsStandardOut = true
};
_outputThread = new Thread(ReadQueueWorker);
_outputThread.Start(outState);
StateObject errState = new StateObject
{
StreamOut = _process.StandardError,
Queue = _errorQueue,
IsStandardError = true
};
_errorThread = new Thread(ReadQueueWorker);
_errorThread.Start(errState);
StateObject inputState = new StateObject
{
StreamIn = _process.StandardInput,
Queue = _inputQueue
};
_inputThread = new Thread(WriteQueueWorker);
_inputThread.Start(inputState);
}
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public int Stop(string input)
{
return Stop(100, 100, 100, 100, input);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public int Stop()
{
return Stop(null);
}
/// <summary>
///
/// </summary>
/// <param name="timeout"></param>
/// <param name="inputTimeout"></param>
/// <param name="outputTimeout"></param>
/// <param name="errorTimeout"></param>
/// <param name="input"></param>
/// <returns></returns>
public int Stop(int timeout, int inputTimeout, int outputTimeout, int errorTimeout, string input)
{
try
{
if (_inputThread.IsAlive)
{
// user is trying to interact with the process to kill it.
if (input != null)
{
// don't set stopped yet, want let the input queue finish
SetInput(input);
// give the worker threads time to join
Thread.Sleep(timeout);
}
else
{
_stopped = true;
ThreadSoftStop(_inputThread, inputTimeout);
}
}
_stopped = true;
ThreadSoftStop(_outputThread, outputTimeout);
ThreadSoftStop(_errorThread, errorTimeout);
_process.WaitForExit(timeout);
}
catch (Exception ex)
{
// probably going to see ThreadAbortExceptions here
// figure out what to do here
throw;
}
return _process.HasExited ? _process.ExitCode : -999;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string[] GetOutput()
{
return LockAndDequeue(_ouputQueue);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string[] GetError()
{
return LockAndDequeue(_errorQueue);
}
/// <summary>
/// </summary>
/// <param name="input"></param>
public void SetInput(string input)
{
LockAndEnqueue(_inputQueue, input);
}
#region Implementation of IDisposable
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
try
{
_process.Kill();
_process.Dispose();
}
catch (Exception ex)
{
// sanity check. empty catch later
throw;
}
}
_disposed = true;
}
}
#endregion
#region Private implementation
protected virtual void OnHasErrorLine(OutputEventArgs e)
{
EventHandler<OutputEventArgs> handler = HasErrorLine;
if (handler != null) handler(this, e);
}
protected virtual void OnHasErrorChar(OutputEventArgs e)
{
EventHandler<OutputEventArgs> handler = HasErrorChar;
if (handler != null) handler(this, e);
}
protected virtual void OnHasOutputLine(OutputEventArgs e)
{
EventHandler<OutputEventArgs> handler = HasOutputLine;
if (handler != null) handler(this, e);
}
protected virtual void OnHasOutputChar(OutputEventArgs e)
{
EventHandler<OutputEventArgs> handler = HasOutputChar;
if (handler != null) handler(this, e);
}
/// <summary>
/// </summary>
/// <param name="state">StatObject with StreamOut</param>
private void ReadQueueWorker(object state)
{
StateObject s = (StateObject)state;
lock (_outputLock)
{
if (s.IsStandardError)
{
_currentErrorLine = string.Empty;
}
if (s.IsStandardOut)
{
_currentOutputLine = string.Empty;
}
}
char[] buffer = new char[1];
int charsRead = s.StreamOut.Read(buffer, 0, 1);
while (charsRead > 0)
{
OutputEventArgs evtArgs;
lock (_outputLock)
{
evtArgs = new OutputEventArgs { Char = buffer[0], CurrentLine = _currentOutputLine };
if (s.IsStandardOut)
{
_currentOutputLine += buffer[0];
OnHasOutputChar(evtArgs);
}
if (s.IsStandardError)
{
_currentErrorLine += buffer[0];
OnHasErrorChar(evtArgs);
}
}
// necessary i think to allow parsing of chars and lines
// to work properly
Thread.Sleep(1);
lock (_outputLock)
{
//TODO: this is cheap and faulty. good nuff fo gubment werk but probably
//implement a simple lexer/parser in here.
// end of line?
if (buffer[0] == '\n')
{
LockAndEnqueue(s.Queue, _currentOutputLine.TrimEnd());
_currentOutputLine = string.Empty;
if (s.IsStandardOut)
{
OnHasOutputLine(evtArgs);
}
if (s.IsStandardError)
{
OnHasErrorLine(evtArgs);
}
}
}
if (_stopped)
{
break;
}
charsRead = s.StreamOut.Read(buffer, 0, 1);
}
}
/// <summary>
/// </summary>
/// <param name="state">StatObject with StreamIn</param>
private void WriteQueueWorker(object state)
{
StateObject s = (StateObject)state;
while (!_stopped)
{
if (s.Queue.Count > 0 && !_stopped)
{
string[] inputs = LockAndDequeue(s.Queue);
foreach (string input in inputs)
{
s.StreamIn.Write(input);
}
}
Thread.Sleep(100);
}
}
/// <summary>
/// Thread safety helper
/// </summary>
/// <param name="queue"></param>
/// <returns></returns>
private static string[] LockAndDequeue(Queue<string> queue)
{
string[] result;
lock (queue)
{
result = new string[queue.Count];
queue.CopyTo(result, 0);
queue.Clear();
}
return result;
}
/// <summary>
/// Thread safety helper
/// </summary>
/// <param name="queue"></param>
/// <param name="input"></param>
private static void LockAndEnqueue(Queue<string> queue, string input)
{
lock (queue)
{
queue.Enqueue(input);
}
}
private static void ThreadSoftStop(Thread thread, int timeout)
{
if (thread.IsAlive && !thread.Join(timeout))
{
try
{
thread.Abort();
}
catch (ThreadAbortException ex)
{
}
}
}
#endregion
#region Nested type: StateObject
private class StateObject
{
public bool IsStandardError;
public bool IsStandardOut;
public Queue<string> Queue;
public StreamWriter StreamIn;
public StreamReader StreamOut;
}
#endregion
}
public class OutputEventArgs : EventArgs
{
public char Char;
public string CurrentLine;
}
}
| 29.263158 | 105 | 0.464553 | [
"MIT"
] | nh43de/csharp-utils | Csharp.Utilities/ConsoleTools/ControllableProcess.cs | 13,346 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace JL
{
public class BodyPart : MonoBehaviour
{
Joint _joint;
TargetJoint[] _myJoints;
BodyPart[] _subParts;
[SerializeField] GameObject[] _bloodCubes;
public int health = 5;
[System.NonSerialized] int _myHealth;
public delegate void OnDie();
public event OnDie OnDieEvent;
Transform topParent;
public void InitBodyPart(CharacterTop characterTop)
{
topParent = characterTop.transform;
}
private void Start()
{
_myHealth = health;
_joint = GetComponent<Joint>();
_myJoints = GetComponentsInChildren<TargetJoint>();
_subParts = GetComponentsInChildren<BodyPart>();
foreach (GameObject bloodCube in _bloodCubes)
{
bloodCube.SetActive(false);
}
}
public void Damage(int damage)
{
_myHealth -= damage;
if (_myHealth < health) health = _myHealth;
SendMessageUpwards("GotDamage", damage, SendMessageOptions.DontRequireReceiver);
if (_myHealth <= 0)
{
OnDieEvent?.Invoke();
OnDieEvent = null;
foreach (BodyPart subPart in _subParts)
{
subPart.health = 0;
}
foreach (GameObject bloodCube in _bloodCubes)
{
bloodCube.SetActive(true);
}
if (_joint) Destroy(_joint);
if (TryGetComponent(out HeadHealth headHealth))
{
transform.SetParent(null);
}
else
{
transform.SetParent(topParent);
}
foreach (TargetJoint _myJoint in _myJoints)
_myJoint.enabled = false;
}
}
}
}
| 19.831169 | 83 | 0.684348 | [
"MIT"
] | leorid/MurderLoop | Assets/BodyPart.cs | 1,529 | C# |
using ActiveQueryBuilder.Core;
using ActiveQueryBuilder.Web.Core;
using ActiveQueryBuilder.Web.Server;
using ActiveQueryBuilder.Web.Server.Services;
using AspNetCoreCrossDomain.Providers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace AspNetCoreCrossDomain.Controllers
{
public class QueryBuilderController : Controller
{
private readonly IQueryBuilderService _aqbs;
// Use IQueryBuilderService to get access to the server-side instances of Active Query Builder objects.
// See the registration of this service in the Startup.cs.
public QueryBuilderController(IQueryBuilderService aqbs)
{
_aqbs = aqbs;
}
public string CheckToken(string token)
{
// get Token QueryBuilder provider from the store
var provider = (TokenQueryBuilderProvider)_aqbs.Provider;
// check if the item with specified key exists in the storage.
if (provider.CheckToken(token))
// Return empty string in the case of success
return string.Empty;
// Return the new token to the client if the specified token doesn't exist.
return provider.CreateToken();
}
/// <summary>
/// Creates and initializes new instance of the QueryBuilder object for the given identifier if it doesn't exist.
/// </summary>
/// <param name="name">Instance identifier of object in the current session.</param>
/// <returns></returns>
public ActionResult CreateQueryBuilder(string name)
{
try
{
// Create an instance of the QueryBuilder object
_aqbs.GetOrCreate(name);
return StatusCode(200);
}
catch (QueryBuilderException e)
{
return StatusCode(400, e.Message);
}
}
}
} | 35.964912 | 123 | 0.618049 | [
"MIT"
] | ActiveDbSoft/active-query-builder-3-asp-net-core-samples-csharp | CrossDomain/Controllers/QueryBuilderController.cs | 2,052 | C# |
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
// using UnityStandardAssets.CrossPlatformInput;
namespace Coop
{
[Flags, Serializable]
public enum PlayerInputMode
{
Game = 1,
UI = 2,
Disabled = 3
}
[RequireComponent(typeof(CoopCharacter2D), typeof(Health))]
public class CoopUserControl : MonoBehaviour
{
private CoopCharacter2D m_Character;
private bool m_Jump;
private bool m_FiringPrimary = false;
private bool m_FiringSecondary = false;
private bool m_CanFire = true;
private bool m_HideGun = false; //TODO: Don't think I'll need this afterall.
internal bool CanFire
{
get { return m_CanFire; }
set {
m_CanFire = value;
m_HideGun = !value;
}
}
internal void ExitLevel()
{
// TODO: Play sound.
if (gun) SetGun(null);
GetComponent<Animator>().SetTrigger("FlickerOut");
SetInputMode(PlayerInputMode.Disabled);
}
private PlayerInputMode m_InputMode = PlayerInputMode.Game;
[Header("Controls")]
public PlayerControlData controlData;
private bool isAiming = false;
[Header("Character Customization")]
[SerializeField] private Sprite m_HeadSprite;
public Sprite HeadSprite
{
get { return m_HeadSprite; }
set {
if(value)
{
headSocket.GetComponentInChildren<SpriteRenderer>().sprite = value;
m_HeadSprite = value;
}
else
Debug.LogWarning("Did not set null head sprite.");
}
}
[Header("Weapon")]
public Gun gun;
public GameObject gunSocket;
public GameObject armSocket;
public GameObject headSocket;
public SpriteRenderer crosshair;
[Header("Other")]
[Tooltip("How long until first respawn attempt.")]
[SerializeField] private float m_RespawnTimer = 2f;
[Tooltip("How long between repeat respawn attempts.")]
[SerializeField] private float m_RespawnRetryTimer = 1f;
private MultiplayerFollow m_Cam;
private Vector3 m_Bounds;
private Health m_HP;
private Animator m_Anim;
private BoxCollider2D m_Coll;
private LevelManager m_LevelManager;
private void Awake()
{
m_LevelManager = FindObjectOfType<LevelManager>();
m_Character = GetComponent<CoopCharacter2D>();
m_HP = GetComponent<Health>();
m_Anim = GetComponent<Animator>();
m_Coll = GetComponent<BoxCollider2D>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
m_Cam = FindObjectOfType<MultiplayerFollow>();
m_Bounds = GetComponent<SpriteRenderer>().sprite.bounds.extents;
// Trigger logic in public property.
if(m_HeadSprite != null) HeadSprite = m_HeadSprite;
crosshair.transform.SetParent(null);
}
private void Update()
{
if(m_HP.isDead || m_InputMode == PlayerInputMode.Disabled)
return;
if (!m_Jump)
{
// Read the jump input in Update so button presses aren't missed.
m_Jump = Input.GetButtonDown(controlData.jump);
}
//TODO: Package this and move it to an appropriate script/method
#region Manage Game Input
if (m_InputMode == PlayerInputMode.Game)
{
if(m_CanFire)
{
var crossPos = crosshair.transform.position;
if(isAiming)
{
// Bi-directional ('Crosshair') aiming.
crossPos += new Vector3(Input.GetAxis(controlData.aimHorizontal), Input.GetAxis(controlData.aimVertical), 0);
crosshair.transform.position = crossPos;
// Rotate arm to point gun at target.
LookAtRotate(crossPos, armSocket);
LookAtRotate(crossPos, headSocket, -40, 40);
}
else {
// Up/Down only
float verticalAim = Input.GetAxis(controlData.aimVertical);
if (Mathf.Abs(verticalAim) > 0)
{
UnidirectionalRotate(verticalAim, armSocket);
}
}
// manage game controls
#region Axis Firing Input
float fireAxis = Input.GetAxis(controlData.primaryFire);
if (fireAxis != 0 && m_CanFire)
{
FiringState weap = fireAxis > 0 ? FiringState.Primary : FiringState.Secondary;
if(weap == FiringState.Primary)
{
m_FiringPrimary = true;
}
else
{
m_FiringSecondary = true;
}
gun.Fire(weap, gunSocket.transform.right * Mathf.Sign(transform.localScale.x));
}
#endregion
#region Keyboard Firing Input
else if (Input.GetButton(controlData.primaryFire) && m_CanFire)
{
m_FiringPrimary = true;
if(isAiming)
gun.FireAtTarget(FiringState.Primary, crossPos);
else
gun.Fire(FiringState.Primary, gunSocket.transform.right * Mathf.Sign(transform.localScale.x));
}
else if (Input.GetButton(controlData.secondaryFire) && m_CanFire)
{
m_FiringSecondary = true;
if(isAiming)
gun.FireAtTarget(FiringState.Secondary, crossPos);
else
gun.Fire(FiringState.Secondary, gunSocket.transform.right * Mathf.Sign(transform.localScale.x));
}
#endregion
else if (m_FiringPrimary || m_FiringSecondary) // These may be "true" from the previous frame while buttons are not still held this frame.
{
gun.StopFiring();
m_FiringPrimary = false;
m_FiringSecondary = false;
}
else if (Input.GetButtonDown(controlData.aimActivate) && m_CanFire)
{
if(isAiming) {
// TODO: Use reticle/crosshairs for cursor
Cursor.lockState = CursorLockMode.Locked;
//Cursor.visible = false;
crosshair.gameObject.SetActive(false);
headSocket.transform.rotation = Quaternion.Euler(headSocket.transform.rotation.eulerAngles.x, headSocket.transform.rotation.eulerAngles.y, 0);
isAiming = false;
} else {
Cursor.lockState = CursorLockMode.Locked;
//Cursor.visible = true;
crosshair.gameObject.SetActive(true);
crosshair.transform.position = gun.AmmoSpawnLocation.position;
// Debug.Log("Crosshair should show now.");
isAiming = true;
}
}
else if (Input.GetButtonDown(controlData.switchPlayerWeapon) && m_CanFire)
{
// Debug.Log("Pressed: switchPlayerWeapon " + Input.GetAxis(controlData.switchPlayerWeapon));
SetGun(CoopGameManager.instance.GetAvailableGun(this));
}
}
if (Input.GetButtonDown(controlData.interact))
{
// Debug.Log("Pressed: interact");
Collider2D[] res = new Collider2D[1];
ContactFilter2D filter = new ContactFilter2D()
{
useTriggers = true,
useLayerMask = true,
layerMask = LayerMask.GetMask("Interactable")
};
m_Coll.OverlapCollider(filter, res);
if(res[0])
{
Interactable obj = res[0].GetComponent<Interactable>();
if(obj != null) obj.Interact();
}
}
else if (Input.GetButtonDown(controlData.openMenuPause))
{
if (Time.timeScale != 0)
{
// Debug.Log("Pressed: Pause");
m_LevelManager.ShowPauseMenu();
Time.timeScale = 0;
// TODO: Show pause menu
SetInputMode(Coop.PlayerInputMode.UI);
}
}
}
#endregion
//TODO: Package this and move it to an appropriate script/method???
// ... or is this section even necessary? Feels more like the menu should have the code.
#region Manage UI Input
else if (m_InputMode == PlayerInputMode.UI)
{
// manage UI controls
if (Input.GetButtonDown(controlData.openMenuPause))
{ // && !canGoBack
// Close menu
m_LevelManager.HidePauseMenu();
Time.timeScale = 1;
Debug.Log("Pressed: Unpause");
SetInputMode(PlayerInputMode.Game);
}
else if (Input.GetButtonDown(controlData.submitButton))
{
// Activate menu item
Debug.Log("Pressed: submitButton");
}
else if (Input.GetButtonDown(controlData.cancelButton))
{ // && canGoBack
// Go back
Debug.Log("Pressed: cancelButton");
}
}
#endregion
}
private void LookAtRotate(Vector3 lookAtPos, GameObject rotateObject, int? minZRotation = null, int? maxZRotation = null)
{
var direction = (lookAtPos - rotateObject.transform.position).normalized;
var targetAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
var newAngle = targetAngle;
if(Mathf.Sign(transform.lossyScale.x) > 0) // Facing forward / right
{
if(minZRotation != null)
newAngle = Mathf.Clamp(newAngle, (int)minZRotation, newAngle);
if(maxZRotation != null)
newAngle = Mathf.Clamp(newAngle, newAngle, (int)maxZRotation);
}
else
{
if(minZRotation != null && maxZRotation != null)
{
if(newAngle >= -90 && newAngle <= 0)
newAngle = -(int)minZRotation - 180;
if(newAngle > 0 && newAngle <= 90)
newAngle = 180 - (int)maxZRotation;
if(newAngle > 90 && newAngle < 180)
newAngle = Mathf.Clamp(newAngle, 180 - (int)maxZRotation, 180);
if(newAngle > -180 && newAngle < -90)
newAngle = Mathf.Clamp(newAngle, -180, - (int)minZRotation - 180);
}
newAngle += 180;
}
//newAngle += (Mathf.Sign(transform.lossyScale.x) < 0 ? 180 : 0);
// Simply rotating an additional 180 degrees if the player is facing backward works and makes sense but feels like a hack. What's the better way to do this?
rotateObject.transform.rotation = Quaternion.Euler(0, 0, newAngle);
}
private void UnidirectionalRotate(float verticalAim, GameObject rotateObject)
{
var character = GetComponent<CoopCharacter2D>();
if (character.NormalGravity < 0) verticalAim *= -1;
rotateObject.transform.Rotate(0, 0, verticalAim);
var zRotation = rotateObject.transform.localRotation.eulerAngles.z;
if (zRotation > 90 && zRotation < 270)
{
if (zRotation < 180) zRotation = 90; else zRotation = 270;
rotateObject.transform.localRotation = Quaternion.Euler(0, 0, zRotation);
}
}
/// <summary>
/// Replace the current gun with a new one.
/// </summary>
/// <param name="playerGun">A reference to a prefab to instantiate a player gun from.</param>
internal void SetGun(Gun playerGun)
{
if(this.gun != null) Destroy(this.gun.gameObject);
if(playerGun == null) // null gun will let us do a tutorial level without guns, just switches, doors, etc.
{
m_HideGun = true;
this.gun = null;
// CoopGameManager.instance.SetPlayerGun(this, null);
return; // Temp
}
else
{
this.gun = Instantiate(playerGun, gunSocket.transform.position, gunSocket.transform.rotation, gunSocket.transform);
gun.m_OwnerCharacter = m_Character;
// TODO: This seems so wrong. Gotta clean up the pipeline somehow.
CoopGameManager.instance.SetPlayerGun(this, playerGun);
}
}
private void FixedUpdate()
{
if(m_HP.isDead || m_InputMode == PlayerInputMode.Disabled)
return;
// Read the inputs.
bool crouch = Input.GetButton(controlData.crouchButton);
float h = Input.GetAxis(controlData.horizontalAxis);
// Pass all parameters to the character control script.
m_Character.Move(h, crouch, m_Jump);
m_Jump = false;
}
//Clamp player position to within camera view
private void LateUpdate()
{
if(m_HP.isDead || m_InputMode == PlayerInputMode.Disabled)
return;
transform.position = m_Cam.ConstrainToView(transform.position, m_Bounds);
if(crosshair.gameObject.activeInHierarchy)
crosshair.transform.position = m_Cam.ConstrainToView(crosshair.transform.position, crosshair.GetComponent<SpriteRenderer>().sprite.bounds.extents, true);
}
public void Die()
{
m_Anim.SetTrigger("Die");
m_Coll.enabled = false;
armSocket.SetActive(false);
headSocket.SetActive(false);
}
/// <summary>Called by an animation event at the end of the player's death animation.</summary>
public IEnumerator Respawn()
{
//keep player dead for 2 seconds
yield return new WaitForSeconds(m_RespawnTimer);
while(m_HP.isDead)
{
RespawnPlayer();
yield return new WaitForSeconds(m_RespawnRetryTimer);
}
}
private void RespawnPlayer()
{
if(!m_LevelManager.ActiveCheckpoint.IsVisible)
{
var cam = FindObjectOfType<MultiplayerFollow>();
var camPos = cam.transform.position;
// GetComponent<SpriteRenderer>().enabled = false;
// transform.position = new Vector3(camPos.x, camPos.y, 0);
return;
}
//GetComponent<SpriteRenderer>().enabled = true;
m_Anim.SetTrigger("Respawn");
m_Coll.enabled = true;
armSocket.SetActive(true);
headSocket.SetActive(true);
m_HP.enabled = true;
m_HP.ResetHealth();
// TODO: proper respawning
transform.position = LevelManager.GetRespawnLocation();
StartCoroutine(RespawnFlash());
}
private System.Collections.IEnumerator RespawnFlash()
{
float numFlashes = 4f;
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
SpriteRenderer armSprite = armSocket.GetComponentInChildren<SpriteRenderer>();
SpriteRenderer headSprite = headSocket.GetComponentInChildren<SpriteRenderer>();
Color initColor = sprite.color;
float r = 150f / 255f, g = 150f / 255f, b = 150f / 255f;
Color flashColor = new Color(r, g, b);
for(int i = 0; i < numFlashes * 2; ++i)
{
Color color = sprite.color == initColor ? flashColor : initColor;
sprite.color = color;
armSprite.color = color;
headSprite.color = color;
yield return new WaitForSeconds(0.5f);
}
sprite.color = initColor;
armSprite.color = initColor;
headSprite.color = initColor;
yield return null;
}
public void SetInputMode(PlayerInputMode mode)
{
m_InputMode = mode;
}
public PlayerInputMode GetInputMode()
{
return m_InputMode;
}
/// <summary>
/// OnGUI is called for rendering and handling GUI events.
/// This function can be called multiple times per frame (one call per event).
/// </summary>
void OnGUI()
{
if(!isAiming) return;
var direction = (crosshair.transform.position - headSocket.transform.position).normalized;
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
string output = "Current: " + (headSocket.transform.rotation.eulerAngles.z).ToString() + ", Target: " + angle;
GUI.TextArea(new Rect(headSocket.transform.position, new Vector2(100, 100)) , output);
}
void OnDrawGizmos() {
if(!isAiming) return;
Gizmos.color = Color.yellow;
Gizmos.DrawLine(gunSocket.transform.position, crosshair.transform.position);
}
}
}
| 32.869023 | 162 | 0.611828 | [
"Unlicense"
] | Seanharrs/coopjam | Assets/_Scripts/Character/CoopUserControl.cs | 15,810 | C# |
using System;
using Gtk;
using UI = Gtk.Builder.ObjectAttribute;
using SkyEditor.RomEditor.Domain.Rtdx;
using SkyEditor.RomEditor.Domain.Rtdx.Models;
using SkyEditorUI.Infrastructure;
using SkyEditor.RomEditor.Domain.Rtdx.Constants;
namespace SkyEditorUI.Controllers
{
class FixedPokemonController : Widget
{
[UI] private ListStore? fixedPokemonStore;
[UI] private TreeView? fixedPokemonTree;
[UI] private ListStore? movesStore;
[UI] private ListStore? dungeonsStore;
[UI] private ListStore? speciesStore;
[UI] private EntryCompletion? movesCompletion;
[UI] private EntryCompletion? dungeonsCompletion;
[UI] private EntryCompletion? speciesCompletion;
private IFixedPokemonCollection fixedPokemon;
private IRtdxRom rom;
private const int IndexColumn = 0;
private const int EnumNameColumn = 1;
private const int SpeciesColumn = 2;
private const int Move1Column = 3;
private const int Move2Column = 4;
private const int Move3Column = 5;
private const int Move4Column = 6;
private const int DungeonColumn = 7;
private const int LevelColumn = 8;
private const int HpColumn = 9;
private const int AtkBoostColumn = 10;
private const int SpAtkBoostColumn = 11;
private const int DefBoostColumn = 12;
private const int SpDefBoostColumn = 13;
private const int SpeedBoostColumn = 14;
private const int InvitationIndexColumn = 15;
public FixedPokemonController(IRtdxRom rom) : this(new Builder("FixedPokemon.glade"), rom)
{
}
private FixedPokemonController(Builder builder, IRtdxRom rom) : base(builder.GetRawOwnedObject("main"))
{
builder.Autoconnect(this);
this.rom = rom;
this.fixedPokemon = rom.GetFixedPokemonCollection();
movesStore!.AppendAll(AutocompleteHelpers.GetMoves(rom));
dungeonsStore!.AppendAll(AutocompleteHelpers.GetDungeons(rom));
speciesStore!.AppendAll(AutocompleteHelpers.GetPokemon(rom));
for (int i = 0; i < fixedPokemon.Entries.Count; i++)
{
AddToStore(fixedPokemon.Entries[i], i);
}
}
private void AddToStore(FixedPokemonModel model, int index)
{
fixedPokemonStore!.AppendValues(
index,
((FixedCreatureIndex) index).ToString(),
AutocompleteHelpers.FormatPokemon(rom, model.PokemonId),
AutocompleteHelpers.FormatMove(rom, model.Move1),
AutocompleteHelpers.FormatMove(rom, model.Move2),
AutocompleteHelpers.FormatMove(rom, model.Move3),
AutocompleteHelpers.FormatMove(rom, model.Move4),
AutocompleteHelpers.FormatDungeon(rom, model.DungeonIndex),
(int) model.Level,
(int) model.HitPoints,
(int) model.AttackBoost,
(int) model.SpAttackBoost,
(int) model.DefenseBoost,
(int) model.SpDefenseBoost,
(int) model.SpeedBoost,
(int) model.InvitationIndex
);
}
private void OnSpeciesEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var pokemonIndex = AutocompleteHelpers.ExtractPokemon(args.NewText);
if (pokemonIndex.HasValue)
{
fixedPokemonStore.SetValue(iter, SpeciesColumn,
AutocompleteHelpers.FormatPokemon(rom!, pokemonIndex.Value));
fixedPokemon.Entries[path.Indices[0]].PokemonId = pokemonIndex.Value;
}
}
}
private void OnSpeciesEditingStarted(object sender, EditingStartedArgs args)
{
var editable = (Entry) args.Editable;
editable.Completion = speciesCompletion;
}
private void OnMove1Edited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var moveIndex = AutocompleteHelpers.ExtractMove(args.NewText);
if (moveIndex.HasValue)
{
fixedPokemonStore.SetValue(iter, Move1Column,
AutocompleteHelpers.FormatMove(rom!, moveIndex.Value));
fixedPokemon.Entries[path.Indices[0]].Move1 = moveIndex.Value;
}
}
}
private void OnMove2Edited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var moveIndex = AutocompleteHelpers.ExtractMove(args.NewText);
if (moveIndex.HasValue)
{
fixedPokemonStore.SetValue(iter, Move2Column,
AutocompleteHelpers.FormatMove(rom!, moveIndex.Value));
fixedPokemon.Entries[path.Indices[0]].Move2 = moveIndex.Value;
}
}
}
private void OnMove3Edited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var moveIndex = AutocompleteHelpers.ExtractMove(args.NewText);
if (moveIndex.HasValue)
{
fixedPokemonStore.SetValue(iter, Move3Column,
AutocompleteHelpers.FormatMove(rom!, moveIndex.Value));
fixedPokemon.Entries[path.Indices[0]].Move3 = moveIndex.Value;
}
}
}
private void OnMove4Edited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var moveIndex = AutocompleteHelpers.ExtractMove(args.NewText);
if (moveIndex.HasValue)
{
fixedPokemonStore.SetValue(iter, Move4Column,
AutocompleteHelpers.FormatMove(rom!, moveIndex.Value));
fixedPokemon.Entries[path.Indices[0]].Move4 = moveIndex.Value;
}
}
}
private void OnMoveEditingStarted(object sender, EditingStartedArgs args)
{
var editable = (Entry) args.Editable;
editable.Completion = movesCompletion;
}
private void OnLevelEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.Level = value;
}
fixedPokemonStore.SetValue(iter, LevelColumn, (int) entry.Level);
}
}
private void OnHpEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (short.TryParse(args.NewText, out short value))
{
entry.HitPoints = value;
}
fixedPokemonStore.SetValue(iter, HpColumn, (int) entry.HitPoints);
}
}
private void OnAtkBoostEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.AttackBoost = value;
}
fixedPokemonStore.SetValue(iter, AtkBoostColumn, (int) entry.AttackBoost);
}
}
private void OnSpAtkBoostEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.SpAttackBoost = value;
}
fixedPokemonStore.SetValue(iter, SpAtkBoostColumn, (int) entry.SpAttackBoost);
}
}
private void OnDefBoostEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.DefenseBoost = value;
}
fixedPokemonStore.SetValue(iter, DefBoostColumn, (int) entry.DefenseBoost);
}
}
private void OnSpDefBoostEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.SpDefenseBoost = value;
}
fixedPokemonStore.SetValue(iter, SpDefBoostColumn, (int) entry.SpDefenseBoost);
}
}
private void OnSpeedBoostEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.SpeedBoost = value;
}
fixedPokemonStore.SetValue(iter, SpeedBoostColumn, (int) entry.SpeedBoost);
}
}
private void OnInvitationIndexEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var entry = fixedPokemon.Entries[path.Indices[0]];
if (byte.TryParse(args.NewText, out byte value))
{
entry.InvitationIndex = value;
}
fixedPokemonStore.SetValue(iter, InvitationIndexColumn, (int) entry.InvitationIndex);
}
}
private void OnDungeonIndexEdited(object sender, EditedArgs args)
{
var path = new TreePath(args.Path);
if (fixedPokemonStore!.GetIter(out var iter, path))
{
var dungeonIndex = AutocompleteHelpers.ExtractDungeon(args.NewText);
if (dungeonIndex.HasValue)
{
fixedPokemonStore.SetValue(iter, DungeonColumn,
AutocompleteHelpers.FormatDungeon(rom!, dungeonIndex.Value));
fixedPokemon.Entries[path.Indices[0]].DungeonIndex = dungeonIndex.Value;
}
}
}
private void OnDungeonIndexEditingStarted(object sender, EditingStartedArgs args)
{
var editable = (Entry) args.Editable;
editable.Completion = dungeonsCompletion;
}
private void OnAddClicked(object sender, EventArgs args)
{
var entry = new FixedPokemonModel();
fixedPokemon.Entries.Add(entry);
AddToStore(entry, fixedPokemon.Entries.Count - 1);
}
private void OnRemoveClicked(object sender, EventArgs args)
{
if (fixedPokemonTree!.Selection.GetSelected(out var model, out var iter))
{
var path = model.GetPath(iter);
int index = path.Indices[0];
fixedPokemon.Entries.RemoveAt(index);
var store = (ListStore) model;
store.Remove(ref iter);
store.FixIndices(IndexColumn);
}
}
}
}
| 38.749235 | 111 | 0.559861 | [
"MIT"
] | Blue587/DreamNexus | SkyEditor.UI/Controllers/FixedPokemon/FixedPokemonController.cs | 12,671 | C# |
using SampleBase.Interfaces;
using System;
namespace SampleBase
{
public abstract class ConsoleTestBase : ITestBase
{
private readonly IMessagePrinter msgPrinter;
public string Name { get; set; }
protected ConsoleTestBase(string title)
{
Name = title;
msgPrinter = new ConsoleMessagePrinter();
}
protected ConsoleTestBase()
{
Name = GetType().Name;
msgPrinter = new ConsoleMessagePrinter();
}
public abstract void RunTest();
public void PrintInfo(string message, bool newLine = true)
{
msgPrinter.PrintInfo(message, newLine);
}
public void PrintObject(object obj, bool newLine = true, ConsoleColor consoleColor = ConsoleColor.White)
{
msgPrinter.PrintObject(obj, newLine, consoleColor);
}
public void PrintWarning(string message, bool newLine = true)
{
msgPrinter.PrintWarning(message, newLine);
}
public void PrintError(string message, bool newLine = true)
{
msgPrinter.PrintError(message, newLine);
}
public void PrintSuccess(string message, bool newLine = true)
{
msgPrinter.PrintSuccess(message, newLine);
}
public IMessagePrinter GetMessagePrinter()
{
return msgPrinter;
}
public string WaitToInput()
{
return Console.ReadLine();
}
public void WaitToContinue(string? tip = null)
{
if (tip != null)
Console.WriteLine(tip);
Console.ReadLine();
}
}
}
| 24.855072 | 112 | 0.569679 | [
"Apache-2.0"
] | AvenSun/opencvsharp_samples | SampleBase/Console/ConsoleTestBase.cs | 1,717 | C# |
#region Copyright and License
// Copyright 2010..2017 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ARSoft.Tools.Net.Dns
{
/// <summary>
/// <para>Recursive resolver</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc1035">RFC 1035</see>
/// </para>
/// </summary>
public class RecursiveDnsResolver : IDnsResolver
{
private class State
{
public int QueryCount;
}
private DnsCache _cache = new DnsCache();
private NameserverCache _nameserverCache = new NameserverCache();
private readonly IResolverHintStore _resolverHintStore;
/// <summary>
/// Provides a new instance with custom root server hints
/// </summary>
/// <param name="resolverHintStore"> The resolver hint store with the IP addresses of the root server hints</param>
public RecursiveDnsResolver(IResolverHintStore resolverHintStore = null)
{
_resolverHintStore = resolverHintStore ?? new StaticResolverHintStore();
IsResponseValidationEnabled = true;
QueryTimeout = 2000;
MaximumReferalCount = 20;
}
/// <summary>
/// Gets or sets a value indicating how much referals for a single query could be performed
/// </summary>
public int MaximumReferalCount { get; set; }
/// <summary>
/// Milliseconds after which a query times out.
/// </summary>
public int QueryTimeout { get; set; }
/// <summary>
/// Gets or set a value indicating whether the response is validated as described in
/// <see
/// cref="!:http://tools.ietf.org/id/draft-vixie-dnsext-dns0x20-00.txt">
/// draft-vixie-dnsext-dns0x20-00
/// </see>
/// </summary>
public bool IsResponseValidationEnabled { get; set; }
/// <summary>
/// Gets or set a value indicating whether the query labels are used for additional validation as described in
/// <see
/// cref="!:http://tools.ietf.org/id/draft-vixie-dnsext-dns0x20-00.txt">
/// draft-vixie-dnsext-dns0x20-00
/// </see>
/// </summary>
// ReSharper disable once InconsistentNaming
public bool Is0x20ValidationEnabled { get; set; }
/// <summary>
/// Clears the record cache
/// </summary>
public void ClearCache()
{
_cache = new DnsCache();
_nameserverCache = new NameserverCache();
}
/// <summary>
/// Resolves specified records.
/// </summary>
/// <typeparam name="T"> Type of records, that should be returned </typeparam>
/// <param name="name"> Domain, that should be queried </param>
/// <param name="recordType"> Type the should be queried </param>
/// <param name="recordClass"> Class the should be queried </param>
/// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns>
public List<T> Resolve<T>(DomainName name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet)
where T : DnsRecordBase
{
var res = ResolveAsync<T>(name, recordType, recordClass);
res.Wait();
return res.Result;
}
/// <summary>
/// Resolves specified records as an asynchronous operation.
/// </summary>
/// <typeparam name="T"> Type of records, that should be returned </typeparam>
/// <param name="name"> Domain, that should be queried </param>
/// <param name="recordType"> Type the should be queried </param>
/// <param name="recordClass"> Class the should be queried </param>
/// <param name="token"> The token to monitor cancellation requests </param>
/// <returns> A list of matching <see cref="DnsRecordBase">records</see> </returns>
public Task<List<T>> ResolveAsync<T>(DomainName name, RecordType recordType = RecordType.A, RecordClass recordClass = RecordClass.INet, CancellationToken token = default(CancellationToken))
where T : DnsRecordBase
{
if (name == null)
throw new ArgumentNullException(nameof(name), "Name must be provided");
return ResolveAsyncInternal<T>(name, recordType, recordClass, new State(), token);
}
private async Task<DnsMessage> ResolveMessageAsync(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
{
for (; state.QueryCount <= MaximumReferalCount; state.QueryCount++)
{
DnsMessage msg = await new DnsClient(GetBestNameservers(recordType == RecordType.Ds ? name.GetParentName() : name), QueryTimeout)
{
IsResponseValidationEnabled = IsResponseValidationEnabled,
Is0x20ValidationEnabled = Is0x20ValidationEnabled
}.ResolveAsync(name, recordType, recordClass, new DnsQueryOptions()
{
IsRecursionDesired = false,
IsEDnsEnabled = true
}, token);
if ((msg != null) && ((msg.ReturnCode == ReturnCode.NoError) || (msg.ReturnCode == ReturnCode.NxDomain)))
{
if (msg.IsAuthoritiveAnswer)
return msg;
List<NsRecord> referalRecords = msg.AuthorityRecords
.Where(x =>
(x.RecordType == RecordType.Ns)
&& (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
.OfType<NsRecord>()
.ToList();
if (referalRecords.Count > 0)
{
if (referalRecords.GroupBy(x => x.Name).Count() == 1)
{
var newServers = referalRecords.Join(msg.AdditionalRecords.OfType<AddressRecordBase>(), x => x.NameServer, x => x.Name, (x, y) => new { y.Address, TimeToLive = Math.Min(x.TimeToLive, y.TimeToLive) }).ToList();
if (newServers.Count > 0)
{
DomainName zone = referalRecords.First().Name;
foreach (var newServer in newServers)
{
_nameserverCache.Add(zone, newServer.Address, newServer.TimeToLive);
}
continue;
}
else
{
NsRecord firstReferal = referalRecords.First();
var newLookedUpServers = await ResolveHostWithTtlAsync(firstReferal.NameServer, state, token);
foreach (var newServer in newLookedUpServers)
{
_nameserverCache.Add(firstReferal.Name, newServer.Item1, Math.Min(firstReferal.TimeToLive, newServer.Item2));
}
if (newLookedUpServers.Count > 0)
continue;
}
}
}
// Response of best known server is not authoritive and has no referrals --> No chance to get a result
throw new Exception("Could not resolve " + name);
}
}
// query limit reached without authoritive answer
throw new Exception("Could not resolve " + name);
}
private async Task<List<T>> ResolveAsyncInternal<T>(DomainName name, RecordType recordType, RecordClass recordClass, State state, CancellationToken token)
where T : DnsRecordBase
{
List<T> cachedResults;
if (_cache.TryGetRecords(name, recordType, recordClass, out cachedResults))
{
return cachedResults;
}
List<CNameRecord> cachedCNames;
if (_cache.TryGetRecords(name, RecordType.CName, recordClass, out cachedCNames))
{
return await ResolveAsyncInternal<T>(cachedCNames.First().CanonicalName, recordType, recordClass, state, token);
}
DnsMessage msg = await ResolveMessageAsync(name, recordType, recordClass, state, token);
// check for cname
List<DnsRecordBase> cNameRecords = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClass == recordClass) && x.Name.Equals(name)).ToList();
if (cNameRecords.Count > 0)
{
_cache.Add(name, RecordType.CName, recordClass, cNameRecords, DnsSecValidationResult.Indeterminate, cNameRecords.Min(x => x.TimeToLive));
DomainName canonicalName = ((CNameRecord) cNameRecords.First()).CanonicalName;
List<DnsRecordBase> matchingAdditionalRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(canonicalName)).ToList();
if (matchingAdditionalRecords.Count > 0)
{
_cache.Add(canonicalName, recordType, recordClass, matchingAdditionalRecords, DnsSecValidationResult.Indeterminate, matchingAdditionalRecords.Min(x => x.TimeToLive));
return matchingAdditionalRecords.OfType<T>().ToList();
}
return await ResolveAsyncInternal<T>(canonicalName, recordType, recordClass, state, token);
}
// check for "normal" answer
List<DnsRecordBase> answerRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClass == recordClass) && x.Name.Equals(name)).ToList();
if (answerRecords.Count > 0)
{
_cache.Add(name, recordType, recordClass, answerRecords, DnsSecValidationResult.Indeterminate, answerRecords.Min(x => x.TimeToLive));
return answerRecords.OfType<T>().ToList();
}
// check for negative answer
SoaRecord soaRecord = msg.AuthorityRecords
.Where(x =>
(x.RecordType == RecordType.Soa)
&& (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
.OfType<SoaRecord>()
.FirstOrDefault();
if (soaRecord != null)
{
_cache.Add(name, recordType, recordClass, new List<DnsRecordBase>(), DnsSecValidationResult.Indeterminate, soaRecord.NegativeCachingTTL);
return new List<T>();
}
// authoritive response does not contain answer
throw new Exception("Could not resolve " + name);
}
private async Task<List<Tuple<IPAddress, int>>> ResolveHostWithTtlAsync(DomainName name, State state, CancellationToken token)
{
List<Tuple<IPAddress, int>> result = new List<Tuple<IPAddress, int>>();
var aaaaRecords = await ResolveAsyncInternal<AaaaRecord>(name, RecordType.Aaaa, RecordClass.INet, state, token);
result.AddRange(aaaaRecords.Select(x => new Tuple<IPAddress, int>(x.Address, x.TimeToLive)));
var aRecords = await ResolveAsyncInternal<ARecord>(name, RecordType.A, RecordClass.INet, state, token);
result.AddRange(aRecords.Select(x => new Tuple<IPAddress, int>(x.Address, x.TimeToLive)));
return result;
}
private IEnumerable<IPAddress> GetBestNameservers(DomainName name)
{
Random rnd = new Random();
while (name.LabelCount > 0)
{
List<IPAddress> cachedAddresses;
if (_nameserverCache.TryGetAddresses(name, out cachedAddresses))
{
return cachedAddresses.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ThenBy(x => rnd.Next());
}
name = name.GetParentName();
}
return _resolverHintStore.RootServers.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ThenBy(x => rnd.Next());
}
}
} | 37.64966 | 216 | 0.69645 | [
"MIT"
] | zjccwboy/DnsServer | ARSoft.Tools.Dotnet/Dns/Resolver/RecursiveDnsResolver.cs | 11,071 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
//
// 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("RDL Engine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("My-FyiReporting Software")]
[assembly: AssemblyProduct("RDL Project")]
[assembly: AssemblyCopyright("Copyright (C) 2011-2012 Peter Gill")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.15.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyName("")]
| 41.338983 | 84 | 0.707667 | [
"Apache-2.0"
] | Art8m/My-FyiReporting | RdlEngine/AssemblyInfo.cs | 2,439 | C# |
using System.Web.Mvc;
namespace BasketGraphQLAPI
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 20.833333 | 80 | 0.656 | [
"MIT"
] | jpreecedev/basket-graphql-scratch | backend/BasketGraphQLAPI/App_Start/FilterConfig.cs | 252 | C# |
using QuantumHangar.HangarChecks;
using Sandbox.Game.Entities;
using Sandbox.Game.Entities.Character;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Torch.Commands;
using Torch.Commands.Permissions;
using VRage.Game.ModAPI;
namespace QuantumHangar.Commands
{
[Torch.Commands.Category("hangarmod")]
public class HangarAdminCommands : CommandModule
{
[Command("save", "Saves the grid you are looking at to hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void SaveGrid(string GridName = "")
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.SaveGrid(GridName));
}
[Command("list", "Lists all grids of given player")]
[Permission(MyPromoteLevel.Moderator)]
public async void ListGrids(string NameOrSteamID)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.ListGrids(NameOrSteamID));
}
[Command("load", "loads selected grid from a users hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void LoadGrid(string NameOrSteamID, int ID, bool FromSavePos = true)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.LoadGrid(NameOrSteamID, ID, FromSavePos));
}
[Command("remove", "removes the grid from the players hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void Remove(string NameOrSteamID, int ID)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.RemoveGrid(NameOrSteamID, ID));
}
[Command("sync", "Re-scans the folder for added or removed grids")]
[Permission(MyPromoteLevel.Moderator)]
public async void Sync(string NameOrSteamID)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.SyncHangar(NameOrSteamID));
}
[Command("syncall", "Re-scans all folders for added or removed grids")]
[Permission(MyPromoteLevel.Moderator)]
public async void SyncAll()
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.SyncAll());
}
[Command("autohangar", "Runs Autohangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void RunAutoHangar()
{
await HangarCommandSystem.RunAdminTaskAsync(() => AutoHangar.RunAutoHangar(false, Hangar.Config.AutoHangarStaticGrids, Hangar.Config.AutoHangarLargeGrids, Hangar.Config.AutoHangarSmallGrids, Hangar.Config.KeepPlayersLargestGrid));
}
[Command("autohanger-override", "Runs Autohanger with override values (staticgrids, largegrids, smallgrids, hangerLargest, saveAll)")]
[Permission(MyPromoteLevel.Moderator)]
public async void RunAutoHangerOverride(String[] overrides)
{
bool staticgrids = false;
bool largegrids = false;
bool smallgrids = false;
bool hangerLargest = false;
bool saveAll = false;
foreach (var _override in overrides) {
if (_override == "staticgrids")
{
staticgrids = true;
} else if (_override == "largegrids")
{
largegrids = true;
} else if (_override == "smallgrids")
{
smallgrids = true;
} else if (_override == "hangerLargest")
{
hangerLargest = true;
} else if (_override == "saveAll")
{
saveAll = true;
}
}
await HangarCommandSystem.RunAdminTaskAsync(() => AutoHangar.RunAutoHangar(saveAll, staticgrids, largegrids, smallgrids, hangerLargest));
}
[Command("enable", "Enables Hangar")]
[Permission(MyPromoteLevel.Moderator)]
public void Enable(bool SetPluginEnable)
{
Hangar.Config.PluginEnabled = SetPluginEnable;
}
[Command("saveall", "Saves All grids on server into hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void SaveAllGrids()
{
await HangarCommandSystem.RunAdminTaskAsync(() => AutoHangar.RunAutoHangar(true, true, true, true, true));
}
}
[Torch.Commands.Category("hm")]
public class HangarSimpAdminCommands : CommandModule
{
[Command("save", "Saves the grid you are looking at to hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void SaveGrid(string GridName = "")
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.SaveGrid(GridName));
}
[Command("list", "Lists all grids of given player")]
[Permission(MyPromoteLevel.Moderator)]
public async void ListGrids(string NameOrSteamID)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.ListGrids(NameOrSteamID));
}
[Command("load", "loads selected grid from a users hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void SaveGrid(string NameOrSteamID, int ID, bool FromSavePos = true)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.LoadGrid(NameOrSteamID, ID, FromSavePos));
}
[Command("remove", "removes the grid from the players hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void Remove(string NameOrSteamID, int ID)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.RemoveGrid(NameOrSteamID, ID));
}
[Command("sync", "Re-scans the folder for added or removed grids")]
[Permission(MyPromoteLevel.Moderator)]
public async void Sync(string NameOrSteamID)
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.SyncHangar(NameOrSteamID));
}
[Command("syncall", "Re-scans all folders for added or removed grids")]
[Permission(MyPromoteLevel.Moderator)]
public async void SyncAll()
{
AdminChecks User = new AdminChecks(Context);
await HangarCommandSystem.RunAdminTaskAsync(() => User.SyncAll());
}
[Command("autohangar", "Runs Autohangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void RunAutoHangar()
{
await HangarCommandSystem.RunAdminTaskAsync(() => AutoHangar.RunAutoHangar(false, Hangar.Config.AutoHangarStaticGrids, Hangar.Config.AutoHangarLargeGrids, Hangar.Config.AutoHangarSmallGrids, Hangar.Config.KeepPlayersLargestGrid));
}
[Command("autohanger-override", "Runs Autohanger with override values (staticgrids, largegrids, smallgrids, hangerLargest, saveAll)")]
[Permission(MyPromoteLevel.Moderator)]
public async void RunAutoHangerOverride(String[] overrides)
{
bool staticgrids = false;
bool largegrids = false;
bool smallgrids = false;
bool hangerLargest = false;
bool saveAll = false;
foreach (var _override in overrides) {
if (_override == "staticgrids")
{
staticgrids = true;
} else if (_override == "largegrids")
{
largegrids = true;
} else if (_override == "smallgrids")
{
smallgrids = true;
} else if (_override == "hangerLargest")
{
hangerLargest = true;
} else if (_override == "saveAll")
{
saveAll = true;
}
}
await HangarCommandSystem.RunAdminTaskAsync(() => AutoHangar.RunAutoHangar(saveAll, staticgrids, largegrids, smallgrids, hangerLargest));
}
[Command("enable", "Enables Hangar")]
[Permission(MyPromoteLevel.Moderator)]
public void Enable(bool SetPluginEnable)
{
Hangar.Config.PluginEnabled = SetPluginEnable;
}
[Command("saveall", "Saves All grids on server into hangar")]
[Permission(MyPromoteLevel.Moderator)]
public async void SaveAllGrids()
{
await HangarCommandSystem.RunAdminTaskAsync(() => AutoHangar.RunAutoHangar(true, true, true, true, true));
}
/*
[Command("exportgrid", "exportgrids to obj")]
[Permission(MyPromoteLevel.Admin)]
public void GridExporter()
{
Chat chat = new Chat(Context);
GridResult Result = new GridResult(true);
//Gets grids player is looking at
if (!Result.GetGrids(chat, Context.Player.Character as MyCharacter))
return;
chat.Respond(Result.Grids.Count.ToString());
typeof(MyCubeGrid).GetMethod("ExportToObjFile", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null, new object[] { Result.Grids, true, false });
chat.Respond("Done!");
//GridStamp stamp = Result.GenerateGridStamp();
}
*/
}
}
| 38.208494 | 242 | 0.610651 | [
"Apache-2.0"
] | BobDaRoss/QuantumHangar | Quantumhangar/Commands/HangarAdminCommands.cs | 9,898 | C# |
namespace SpeedHero.Web.Areas.Administration.ViewModels.Posts
{
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Common.Constants;
using SpeedHero.Data.Models;
using SpeedHero.Web.Areas.Administration.ViewModels.Base;
using SpeedHero.Web.Infrastructure.Mapping;
public class ShowPostsViewModel : AdministrationViewModel, IMapFrom<Post>
{
// Client side validation (Kendo)
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Display(Name = "Title")]
[Required]
[StringLength(ValidationConstants.PostTitleMaxLength, MinimumLength = ValidationConstants.PostTitleMinLength)]
public string Title { get; set; }
[Display(Name = "Author")]
[HiddenInput(DisplayValue = false)]
public string AuthorUserName { get; set; }
}
} | 33.846154 | 126 | 0.682955 | [
"MIT"
] | IvoSpasov/SpeedHero | Source/Web/SpeedHero.Web/Areas/Administration/ViewModels/Posts/ShowPostsViewModel.cs | 882 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace _05.ExtractAllSongTitlesWithXmlReader
{
public class Program
{
public static void Main()
{
IList<string> listOfTitles = new List<string>();
using (XmlReader reader = XmlReader.Create("../../../catalogue.xml"))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) &&
(reader.Name == "title"))
{
listOfTitles.Add(reader.ReadElementString());
}
}
}
foreach (var title in listOfTitles)
{
Console.WriteLine(title);
}
}
}
}
| 25.272727 | 81 | 0.472422 | [
"MIT"
] | GoranGit/Database | Homework/03. Processing XML in .Net/05.ExtractAllSongTitlesWithXmlReader/Program.cs | 836 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.