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 |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MilkVitaOrganization.Models
{
using System;
using System.Collections.Generic;
public partial class tbl_Supplier
{
public tbl_Supplier()
{
this.tbl_Demand = new HashSet<tbl_Demand>();
}
public int id { get; set; }
public string code { get; set; }
public string name { get; set; }
public Nullable<int> mobile { get; set; }
public string email { get; set; }
public string address { get; set; }
public virtual ICollection<tbl_Demand> tbl_Demand { get; set; }
}
}
| 31.875 | 85 | 0.521569 | [
"MIT"
] | bd71/MilkVita | MilkVitaOrganization/Models/tbl_Supplier.cs | 1,020 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TuDestinoHND.BL;
namespace TuDestinoHND.Win
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var productosBL = new ProductosBL();
var listadeProductos = productosBL.ObtenerProductos();
listadeProductosBindingSource.DataSource = listadeProductos;
}
}
}
| 21.814815 | 72 | 0.687606 | [
"MIT"
] | walmarqui/tuDestinoHND | TuDestinoHND/TuDestinoHND.Win/Form1.cs | 591 | C# |
namespace JsGeneratorLib
{
public class Expression : Pattern, IExpression
{
}
} | 14.285714 | 50 | 0.62 | [
"MIT"
] | nobiruwa/js-ast-csharp | JsGenerator/JsGeneratorLib/Expression.cs | 100 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Samples.Helpers
{
public static class StampHelper
{
// https://www.meziantou.net/2018/09/24/getting-the-date-of-build-of-a-net-assembly-at-runtime
public static DateTime GetBuildDate(Assembly assembly)
{
var attribute = assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(x => x.Key == "BuildDate");
if (attribute != null)
{
if (DateTime.TryParseExact(
attribute.Value,
"yyyyMMddHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out var result))
{
return result;
}
}
return default(DateTime);
}
public static string GetCommitHash(Assembly assembly)
{
var attribute = assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(x => x.Key == "CommitHash");
if (attribute != null)
{
return attribute.Value;
}
return string.Empty;
}
}
}
| 29.465116 | 102 | 0.538279 | [
"MIT"
] | EvergineTeam/WebGL.NET | src/Samples/Helpers/StampHelper.cs | 1,269 | C# |
using System.Threading.Tasks;
using BrickPort.Services.Commands;
namespace BrickPort.Infrastructure.Services.Domain.Commands
{
public class DomainCreateGameHandler : ICreateGameHandler
{
public Task<string> HandleAsync(CreateGameCommand command)
{
throw new System.NotImplementedException();
}
}
} | 26.615385 | 66 | 0.719653 | [
"MIT"
] | NaJ64/brickport | brickport-infrastructure-services-domain/src/commands/create-game.cs | 346 | C# |
using System.Collections.Generic;
namespace DataFlow.Models
{
public class EdFiMetadataProcessorField
{
public EdFiMetadataProcessorField()
{
SubFields = new List<EdFiMetadataProcessorField>();
}
public string Name { get; set; }
public string Type { get; set; }
public string SubType { get; set; }
public bool Required { get; set; }
public List<EdFiMetadataProcessorField> SubFields { get; set; }
}
}
| 24.65 | 71 | 0.622718 | [
"Apache-2.0"
] | schoolstacks/dataflow | DataFlow.Models/EdFiMetadataProcessorField.cs | 495 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine;
using Engine.Renderer;
using Engine.Platform;
using Engine.ObjectManagement;
using OgrePlugin;
using Engine.Resources;
using Anomalous.GuiFramework.Cameras;
namespace Medical.Controller
{
public class MeasurementGrid : IDisposable
{
private String name;
private ManualObject manualObject;
private SceneNode sceneNode;
private SceneViewController sceneViewController;
private bool visible = false;
private Color color = new Color(0f, 0.5019608f, 0f, 1f);
private Vector3 origin = Vector3.Zero;
private ResourceManager gridResources;
private float gridSpacingMM = 5.0f;
private float gridMax = 25.0f;
public MeasurementGrid(String name, SceneViewController sceneViewController)
{
gridResources = PluginManager.Instance.createLiveResourceManager("Grid");
var rendererResources = gridResources.getSubsystemResource("Ogre");
var materials = rendererResources.addResourceGroup("Materials");
materials.addResource(String.Format("{0}||Medical.Controller.Grid.", GetType().AssemblyQualifiedName), "EmbeddedResource", true);
gridResources.initializeResources();
this.name = name;
this.sceneViewController = sceneViewController;
sceneViewController.WindowCreated += new SceneViewWindowEvent(sceneViewController_WindowCreated);
sceneViewController.WindowDestroyed += new SceneViewWindowEvent(sceneViewController_WindowDestroyed);
}
public void Dispose()
{
}
public void sceneLoaded(SimScene scene)
{
SimSubScene subScene = scene.getDefaultSubScene();
if (subScene != null)
{
OgreSceneManager sceneManager = subScene.getSimElementManager<OgreSceneManager>();
manualObject = sceneManager.SceneManager.createManualObject(name + "__MeasurementManualObject");
manualObject.setRenderQueueGroup(95);
manualObject.RedrawRequired += manualObject_RedrawRequired;
sceneNode = sceneManager.SceneManager.createSceneNode(name + "__MeasurementManualObjectSceneNode");
sceneNode.attachObject(manualObject);
sceneNode.setVisible(visible);
sceneNode.setPosition(origin);
sceneManager.SceneManager.getRootSceneNode().addChild(sceneNode);
redraw();
}
}
public void sceneUnloading(SimScene scene)
{
SimSubScene subScene = scene.getDefaultSubScene();
if (subScene != null && manualObject != null)
{
OgreSceneManager sceneManager = subScene.getSimElementManager<OgreSceneManager>();
sceneManager.SceneManager.getRootSceneNode().removeChild(sceneNode);
sceneNode.detachObject(manualObject);
sceneManager.SceneManager.destroyManualObject(manualObject);
sceneManager.SceneManager.destroySceneNode(sceneNode);
manualObject = null;
sceneNode = null;
}
}
public bool Visible
{
get
{
return visible;
}
set
{
visible = value;
if (sceneNode != null)
{
sceneNode.setVisible(value);
}
}
}
public void changeGrid(float gridSpacingMM, float gridMax)
{
this.gridSpacingMM = gridSpacingMM;
this.gridMax = gridMax;
redraw();
}
/// <summary>
/// Draw a grid with the given spacing in milimeters taking up the space specified by gridmax.
/// </summary>
/// <param name="gridSpacingMM">The number of milimeters to space the grid lines.</param>
/// <param name="gridMax">The area of the grid in 3d units.</param>
private void redraw()
{
float gridSpacing = gridSpacingMM * (1.0f / SimulationConfig.UnitsToMM);
Vector3 startPoint = new Vector3(0.0f, -gridMax, 0.0f);
Vector3 endPoint = new Vector3(0.0f, gridMax, 0.0f);
manualObject.clear();
manualObject.begin("Grid", OperationType.OT_LINE_LIST);
for (float x = 0; x < gridMax; x += gridSpacing)
{
startPoint.x = x;
endPoint.x = x;
manualObject.position(ref startPoint);
manualObject.color(color.r, color.g, color.b, color.a);
manualObject.position(ref endPoint);
manualObject.color(color.r, color.g, color.b, color.a);
}
for (float x = -gridSpacing; x > -gridMax; x -= gridSpacing)
{
startPoint.x = x;
endPoint.x = x;
manualObject.position(ref startPoint);
manualObject.color(color.r, color.g, color.b, color.a);
manualObject.position(ref endPoint);
manualObject.color(color.r, color.g, color.b, color.a);
}
startPoint.x = -gridMax;
endPoint.x = gridMax;
for (float y = 0; y < gridMax; y += gridSpacing)
{
startPoint.y = y;
endPoint.y = y;
manualObject.position(ref startPoint);
manualObject.color(color.r, color.g, color.b, color.a);
manualObject.position(ref endPoint);
manualObject.color(color.r, color.g, color.b, color.a);
}
for (float y = -gridSpacing; y > -gridMax; y -= gridSpacing)
{
startPoint.y = y;
endPoint.y = y;
manualObject.position(ref startPoint);
manualObject.color(color.r, color.g, color.b, color.a);
manualObject.position(ref endPoint);
manualObject.color(color.r, color.g, color.b, color.a);
}
manualObject.end();
}
public Color Color
{
get
{
return color;
}
set
{
color = value;
}
}
public Vector3 Origin
{
get
{
return origin;
}
set
{
origin = value;
if (sceneNode != null)
{
sceneNode.setPosition(origin);
}
}
}
void sceneViewController_WindowDestroyed(SceneViewWindow window)
{
window.RenderingStarted -= window_RenderingStarted;
window.RenderingEnded -= window_RenderingEnded;
}
void sceneViewController_WindowCreated(SceneViewWindow window)
{
window.RenderingStarted += window_RenderingStarted;
window.RenderingEnded += window_RenderingEnded;
}
void window_RenderingStarted(SceneViewWindow window, bool currentCameraRender)
{
if (visible && currentCameraRender)
{
sceneNode.setVisible(true);
sceneNode.setOrientation(window.Orientation);
}
}
void window_RenderingEnded(SceneViewWindow window, bool currentCameraRender)
{
if (visible && currentCameraRender)
{
sceneNode.setVisible(false);
}
}
/// <summary>
/// Call this function before a screenshot is rendered to hide the
/// grid lines if you wish them hidden in the screenshot. This
/// function is setup to consume as an EventHandler, but it does not
/// actually use the arguments.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
public void ScreenshotRenderStarted(Object sender, EventArgs e)
{
if (visible)
{
if (sceneNode != null)
{
sceneNode.setVisible(false);
}
}
}
/// <summary>
/// Call this function after a screenshot is rendered to show the
/// grid lines if you hid them with ScreenshotRenderStarted. This
/// function is setup to consume as an EventHandler, but it does not
/// actually use the arguments.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
public void ScreenshotRenderCompleted(Object sender, EventArgs e)
{
if (visible)
{
if (sceneNode != null)
{
sceneNode.setVisible(true);
}
}
}
void manualObject_RedrawRequired(ManualObject manualObject)
{
redraw();
}
}
}
| 36.817121 | 142 | 0.538364 | [
"MIT"
] | AnomalousMedical/Medical | Standalone/Controller/Grid/MeasurementGrid.cs | 9,464 | C# |
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
namespace SpacedRepApp.Share
{
public class Category
{
public long Id { get; set; }
public string Name { get; set; }
public List<Note> Notes { get; set; }
}
}
| 19.785714 | 48 | 0.617329 | [
"MIT"
] | MariaWritesCode/SpacedRepetitionsApp | SpacedRepApp.Share/Category.cs | 279 | C# |
using System;
using CoreGraphics;
using UIKit;
using XForm.EventSubscription;
using XForm.Fields.Interfaces;
using XForm.Ios.ContentViews;
using XForm.Ios.ContentViews.Interfaces;
using XForm.Ios.FieldViews.Bases;
namespace XForm.Ios.FieldViews
{
public class OptionPickerFieldView : ValueFieldView<IOptionPickerField, ITitleButtonFieldContent, int?>
{
private IDisposable _buttonTouchUpInsideSubscription;
public OptionPickerFieldView(IntPtr handle) : base(handle)
{
}
internal override Func<ITitleButtonFieldContent> DefaultContentCreator { get; } = () => new TitleButtonFieldContent();
public UILabel TitleLabel => Content.TitleLabel;
public UIButton Button => Content.Button;
internal override void Setup()
{
base.Setup();
_buttonTouchUpInsideSubscription = Button.GetType()
.GetEvent(nameof(Button.TouchUpInside))
.WeakSubscribe(Button, ButtonTouchUpInside);
}
protected override void EnabledChanged(bool value)
{
base.EnabledChanged(value);
Button.Enabled = value;
ResignFirstResponder();
}
protected override void TitleChanged(string value)
{
base.TitleChanged(value);
TitleLabel.Text = Field.Title;
}
protected override void ValueChanged(int? value)
{
base.ValueChanged(value);
Button.SetTitle(Field.SelectedOptionText ?? "Option", UIControlState.Normal);
}
private void ButtonTouchUpInside(object sender, EventArgs e)
{
BecomeFirstResponder();
// Set first option as default
if (!Field.Value.HasValue && Field.OptionsCount > 0)
{
Field.Value = 0;
}
}
private void DoneTouchUp(object sender, EventArgs e)
{
ResignFirstResponder();
}
public override bool CanBecomeFirstResponder => true;
public override UIView InputAccessoryView
{
get
{
var toolbar = new UIToolbar(new CGRect(0, 0, 200, 44));
toolbar.Items = new[]
{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
new UIBarButtonItem(UIBarButtonSystemItem.Done, DoneTouchUp)
};
return toolbar;
}
}
public override UIView InputView
{
get
{
var pickerView = new UIPickerView();
pickerView.Model = new PickerViewModel(Field);
if (Field.Value.HasValue)
pickerView.Select(Field.Value.Value, 0, true);
return pickerView;
}
}
private class PickerViewModel: UIPickerViewModel
{
private readonly WeakReference<IOptionPickerField> _fieldReference;
public PickerViewModel(IOptionPickerField field)
{
_fieldReference = new WeakReference<IOptionPickerField>(field);
}
public override nint GetComponentCount(UIPickerView pickerView)
{
return 1;
}
public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
{
return _fieldReference.TryGetTarget(out var field) ? field.OptionsCount : 0;
}
public override string GetTitle(UIPickerView pickerView, nint row, nint component)
{
return _fieldReference.TryGetTarget(out var field) ? field.OptionTextForValue((int) row) : string.Empty;
}
public override void Selected(UIPickerView pickerView, nint row, nint component)
{
if (_fieldReference.TryGetTarget(out var field))
field.Value = (int) row;
}
}
}
} | 30.948905 | 126 | 0.553302 | [
"MIT"
] | DevelappersGmbH/XForm | XForm/Platform/Ios/FieldViews/OptionPickerFieldView.cs | 4,240 | C# |
using System.Collections;
using Archon.SwissArmyLib.Events.Loops;
using Archon.SwissArmyLib.Pooling;
using UnityEngine;
namespace Archon.SwissArmyLib.Coroutines
{
internal sealed class BetterCoroutine : IPoolable
{
internal int Id;
internal bool IsDone;
internal bool IsPaused;
internal bool IsParentPaused;
internal int UpdateLoopId;
internal IEnumerator Enumerator;
internal BetterCoroutine Parent;
internal BetterCoroutine Child;
internal float WaitTillTime = float.MinValue;
internal bool WaitTimeIsUnscaled;
internal bool WaitingForEndOfFrame;
internal bool IsLinkedToObject;
internal GameObject LinkedObject;
internal bool IsLinkedToComponent;
internal MonoBehaviour LinkedComponent;
void IPoolable.OnSpawned()
{
}
void IPoolable.OnDespawned()
{
var poolableYieldInstruction = Enumerator as IPoolableYieldInstruction;
if (poolableYieldInstruction != null)
poolableYieldInstruction.Despawn();
Id = -1;
IsDone = false;
IsPaused = false;
IsParentPaused = false;
UpdateLoopId = ManagedUpdate.EventIds.Update;
Enumerator = null;
Parent = null;
Child = null;
WaitTillTime = float.MinValue;
WaitTimeIsUnscaled = false;
WaitingForEndOfFrame = false;
LinkedObject = null;
LinkedComponent = null;
IsLinkedToObject = false;
IsLinkedToComponent = false;
}
}
} | 28.862069 | 83 | 0.61828 | [
"MIT"
] | ArchonInteractive/SwissArmyLib | Archon.SwissArmyLib/Coroutines/BetterCoroutine.cs | 1,674 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client;
public class UnfurlsBlockUnfurlPostRequest
: IPropagatePropertyAccessPath
{
public UnfurlsBlockUnfurlPostRequest() { }
public UnfurlsBlockUnfurlPostRequest(string link, bool wholeHost)
{
Link = link;
IsWholeHost = wholeHost;
}
private PropertyValue<string> _link = new PropertyValue<string>(nameof(UnfurlsBlockUnfurlPostRequest), nameof(Link), "link");
[Required]
[JsonPropertyName("link")]
public string Link
{
get => _link.GetValue(InlineErrors);
set => _link.SetValue(value);
}
private PropertyValue<bool> _wholeHost = new PropertyValue<bool>(nameof(UnfurlsBlockUnfurlPostRequest), nameof(IsWholeHost), "wholeHost");
[Required]
[JsonPropertyName("wholeHost")]
public bool IsWholeHost
{
get => _wholeHost.GetValue(InlineErrors);
set => _wholeHost.SetValue(value);
}
public virtual void SetAccessPath(string parentChainPath, bool validateHasBeenSet)
{
_link.SetAccessPath(parentChainPath, validateHasBeenSet);
_wholeHost.SetAccessPath(parentChainPath, validateHasBeenSet);
}
/// <inheritdoc />
[JsonPropertyName("$errors")]
public List<ApiInlineError> InlineErrors { get; set; } = new();
}
| 30.2 | 142 | 0.674614 | [
"Apache-2.0"
] | isabella232/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Dtos/UnfurlsBlockUnfurlPostRequest.generated.cs | 2,265 | C# |
using FluentValidation;
using FluentValidation.Results;
using Mimic.Application.Arguments.Dtos.Words;
using Mimic.Application.Interfaces;
using Mimic.Application.Resources;
namespace Mimic.Application.Validations.Words.Update
{
public class V01DataMustNotBeEmpty : AbstractValidator<UpdateWordDto>, IValidationHandler<UpdateWordDto>
{
public IValidationHandler<UpdateWordDto> Next { get; set; }
public ValidationResult Apply(UpdateWordDto validationDto)
{
RuleFor(word => word.Description)
.NotEmpty()
.WithMessage(
string.Format(ValidationsResource.CannotBeEmpty, "Description")
);
RuleFor(word => word.Points)
.NotNull()
.WithMessage(
string.Format(ValidationsResource.CannotBeEmpty, "Points")
);
return Validate(validationDto);
}
}
}
| 30.774194 | 108 | 0.634172 | [
"MIT"
] | ricardorinco/MimicAPI | src/Mimic.Application/Validations/Words/Update/V01DataMustNotBeEmpty.cs | 956 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FloattyObj : MonoBehaviour
{
public float Amplitude;
public float Speed;
protected float baseY;
protected float time = 0f;
void Start ()
{
baseY = transform.position.y;
}
void Update ()
{
time += Speed * Time.deltaTime;
Vector3 newPosition = transform.position;
newPosition.y = baseY + Mathf.Sin(time) * Amplitude;
transform.position = newPosition;
if (time > Mathf.Infinity - 1f)
{
time = 0f;
}
}
}
| 17.111111 | 60 | 0.597403 | [
"MIT"
] | Maeloo/A4scape_game | Assets/Game/Scripts/Utils/FloattyObj.cs | 618 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MinegamesAntiCheat;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
namespace MinegamesAntiCheatAPP
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private bool IsDllVaild()
{
if (File.Exists(Environment.CurrentDirectory + @"\MinegamesAntiCheat.dll"))
{
FileStream CheckIfDllVaild = new FileStream(Environment.CurrentDirectory + @"\MinegamesAntiCheat.dll", FileMode.Open, FileAccess.Read);
SHA256CryptoServiceProvider HashFile = new SHA256CryptoServiceProvider();
byte[] FileHashSHA256 = HashFile.ComputeHash(CheckIfDllVaild);
string TheFinalHashSHA256 = BitConverter.ToString(FileHashSHA256).Replace("-", string.Empty).ToLower();
if (TheFinalHashSHA256 == "8a2830bc33c8199979c061251e8dbef7bc1b097ed11714bcc0f3a79601ee2190")
{
CheckIfDllVaild.Close();
HashFile.Clear();
return true;
}
}
return false;
}
private void PreventReplacing(bool IsWillUse)
{
FileStream OpenFileToPreventReplacing = new FileStream(Environment.CurrentDirectory + @"\MinegamesAntiCheat.dll", FileMode.Open, FileAccess.Read);
if (IsWillUse == true)
{
OpenFileToPreventReplacing.Close();
}
}
private void AntiDllInjectionThread()
{
Task.Delay(7000).Wait();
AntiCheat.LockDownLibraryLoading_Aggressive(true);
AntiDebugging.ActiveAntiDebuggingProtection();
}
private void LeavingWindowThread()
{
AntiCheat.PreventLeavingOrNotFocusingOnWindowHandle(this.Handle);
}
private void Main_Load(object sender, EventArgs e)
{
if (IsDllVaild() == false)
{
MessageBox.Show("Unfixable Error while loading a library, please contact the software developer and try again.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
Environment.Exit(0);
Task.Delay(1000).Wait();
}
else
{
AntiDebugging.AntiDebuggerAttach();
if (AntiDebugging.CloseHandleAntiDebug() || AntiDebugging.RemoteDebuggerCheckAntiDebug())
{
MessageBox.Show("Yes, there's a debugger.", "Debugger Detected", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("nope, no debugger detected.", "Nope", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
if (AntiVirtualization.IsSandboxiePresent() || AntiVirtualization.IsWinePresent() || AntiVirtualization.IsComodoSandboxPresent() || AntiVirtualization.IsCuckooSandboxPresent() || AntiVirtualization.IsQihoo360SandboxPresent() || AntiVirtualization.IsEmulationPresent() || AntiVirtualization.IsVMPresent())
{
MessageBox.Show("Yes, you are in a virutal environment.", "Virtual Environment Detected", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Nope, no virtual environment detected.", "Not a Virtual Environment", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
MessageBox.Show("Your Hardware ID: " + Licensing.GetHardwareID(), "HWID", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
DialogResult GetInput = MessageBox.Show("Do you want me to prevent you from leaving the window of the program?", "Should i?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
PreventReplacing(true);
Thread DllInjectionPreventionThread = new Thread(new ThreadStart(AntiDllInjectionThread));
DllInjectionPreventionThread.Start();
if(GetInput == DialogResult.Yes)
{
Thread MonitorWindowThread = new Thread(new ThreadStart(LeavingWindowThread));
MonitorWindowThread.Start();
}
AntiDebugging.HideThreadsFromDebugger();
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
}
} | 44.330357 | 321 | 0.606244 | [
"MIT"
] | AhmedMinegames/MinegamesAntiCheat | MinegamesAntiCheatAPP/MinegamesAntiCheatAPP/Main.cs | 4,967 | C# |
namespace Blazorise
{
/// <summary>
/// Defines the behaviour of the text input.
/// </summary>
public enum TextRole
{
/// <summary>
/// Defines a default text input field.
/// </summary>
Text,
/// <summary>
/// Used for input fields that should contain an e-mail address.
/// </summary>
Email,
/// <summary>
/// Defines a password field.
/// </summary>
Password,
/// <summary>
/// Used for input fields that should contain a URL address.
/// </summary>
Url,
/// <summary>
/// Define a search field (like a site search, or Google search).
/// </summary>
Search,
/// <summary>
/// Define a field for entering a telephone number.
/// </summary>
Telephone,
}
}
| 22.564103 | 73 | 0.492045 | [
"MIT"
] | OuticNZ/Blazorise | Source/Blazorise/Enums/TextRole.cs | 882 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="PORX_IN150101UK31.Subject", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PORX_IN150101UK31.Subject", Namespace="urn:hl7-org:v3")]
public partial class PORX_IN150101UK31Subject {
private PORX_MT142201UK31ReimbursementClaimReject reimbursementClaimRejectField;
private string typeField;
private string typeCodeField;
private bool contextConductionIndField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PORX_IN150101UK31Subject() {
this.typeField = "ActRelationship";
this.typeCodeField = "SUBJ";
this.contextConductionIndField = false;
}
public PORX_MT142201UK31ReimbursementClaimReject ReimbursementClaimReject {
get {
return this.reimbursementClaimRejectField;
}
set {
this.reimbursementClaimRejectField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string typeCode {
get {
return this.typeCodeField;
}
set {
this.typeCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool contextConductionInd {
get {
return this.contextConductionIndField;
}
set {
this.contextConductionIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PORX_IN150101UK31Subject));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PORX_IN150101UK31Subject object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an PORX_IN150101UK31Subject object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PORX_IN150101UK31Subject object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out PORX_IN150101UK31Subject obj, out System.Exception exception) {
exception = null;
obj = default(PORX_IN150101UK31Subject);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PORX_IN150101UK31Subject obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PORX_IN150101UK31Subject Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PORX_IN150101UK31Subject)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PORX_IN150101UK31Subject object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an PORX_IN150101UK31Subject object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PORX_IN150101UK31Subject object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out PORX_IN150101UK31Subject obj, out System.Exception exception) {
exception = null;
obj = default(PORX_IN150101UK31Subject);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PORX_IN150101UK31Subject obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PORX_IN150101UK31Subject LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this PORX_IN150101UK31Subject object
/// </summary>
public virtual PORX_IN150101UK31Subject Clone() {
return ((PORX_IN150101UK31Subject)(this.MemberwiseClone()));
}
#endregion
}
}
| 41.014337 | 1,358 | 0.574063 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/PORX_IN150101UK31Subject.cs | 11,443 | C# |
using AutoMapper;
using ToDo.Api.Context;
using ToDo.Shared.Dtos;
using ToDo.Shared.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ToDo.Api.Service
{
/// <summary>
/// 待办事项的实现
/// </summary>
public class ToDoService : IToDoService
{
private readonly IUnitOfWork work;
private readonly IMapper Mapper;
public ToDoService(IUnitOfWork work, IMapper mapper)
{
this.work = work;
Mapper = mapper;
}
public async Task<ApiResponse> AddAsync(ToDoDto model)
{
try
{
var todo = Mapper.Map<ToDoEntity>(model);
await work.GetRepository<Context.ToDoEntity>().InsertAsync((Context.ToDoEntity)todo);
if (await work.SaveChangesAsync() > 0)
return new ApiResponse(true, todo);
return new ApiResponse("添加数据失败");
}
catch (Exception ex)
{
return new ApiResponse(ex.Message);
}
}
public async Task<ApiResponse> DeleteAsync(int id)
{
try
{
var repository = work.GetRepository<Context.ToDoEntity>();
var todo = await repository
.GetFirstOrDefaultAsync(predicate: x => x.Id.Equals(id));
repository.Delete(todo);
if (await work.SaveChangesAsync() > 0)
return new ApiResponse(true, "");
return new ApiResponse("删除数据失败");
}
catch (Exception ex)
{
return new ApiResponse(ex.Message);
}
}
public async Task<ApiResponse> GetAllAsync(QueryParameter parameter)
{
try
{
var repository = work.GetRepository<Context.ToDoEntity>();
var todos = await repository.GetPagedListAsync(predicate:
x => string.IsNullOrWhiteSpace(parameter.Search) ? true : x.Title.Contains(parameter.Search),
pageIndex: parameter.PageIndex,
pageSize: parameter.PageSize,
orderBy: source => source.OrderByDescending(t => t.CreateDate));
return new ApiResponse(true, todos);
}
catch (Exception ex)
{
return new ApiResponse(ex.Message);
}
}
public async Task<ApiResponse> GetAllAsync(ToDoParameter parameter)
{
try
{
var repository = work.GetRepository<Context.ToDoEntity>();
var todos = await repository.GetPagedListAsync(predicate:
x => (string.IsNullOrWhiteSpace(parameter.Search) ? true : x.Title.Contains(parameter.Search))
&& (parameter.Status == null ? true : x.Status.Equals(parameter.Status)),
pageIndex: parameter.PageIndex,
pageSize: parameter.PageSize,
orderBy: source => source.OrderByDescending(t => t.CreateDate));
return new ApiResponse(true, todos);
}
catch (Exception ex)
{
return new ApiResponse(ex.Message);
}
}
public async Task<ApiResponse> GetSingleAsync(int id)
{
try
{
var repository = work.GetRepository<Context.ToDoEntity>();
var todo = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id.Equals(id));
return new ApiResponse(true, todo);
}
catch (Exception ex)
{
return new ApiResponse(ex.Message);
}
}
public async Task<ApiResponse> UpdateAsync(ToDoDto model)
{
try
{
var dbToDo = Mapper.Map<ToDoEntity>(model);
var repository = work.GetRepository<Context.ToDoEntity>();
var todo = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id.Equals(dbToDo.Id));
todo.Title = dbToDo.Title;
todo.Content = dbToDo.Content;
todo.Status = dbToDo.Status;
todo.UpdateDate = DateTime.Now;
repository.Update(todo);
if (await work.SaveChangesAsync() > 0)
return new ApiResponse(true, todo);
return new ApiResponse("更新数据异常!");
}
catch (Exception ex)
{
return new ApiResponse(ex.Message);
}
}
}
}
| 34.313869 | 113 | 0.526909 | [
"MIT"
] | Memoyu/WPF-Learn-Demo | Project/ToDo/ToDo.Api/Service/ToDoService.cs | 4,755 | C# |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Functional
{
public static class CollectionExtensions
{
public static async Task<IEnumerable> AsEnumerable(this Task<ICollection> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<IList> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<IDictionary> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<Array> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<ArrayList> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<BitArray> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<Hashtable> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<Queue> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<Stack> collection)
=> await collection;
public static async Task<IEnumerable> AsEnumerable(this Task<SortedList> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<ICollection<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<IList<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<ISet<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<IOrderedEnumerable<T>> collection)
=> await collection;
public static async Task<IEnumerable<KeyValuePair<TKey, TValue>>> AsEnumerable<TKey, TValue>(this Task<IDictionary<TKey, TValue>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<IReadOnlyCollection<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<IReadOnlyList<T>> collection)
=> await collection;
public static async Task<IEnumerable<KeyValuePair<TKey, TValue>>> AsEnumerable<TKey, TValue>(this Task<IReadOnlyDictionary<TKey, TValue>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<T[]> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<List<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<LinkedList<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<Stack<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<Queue<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<HashSet<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<SortedSet<T>> collection)
=> await collection;
public static async Task<IEnumerable<KeyValuePair<TKey, TValue>>> AsEnumerable<TKey, TValue>(this Task<SortedDictionary<TKey, TValue>> collection)
=> await collection;
public static async Task<IEnumerable<KeyValuePair<TKey, TValue>>> AsEnumerable<TKey, TValue>(this Task<SortedList<TKey, TValue>> collection)
=> await collection;
public static async Task<IEnumerable<KeyValuePair<TKey, TValue>>> AsEnumerable<TKey, TValue>(this Task<Dictionary<TKey, TValue>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<IProducerConsumerCollection<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<ConcurrentBag<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<ConcurrentQueue<T>> collection)
=> await collection;
public static async Task<IEnumerable<T>> AsEnumerable<T>(this Task<ConcurrentStack<T>> collection)
=> await collection;
public static async Task<IEnumerable<KeyValuePair<TKey, TValue>>> AsEnumerable<TKey, TValue>(this Task<ConcurrentDictionary<TKey, TValue>> collection)
=> await collection;
}
}
| 39.451327 | 152 | 0.761104 | [
"MIT"
] | NathanMagnus/Functional | Functional.Enumerables.Extensions/CollectionExtensions.cs | 4,460 | C# |
using System;
using Windows.Storage;
namespace UWPLogoMaker.Utilities
{
public class SettingsHelper
{
public static void SetSetting<T>(string key, T value)
{
ApplicationData.Current.LocalSettings.Values[key] = value;
}
public static T GetSetting<T>(string key)
{
try
{
return (T) ApplicationData.Current.LocalSettings.Values[key];
}
catch (Exception)
{
return default(T);
}
}
}
public sealed class SettingKey
{
public static readonly SettingKey SaveMode = new SettingKey("SaveMode");
public static readonly SettingKey SavePath = new SettingKey("SavePath");
public static readonly SettingKey SaveToken = new SettingKey("SaveToken");
public static readonly SettingKey DatabaseVersion = new SettingKey("DatabaseVersion");
private SettingKey(string value)
{
Value = value;
}
public string Value { get; }
}
public class SettingManager
{
public static int GetSaveMode()
{
return SettingsHelper.GetSetting<int>(SettingKey.SaveMode.Value);
}
/// <summary>
/// Set save mode
/// 1: Save in the same folder
/// 2: Choose where to save
/// 3: Save in specific folder
/// </summary>
/// <param name="saveMode">save mode</param>
/// <param name="path">path to specific folder. Apply for 3</param>
/// <param name="token">token to access later. Apply for 3</param>
public static void SetSaveMode(int saveMode, string path = null, string token = null)
{
SettingsHelper.SetSetting(SettingKey.SaveMode.Value, saveMode);
if (path != null)
{
SettingsHelper.SetSetting(SettingKey.SavePath.Value, path);
SettingsHelper.SetSetting(SettingKey.SaveToken.Value, token);
}
}
public static string GetSavePath()
{
return SettingsHelper.GetSetting<string>(SettingKey.SavePath.Value);
}
public static string GetSaveToken()
{
return SettingsHelper.GetSetting<string>(SettingKey.SaveToken.Value);
}
}
}
| 30.012821 | 94 | 0.57924 | [
"Apache-2.0"
] | huntertran/05-UWPLogoMaker | UWPLogoMaker/Utilities/SettingsHelper.cs | 2,343 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("client")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("bb766b9a-5ce4-4942-b27c-108cb8153988")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 28.162162 | 56 | 0.695777 | [
"MIT"
] | euidong/khuLabMonitoring | labMonitoring/client/Properties/AssemblyInfo.cs | 1,475 | C# |
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
/*
* Regression tests for the mono JIT.
*
* Each test needs to be of the form:
*
* public static int test_<result>_<name> ();
*
* where <result> is an integer (the value that needs to be returned by
* the method to make it pass.
* <name> is a user-displayed name used to identify the test.
*
* The tests can be driven in two ways:
* *) running the program directly: Main() uses reflection to find and invoke
* the test methods (this is useful mostly to check that the tests are correct)
* *) with the --regression switch of the jit (this is the preferred way since
* all the tests will be run with optimizations on and off)
*
* The reflection logic could be moved to a .dll since we need at least another
* regression test file written in IL code to have better control on how
* the IL code looks.
*/
class Tests {
public static int Main (string[] args) {
return TestDriver.RunTests (typeof (Tests), args);
}
public static int test_0_catch () {
Exception x = new Exception ();
try {
throw x;
} catch (Exception e) {
if (e == x)
return 0;
}
return 1;
}
public static int test_0_finally_without_exc () {
int x;
try {
x = 1;
} catch (Exception e) {
x = 2;
} finally {
x = 0;
}
return x;
}
public static int test_0_finally () {
int x = 1;
try {
throw new Exception ();
} catch (Exception e) {
x = 2;
} finally {
x = 0;
}
return x;
}
public static int test_0_nested_finally () {
int a;
try {
a = 1;
} finally {
try {
a = 2;
} finally {
a = 0;
}
}
return a;
}
public static int test_0_byte_cast () {
int a;
long l;
ulong ul;
byte b = 0;
bool failed;
try {
a = 255;
failed = false;
checked {
b = (byte)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 1;
if (b != 255)
return -1;
try {
a = 0;
failed = false;
checked {
b = (byte)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
if (b != 0)
return -2;
try {
a = 256;
failed = true;
checked {
b = (byte)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 3;
if (b != 0)
return -3;
try {
a = -1;
failed = true;
checked {
b = (byte)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
if (b != 0)
return -4;
try {
double d = 0;
failed = false;
checked {
b = (byte)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 5;
if (b != 0)
return -5;
try {
double d = -1;
failed = true;
checked {
b = (byte)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 6;
if (b != 0)
return -6;
try {
double d = 255;
failed = false;
checked {
b = (byte)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 7;
if (b != 255)
return -7;
try {
double d = 256;
failed = true;
checked {
b = (byte)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 8;
if (b != 255)
return -8;
try {
l = 255;
failed = false;
checked {
b = (byte)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 9;
if (b != 255)
return -9;
try {
l = 0;
failed = false;
checked {
b = (byte)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 10;
if (b != 0)
return -10;
try {
l = 256;
failed = true;
checked {
b = (byte)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 11;
if (b != 0)
return -11;
try {
l = -1;
failed = true;
checked {
b = (byte)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 12;
if (b != 0)
return -12;
try {
ul = 256;
failed = true;
checked {
b = (byte)ul;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 13;
if (b != 0)
return -13;
return 0;
}
public static int test_0_sbyte_cast () {
int a;
long l;
sbyte b = 0;
bool failed;
try {
a = 255;
failed = true;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 1;
if (b != 0)
return -1;
try {
a = 0;
failed = false;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
if (b != 0)
return -2;
try {
a = 256;
failed = true;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 3;
if (b != 0)
return -3;
try {
a = -129;
failed = true;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
if (b != 0)
return -4;
try {
a = -1;
failed = false;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 5;
if (b != -1)
return -5;
try {
a = -128;
failed = false;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 6;
if (b != -128)
return -6;
try {
a = 127;
failed = false;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 7;
if (b != 127)
return -7;
try {
a = 128;
failed = true;
checked {
b = (sbyte)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 8;
if (b != 127)
return -8;
try {
double d = 127;
failed = false;
checked {
b = (sbyte)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 9;
if (b != 127)
return -9;
try {
double d = -128;
failed = false;
checked {
b = (sbyte)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 10;
if (b != -128)
return -10;
try {
double d = 128;
failed = true;
checked {
b = (sbyte)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 11;
if (b != -128)
return -11;
try {
double d = -129;
failed = true;
checked {
b = (sbyte)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 12;
if (b != -128)
return -12;
try {
l = 255;
failed = true;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 13;
if (b != -128)
return -13;
try {
l = 0;
failed = false;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 14;
if (b != 0)
return -14;
try {
l = 256;
failed = true;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 15;
if (b != 0)
return -15;
try {
l = -129;
failed = true;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 16;
if (b != 0)
return -16;
try {
l = -1;
failed = false;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 17;
if (b != -1)
return -17;
try {
l = -128;
failed = false;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 18;
if (b != -128)
return -18;
try {
l = 127;
failed = false;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 19;
if (b != 127)
return -19;
try {
l = 128;
failed = true;
checked {
b = (sbyte)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 20;
if (b != 127)
return -20;
try {
ulong ul = 128;
failed = true;
checked {
b = (sbyte)ul;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 21;
if (b != 127)
return -21;
return 0;
}
public static int test_0_ushort_cast () {
int a;
long l;
ulong ul;
ushort b;
bool failed;
try {
a = System.UInt16.MaxValue;
failed = false;
checked {
b = (ushort)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 1;
try {
a = 0;
failed = false;
checked {
b = (ushort)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
try {
a = System.UInt16.MaxValue + 1;
failed = true;
checked {
b = (ushort)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 3;
try {
a = -1;
failed = true;
checked {
b = (ushort)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
try {
double d = 0;
failed = false;
checked {
b = (ushort)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 5;
try {
double d = System.UInt16.MaxValue;
failed = false;
checked {
b = (ushort)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 6;
try {
double d = -1;
failed = true;
checked {
b = (ushort)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 7;
try {
double d = System.UInt16.MaxValue + 1.0;
failed = true;
checked {
b = (ushort)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 8;
try {
l = System.UInt16.MaxValue;
failed = false;
checked {
b = (ushort)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 9;
try {
l = 0;
failed = false;
checked {
b = (ushort)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 10;
try {
l = System.UInt16.MaxValue + 1;
failed = true;
checked {
b = (ushort)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 11;
try {
l = -1;
failed = true;
checked {
b = (ushort)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 12;
try {
ul = 0xfffff;
failed = true;
checked {
b = (ushort)ul;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 13;
return 0;
}
public static int test_0_short_cast () {
int a;
long l;
short b;
bool failed;
try {
a = System.UInt16.MaxValue;
failed = true;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 1;
try {
a = 0;
failed = false;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
try {
a = System.Int16.MaxValue + 1;
failed = true;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 3;
try {
a = System.Int16.MinValue - 1;
failed = true;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
try {
a = -1;
failed = false;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 5;
try {
a = System.Int16.MinValue;
failed = false;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 6;
try {
a = System.Int16.MaxValue;
failed = false;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 7;
try {
a = System.Int16.MaxValue + 1;
failed = true;
checked {
b = (short)a;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 8;
try {
double d = System.Int16.MaxValue;
failed = false;
checked {
b = (short)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 9;
try {
double d = System.Int16.MinValue;
failed = false;
checked {
b = (short)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 10;
try {
double d = System.Int16.MaxValue + 1.0;
failed = true;
checked {
b = (short)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 11;
try {
double d = System.Int16.MinValue - 1.0;
failed = true;
checked {
b = (short)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 12;
try {
l = System.Int16.MaxValue + 1;
failed = true;
checked {
b = (short)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 13;
try {
l = System.Int16.MaxValue;
failed = false;
checked {
b = (short)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 14;
try {
l = System.Int16.MinValue - 1;
failed = true;
checked {
b = (short)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 15;
try {
l = System.Int16.MinValue;
failed = false;
checked {
b = (short)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 16;
try {
l = 0x00000000ffffffff;
failed = true;
checked {
b = (short)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 17;
try {
ulong ul = 32768;
failed = true;
checked {
b = (short)ul;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 18;
return 0;
}
public static int test_0_int_cast () {
int a;
long l;
bool failed;
try {
double d = System.Int32.MaxValue + 1.0;
failed = true;
checked {
a = (int)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 1;
try {
double d = System.Int32.MaxValue;
failed = false;
checked {
a = (int)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
try {
double d = System.Int32.MinValue;
failed = false;
checked {
a = (int)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 3;
try {
double d = System.Int32.MinValue - 1.0;
failed = true;
checked {
a = (int)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
try {
l = System.Int32.MaxValue + (long)1;
failed = true;
checked {
a = (int)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 5;
try {
l = System.Int32.MaxValue;
failed = false;
checked {
a = (int)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 6;
try {
l = System.Int32.MinValue;
failed = false;
checked {
a = (int)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 7;
try {
l = System.Int32.MinValue - (long)1;
failed = true;
checked {
a = (int)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 8;
try {
uint ui = System.UInt32.MaxValue;
failed = true;
checked {
a = (int)ui;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 9;
try {
ulong ul = (long)(System.Int32.MaxValue) + 1;
failed = true;
checked {
a = (int)ul;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 10;
try {
ulong ul = UInt64.MaxValue;
failed = true;
checked {
a = (int)ul;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 11;
{
int i;
float f = 1.1f;
checked {
i = (int) f;
}
}
return 0;
}
public static int test_0_uint_cast () {
uint a;
long l;
bool failed;
try {
double d = System.UInt32.MaxValue;
failed = false;
checked {
a = (uint)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 1;
try {
double d = System.UInt32.MaxValue + 1.0;
failed = true;
checked {
a = (uint)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 2;
try {
double d = System.UInt32.MinValue;
failed = false;
checked {
a = (uint)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 3;
try {
double d = System.UInt32.MinValue - 1.0;
failed = true;
checked {
a = (uint)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
try {
l = System.UInt32.MaxValue;
failed = false;
checked {
a = (uint)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 5;
try {
l = System.UInt32.MaxValue + (long)1;
failed = true;
checked {
a = (uint)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 6;
try {
l = System.UInt32.MinValue;
failed = false;
checked {
a = (uint)l;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 7;
try {
l = System.UInt32.MinValue - (long)1;
failed = true;
checked {
a = (uint)l;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 8;
try {
int i = -1;
failed = true;
checked {
a = (uint)i;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 9;
{
uint i;
float f = 1.1f;
checked {
i = (uint) f;
}
}
return 0;
}
public static int test_0_long_cast () {
/*
* These tests depend on properties of x86 fp arithmetic so they won't work
* on other platforms.
*/
/*
long a;
bool failed;
try {
double d = System.Int64.MaxValue - 512.0;
failed = true;
checked {
a = (long)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 1;
try {
double d = System.Int64.MaxValue - 513.0;
failed = false;
checked {
a = (long)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
try {
double d = System.Int64.MinValue - 1024.0;
failed = false;
checked {
a = (long)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 3;
try {
double d = System.Int64.MinValue - 1025.0;
failed = true;
checked {
a = (long)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
*/
{
long i;
float f = 1.1f;
checked {
i = (long) f;
}
}
return 0;
}
public static int test_0_ulong_cast () {
ulong a;
bool failed;
/*
* These tests depend on properties of x86 fp arithmetic so they won't work
* on other platforms.
*/
/*
try {
double d = System.UInt64.MaxValue - 1024.0;
failed = true;
checked {
a = (ulong)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 1;
try {
double d = System.UInt64.MaxValue - 1025.0;
failed = false;
checked {
a = (ulong)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 2;
*/
try {
double d = 0;
failed = false;
checked {
a = (ulong)d;
}
} catch (OverflowException) {
failed = true;
}
if (failed)
return 3;
try {
double d = -1;
failed = true;
checked {
a = (ulong)d;
}
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
{
ulong i;
float f = 1.1f;
checked {
i = (ulong) f;
}
}
try {
int i = -1;
failed = true;
checked {
a = (ulong)i;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 5;
try {
int i = Int32.MinValue;
failed = true;
checked {
a = (ulong)i;
}
}
catch (OverflowException) {
failed = false;
}
if (failed)
return 6;
return 0;
}
public static int test_0_simple_double_casts () {
double d = 0xffffffff;
if ((uint)d != 4294967295)
return 1;
/*
* These tests depend on properties of x86 fp arithmetic so they won't work
* on other platforms.
*/
/*
d = 0xffffffffffffffff;
if ((ulong)d != 0)
return 2;
if ((ushort)d != 0)
return 3;
if ((byte)d != 0)
return 4;
*/
d = 0xffff;
if ((ushort)d != 0xffff)
return 5;
if ((byte)d != 0xff)
return 6;
return 0;
}
[Category ("NaClDisable")]
public static int test_0_div_zero () {
int d = 1;
int q = 0;
int val;
bool failed;
try {
failed = true;
val = d / q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 1;
try {
failed = true;
val = d % q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 2;
try {
failed = true;
q = -1;
d = Int32.MinValue;
val = d / q;
} catch (DivideByZeroException) {
/* wrong exception */
} catch (OverflowException) {
failed = false;
}
if (failed)
return 3;
try {
failed = true;
q = -1;
d = Int32.MinValue;
val = d % q;
} catch (DivideByZeroException) {
/* wrong exception */
} catch (OverflowException) {
failed = false;
}
if (failed)
return 4;
return 0;
}
public static int return_55 () {
return 55;
}
public static int test_0_cfold_div_zero () {
// Test that constant folding doesn't cause division by zero exceptions
if (return_55 () != return_55 ()) {
int d = 1;
int q = 0;
int val;
val = d / q;
val = d % q;
q = -1;
d = Int32.MinValue;
val = d / q;
q = -1;
val = d % q;
}
return 0;
}
public static int test_0_udiv_zero () {
uint d = 1;
uint q = 0;
uint val;
bool failed;
try {
failed = true;
val = d / q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 1;
try {
failed = true;
val = d % q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 2;
return 0;
}
[Category ("NaClDisable")]
public static int test_0_long_div_zero () {
long d = 1;
long q = 0;
long val;
bool failed;
try {
failed = true;
val = d / q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 1;
try {
failed = true;
val = d % q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 2;
try {
failed = true;
q = -1;
d = Int64.MinValue;
val = d / q;
} catch (DivideByZeroException) {
/* wrong exception */
} catch (ArithmeticException) {
failed = false;
}
if (failed)
return 3;
try {
failed = true;
q = -1;
d = Int64.MinValue;
val = d % q;
} catch (DivideByZeroException) {
/* wrong exception */
} catch (ArithmeticException) {
failed = false;
}
if (failed)
return 4;
return 0;
}
public static int test_0_ulong_div_zero () {
ulong d = 1;
ulong q = 0;
ulong val;
bool failed;
try {
failed = true;
val = d / q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 1;
try {
failed = true;
val = d % q;
} catch (DivideByZeroException) {
failed = false;
}
if (failed)
return 2;
return 0;
}
public static int test_0_float_div_zero () {
double d = 1;
double q = 0;
double val;
bool failed;
try {
failed = false;
val = d / q;
} catch (DivideByZeroException) {
failed = true;
}
if (failed)
return 1;
try {
failed = false;
val = d % q;
} catch (DivideByZeroException) {
failed = true;
}
if (failed)
return 2;
return 0;
}
public static int test_0_invalid_unbox () {
int i = 123;
object o = "Some string";
int res = 1;
try {
// Illegal conversion; o contains a string not an int
i = (int) o;
} catch (Exception e) {
if (i ==123)
res = 0;
}
return res;
}
// Test that double[] can't be cast to double (bug #46027)
public static int test_0_invalid_unbox_arrays () {
double[] d1 = { 1.0 };
double[][] d2 = { d1 };
Array a = d2;
try {
foreach (double d in a) {
}
return 1;
}
catch (InvalidCastException e) {
return 0;
}
}
/* bug# 42190, at least mcs generates a leave for the return that
* jumps out of multiple exception clauses: we used to execute just
* one enclosing finally block.
*/
public static int finally_level;
static void do_something () {
int a = 0;
try {
try {
return;
} finally {
a = 1;
}
} finally {
finally_level++;
}
}
public static int test_2_multiple_finally_clauses () {
finally_level = 0;
do_something ();
if (finally_level == 1)
return 2;
return 0;
}
public static int test_3_checked_cast_un () {
ulong i = 0x8000000034000000;
long j;
try {
checked { j = (long)i; }
} catch (OverflowException) {
j = 2;
}
if (j != 2)
return 0;
return 3;
}
public static int test_4_checked_cast () {
long i;
ulong j;
unchecked { i = (long)0x8000000034000000;};
try {
checked { j = (ulong)i; }
} catch (OverflowException) {
j = 3;
}
if (j != 3)
return 0;
return 4;
}
static readonly int[] mul_dim_results = new int[] {
0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8,
1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8,
2, 0, 2, 1, 2, 8,
3, 0, 3, 1, 3, 8,
4, 0, 4, 1, 4, 8,
5, 0, 5, 1, 5, 2, 5, 3, 5, 4, 5, 5, 5, 6, 5, 7, 5, 8,
6, 0, 6, 1, 6, 2, 6, 3, 6, 4, 6, 5, 6, 6, 6, 7, 6, 8,
7, 0, 7, 1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6, 7, 7, 7, 8,
};
public static int test_0_multi_dim_array_access () {
int [,] a = System.Array.CreateInstance (typeof (int),
new int [] {3,6}, new int [] {2,2 }) as int[,];
int x, y;
int result_idx = 0;
for (x = 0; x < 8; ++x) {
for (y = 0; y < 9; ++y) {
bool got_ex = false;
try {
a [x, y] = 1;
} catch {
got_ex = true;
}
if (got_ex) {
if (result_idx >= mul_dim_results.Length)
return -1;
if (mul_dim_results [result_idx] != x || mul_dim_results [result_idx + 1] != y) {
return result_idx + 1;
}
result_idx += 2;
}
}
}
if (result_idx == mul_dim_results.Length)
return 0;
return 200;
}
static void helper_out_obj (out object o) {
o = (object)"buddy";
}
static void helper_out_string (out string o) {
o = "buddy";
}
public static int test_2_array_mismatch () {
string[] a = { "hello", "world" };
object[] b = a;
bool passed = false;
try {
helper_out_obj (out b [1]);
} catch (ArrayTypeMismatchException) {
passed = true;
}
if (!passed)
return 0;
helper_out_string (out a [1]);
if (a [1] != "buddy")
return 1;
return 2;
}
public static int test_0_ovf1 () {
int exception = 0;
checked {
try {
ulong a = UInt64.MaxValue - 1;
ulong t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf2 () {
int exception = 0;
checked {
try {
ulong a = UInt64.MaxValue;
ulong t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf3 () {
int exception = 0;
long a = Int64.MaxValue - 1;
checked {
try {
long t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf4 () {
int exception = 0;
long a = Int64.MaxValue;
checked {
try {
long t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf5 () {
int exception = 0;
ulong a = UInt64.MaxValue - 1;
checked {
try {
ulong t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf6 () {
int exception = 0;
ulong a = UInt64.MaxValue;
checked {
try {
ulong t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf7 () {
int exception = 0;
long a = Int64.MinValue + 1;
checked {
try {
long t = a--;
} catch {
exception = 1;
}
}
return 0;
}
public static int test_1_ovf8 () {
int exception = 0;
long a = Int64.MinValue;
checked {
try {
long t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf9 () {
int exception = 0;
ulong a = UInt64.MinValue + 1;
checked {
try {
ulong t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf10 () {
int exception = 0;
ulong a = UInt64.MinValue;
checked {
try {
ulong t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf11 () {
int exception = 0;
int a = Int32.MinValue + 1;
checked {
try {
int t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf12 () {
int exception = 0;
int a = Int32.MinValue;
checked {
try {
int t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf13 () {
int exception = 0;
uint a = 1;
checked {
try {
uint t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf14 () {
int exception = 0;
uint a = 0;
checked {
try {
uint t = a--;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf15 () {
int exception = 0;
sbyte a = 126;
checked {
try {
sbyte t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf16 () {
int exception = 0;
sbyte a = 127;
checked {
try {
sbyte t = a++;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf17 () {
int exception = 0;
checked {
try {
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf18 () {
int exception = 0;
int a = 1 << 29;
checked {
try {
int t = a*2;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf19 () {
int exception = 0;
int a = 1 << 30;
checked {
try {
int t = a*2;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_0_ovf20 () {
int exception = 0;
checked {
try {
ulong a = 0xffffffffff;
ulong t = a*0x0ffffff;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf21 () {
int exception = 0;
ulong a = 0xffffffffff;
checked {
try {
ulong t = a*0x0fffffff;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf22 () {
int exception = 0;
long a = Int64.MinValue;
long b = 10;
checked {
try {
long v = a * b;
} catch {
exception = 1;
}
}
return exception;
}
public static int test_1_ovf23 () {
int exception = 0;
long a = 10;
long b = Int64.MinValue;
checked {
try {
long v = a * b;
} catch {
exception = 1;
}
}
return exception;
}
class Broken {
public static int i;
static Broken () {
throw new Exception ("Ugh!");
}
public static int DoSomething () {
return i;
}
}
public static int test_0_exception_in_cctor () {
try {
Broken.DoSomething ();
}
catch (TypeInitializationException) {
// This will only happen once even if --regression is used
}
return 0;
}
public static int test_5_regalloc () {
int i = 0;
try {
for (i = 0; i < 10; ++i) {
if (i == 5)
throw new Exception ();
}
}
catch (Exception) {
if (i != 5)
return i;
}
// Check that variables written in catch clauses are volatile
int j = 0;
try {
throw new Exception ();
}
catch (Exception) {
j = 5;
}
if (j != 5)
return 6;
int k = 0;
try {
try {
throw new Exception ();
}
finally {
k = 5;
}
}
catch (Exception) {
}
if (k != 5)
return 7;
return i;
}
public static void rethrow () {
try {
throw new ApplicationException();
} catch (ApplicationException) {
try {
throw new OverflowException();
} catch (Exception) {
throw;
}
}
}
// Test that a rethrow rethrows the correct exception
public static int test_0_rethrow_nested () {
try {
rethrow ();
} catch (OverflowException) {
return 0;
} catch (Exception) {
return 1;
}
return 2;
}
/* MarshalByRefObject prevents the methods from being inlined */
class ThrowClass : MarshalByRefObject {
public static void rethrow1 () {
throw new Exception ();
}
public static void rethrow2 () {
rethrow1 ();
/* This disables tailcall opts */
Console.WriteLine ();
}
}
public static int test_0_rethrow_stacktrace () {
// Check that rethrowing an exception preserves the original stack trace
try {
try {
ThrowClass.rethrow2 ();
}
catch (Exception ex) {
// Check that each catch clause has its own exception variable
// If not, the throw below will overwrite the exception used
// by the rethrow
try {
throw new DivideByZeroException ();
}
catch (Exception foo) {
}
throw;
}
}
catch (Exception ex) {
if (ex.StackTrace.IndexOf ("rethrow2") != -1)
return 0;
}
return 1;
}
interface IFace {}
class Face : IFace {}
public static int test_1_array_mismatch_2 () {
try {
object [] o = new Face [1];
o [0] = 1;
return 0;
} catch (ArrayTypeMismatchException) {
return 1;
}
}
public static int test_1_array_mismatch_3 () {
try {
object [] o = new IFace [1];
o [0] = 1;
return 0;
} catch (ArrayTypeMismatchException) {
return 1;
}
}
public static int test_1_array_mismatch_4 () {
try {
object [][] o = new Face [5] [];
o [0] = new object [5];
return 0;
} catch (ArrayTypeMismatchException) {
return 1;
}
}
public static int test_0_array_size () {
bool failed;
try {
failed = true;
int[] mem1 = new int [Int32.MaxValue];
}
catch (OutOfMemoryException e) {
failed = false;
}
if (failed)
return 1;
try {
failed = true;
int[,] mem2 = new int [Int32.MaxValue, Int32.MaxValue];
}
catch (OutOfMemoryException e) {
failed = false;
}
if (failed)
return 2;
return 0;
}
struct S {
int i, j, k, l, m, n;
}
static IntPtr[] addr;
static unsafe void throw_func (int i, S s) {
addr [i] = new IntPtr (&i);
throw new Exception ();
}
/* Test that arguments are correctly popped off the stack during unwinding */
/* FIXME: Fails on x86 when llvm is enabled (#5432) */
/*
public static int test_0_stack_unwind () {
addr = new IntPtr [1000];
S s = new S ();
for (int j = 0; j < 1000; j++) {
try {
throw_func (j, s);
}
catch (Exception) {
}
}
return (addr [0].ToInt64 () - addr [100].ToInt64 () < 100) ? 0 : 1;
}
*/
static unsafe void get_sp (int i) {
addr [i] = new IntPtr (&i);
}
/* Test that the arguments to the throw trampoline are correctly popped off the stack */
public static int test_0_throw_unwind () {
addr = new IntPtr [1000];
S s = new S ();
for (int j = 0; j < 1000; j++) {
try {
get_sp (j);
throw new Exception ();
}
catch (Exception) {
}
}
return (addr [0].ToInt64 () - addr [100].ToInt64 () < 100) ? 0 : 1;
}
public static int test_0_regress_73242 () {
int [] arr = new int [10];
for (int i = 0; i < 10; ++i)
arr [i] = 0;
try {
throw new Exception ();
}
catch {
}
return 0;
}
public static int test_0_nullref () {
try {
Array foo = null;
foo.Clone();
} catch (NullReferenceException e) {
return 0;
}
return 1;
}
public int amethod () {
return 1;
}
public static int test_0_nonvirt_nullref_at_clause_start () {
Tests t = null;
try {
t.amethod ();
} catch (NullReferenceException) {
return 0;
}
return 1;
}
public static int throw_only () {
throw new Exception ();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int throw_only2 () {
return throw_only ();
}
public static int test_0_inline_throw_only () {
try {
return throw_only2 ();
}
catch (Exception ex) {
return 0;
}
}
public static string GetText (string s) {
return s;
}
public static int throw_only_gettext () {
throw new Exception (GetText ("FOO"));
}
public static int test_0_inline_throw_only_gettext () {
object o = null;
try {
o = throw_only_gettext ();
}
catch (Exception ex) {
return 0;
}
return o != null ? 0 : 1;
}
// bug #78633
public static int test_0_throw_to_branch_opt_outer_clause () {
int i = 0;
try {
try {
string [] files = new string[1];
string s = files[2];
} finally {
i ++;
}
} catch {
}
return (i == 1) ? 0 : 1;
}
// bug #485721
public static int test_0_try_inside_finally_cmov_opt () {
bool Reconect = false;
object o = new object ();
try {
}
catch (Exception ExCon) {
if (o != null)
Reconect = true;
try {
}
catch (Exception Last) {
}
}
finally {
if (Reconect == true) {
try {
}
catch (Exception ex) {
}
}
}
return 0;
}
public static int test_0_inline_throw () {
try {
inline_throw1 (5);
return 1;
} catch {
return 0;
}
}
// for llvm, the end bblock is unreachable
public static int inline_throw1 (int i) {
if (i == 0)
throw new Exception ();
else
return inline_throw2 (i);
}
public static int inline_throw2 (int i) {
throw new Exception ();
}
// bug #539550
public static int test_0_lmf_filter () {
try {
// The invoke calls a runtime-invoke wrapper which has a filter clause
typeof (Tests).GetMethod ("lmf_filter").Invoke (null, new object [] { });
} catch (TargetInvocationException) {
}
return 0;
}
public static void lmf_filter () {
try {
Connect ();
}
catch {
throw new NotImplementedException ();
}
}
public static void Connect () {
Stop ();
throw new Exception();
}
public static void Stop () {
try {
lock (null) {}
}
catch {
}
}
private static void do_raise () {
throw new System.Exception ();
}
private static int int_func (int i) {
return i;
}
// #559876
public static int test_8_local_deadce_causes () {
int myb = 4;
try {
myb = int_func (8);
do_raise();
myb = int_func (2);
} catch (System.Exception) {
return myb;
}
return 0;
}
public static int test_0_except_opt_two_clauses () {
int size;
size = -1;
uint ui = (uint)size;
try {
checked {
uint v = ui * (uint)4;
}
} catch (OverflowException e) {
return 0;
} catch (Exception) {
return 1;
}
return 2;
}
class Child
{
public virtual long Method()
{
throw new Exception();
}
}
/* #612206 */
public static int test_100_long_vars_in_clauses_initlocals_opt () {
Child c = new Child();
long value = 100;
try {
value = c.Method();
}
catch {}
return (int)value;
}
class A {
public object AnObj;
}
public static void DoSomething (ref object o) {
}
public static int test_0_ldflda_null () {
A a = null;
try {
DoSomething (ref a.AnObj);
} catch (NullReferenceException) {
return 0;
}
return 1;
}
unsafe struct Foo
{
public int i;
public static Foo* pFoo;
}
/* MS.NET doesn't seem to throw in this case */
public unsafe static int test_0_ldflda_null_pointer () {
int* pi = &Foo.pFoo->i;
return 0;
}
static int test_0_try_clause_in_finally_clause_regalloc () {
// Fill up registers with values
object a = new object ();
object[] arr1 = new object [1];
object[] arr2 = new object [1];
object[] arr3 = new object [1];
object[] arr4 = new object [1];
object[] arr5 = new object [1];
for (int i = 0; i < 10; ++i)
arr1 [0] = a;
for (int i = 0; i < 10; ++i)
arr2 [0] = a;
for (int i = 0; i < 10; ++i)
arr3 [0] = a;
for (int i = 0; i < 10; ++i)
arr4 [0] = a;
for (int i = 0; i < 10; ++i)
arr5 [0] = a;
int res = 1;
try {
try_clause_in_finally_clause_regalloc_inner (out res);
} catch (Exception) {
}
return res;
}
public static object Throw () {
for (int i = 0; i < 10; ++i)
;
throw new Exception ();
}
static void try_clause_in_finally_clause_regalloc_inner (out int res) {
object o = null;
res = 1;
try {
o = Throw ();
} catch (Exception) {
/* Make sure this doesn't branch to the finally */
throw new DivideByZeroException ();
} finally {
try {
/* Make sure o is register allocated */
if (o == null)
res = 0;
else
res = 1;
if (o == null)
res = 0;
else
res = 1;
if (o == null)
res = 0;
else
res = 1;
} catch (DivideByZeroException) {
}
}
}
public static bool t_1835_inner () {
bool a = true;
if (a) throw new Exception();
return true;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool t_1835_inner_2 () {
bool b = t_1835_inner ();
return b;
}
public static int test_0_inline_retval_throw_in_branch_1835 () {
try {
t_1835_inner_2 ();
} catch {
return 0;
}
return 1;
}
}
| 15.267642 | 89 | 0.546735 | [
"Apache-2.0"
] | adob/mono | mono/mini/exceptions.cs | 41,757 | C# |
namespace HomeBook.Data.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using HomeBook.Common;
using HomeBook.Data.Common.Models;
public class Entrance : BaseDeletableModel<int>
{
[MaxLength(GlobalConstants.DataValidations.EntranceAddressMaxLength)]
public string EntranceAddressSign { get; set; }
public int BuildingId { get; set; }
public virtual Building Building { get; set; }
public virtual ICollection<Apartment> Apartments { get; set; }
}
}
| 26.761905 | 77 | 0.699288 | [
"MIT"
] | TodorGrigorov89/HomeBook | Data/HomeBook.Data.Models/Entrance.cs | 564 | C# |
namespace TraktNet.Objects.Post.Responses
{
using Get.Shows;
/// <summary>A Trakt show, which was not found.</summary>
public interface ITraktPostResponseNotFoundShow
{
/// <summary>Gets or sets the ids of the not found show. See also <seealso cref="ITraktShowIds" />.</summary>
ITraktShowIds Ids { get; set; }
}
}
| 29.416667 | 117 | 0.665722 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Objects/Post/Responses/ITraktPostResponseNotFoundShow.cs | 355 | C# |
// Copyright (c) Mark Nichols. All Rights Reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using Bicep.Core.Diagnostics;
using Bicep.Core.Extensions;
using Bicep.Core.Syntax;
namespace Bicep.Core.Parsing
{
public class Lexer
{
// maps the escape character (that follows the backslash) to its value
private static readonly ImmutableSortedDictionary<char, char> SingleCharacterEscapes = new Dictionary<char, char>
{
{'n', '\n'},
{'r', '\r'},
{'t', '\t'},
{'\\', '\\'},
{'\'', '\''},
{'$', '$'}
}.ToImmutableSortedDictionary();
private static readonly ImmutableArray<string> CharacterEscapeSequences = SingleCharacterEscapes.Keys
.Select(c => $"\\{c}")
.Append("\\u{...}")
.ToImmutableArray();
private const int MultilineStringTerminatingQuoteCount = 3;
// the rules for parsing are slightly different if we are inside an interpolated string (for example, a new line should result in a lex error).
// to handle this, we use a modal lexing pattern with a stack to ensure we're applying the correct set of rules.
private readonly Stack<TokenType> templateStack = new Stack<TokenType>();
private readonly IList<Token> tokens = new List<Token>();
private readonly IDiagnosticWriter diagnosticWriter;
private readonly SlidingTextWindow textWindow;
public Lexer(SlidingTextWindow textWindow, IDiagnosticWriter diagnosticWriter)
{
this.textWindow = textWindow;
this.diagnosticWriter = diagnosticWriter;
}
private void AddDiagnostic(TextSpan span, DiagnosticBuilder.ErrorBuilderDelegate diagnosticFunc)
{
var diagnostic = diagnosticFunc(DiagnosticBuilder.ForPosition(span));
this.diagnosticWriter.Write(diagnostic);
}
private void AddDiagnostic(DiagnosticBuilder.ErrorBuilderDelegate diagnosticFunc)
=> AddDiagnostic(textWindow.GetSpan(), diagnosticFunc);
public void Lex()
{
while (!textWindow.IsAtEnd())
{
LexToken();
}
// make sure we always include an end-of-line
if (!tokens.Any() || tokens.Last().Type != TokenType.EndOfFile)
{
LexToken();
}
}
public ImmutableArray<Token> GetTokens() => tokens.ToImmutableArray();
/// <summary>
/// Converts a set of string literal tokens into their raw values. Returns null if any of the tokens are of the wrong type or malformed.
/// </summary>
/// <param name="stringTokens">the string tokens</param>
public static IEnumerable<string>? TryGetRawStringSegments(IReadOnlyList<Token> stringTokens)
{
var segments = new string[stringTokens.Count];
for (var i = 0; i < stringTokens.Count; i++)
{
var nextSegment = Lexer.TryGetStringValue(stringTokens[i]);
if (nextSegment == null)
{
return null;
}
segments[i] = nextSegment;
}
return segments;
}
public static string? TryGetMultilineStringValue(Token stringToken)
{
var tokenText = stringToken.Text;
if (tokenText.Length < MultilineStringTerminatingQuoteCount * 2)
{
return null;
}
for (var i = 0; i < MultilineStringTerminatingQuoteCount; i++)
{
if (tokenText[i] != '\'')
{
return null;
}
}
for (var i = tokenText.Length - MultilineStringTerminatingQuoteCount; i < tokenText.Length; i++)
{
if (tokenText[i] != '\'')
{
return null;
}
}
var startOffset = MultilineStringTerminatingQuoteCount;
// we strip a leading \r\n or \n
if (tokenText[startOffset] == '\r')
{
startOffset++;
}
if (tokenText[startOffset] == '\n')
{
startOffset++;
}
return tokenText.Substring(startOffset, tokenText.Length - startOffset - MultilineStringTerminatingQuoteCount);
}
/// <summary>
/// Converts string literal text into its value. Returns null if the specified string token is malformed due to lexer error recovery.
/// </summary>
/// <param name="stringToken">the string token</param>
public static string? TryGetStringValue(Token stringToken)
{
var (start, end) = stringToken.Type switch
{
TokenType.StringComplete => (LanguageConstants.StringDelimiter, LanguageConstants.StringDelimiter),
TokenType.StringLeftPiece => (LanguageConstants.StringDelimiter, LanguageConstants.StringHoleOpen),
TokenType.StringMiddlePiece => (LanguageConstants.StringHoleClose, LanguageConstants.StringHoleOpen),
TokenType.StringRightPiece => (LanguageConstants.StringHoleClose, LanguageConstants.StringDelimiter),
_ => (null, null),
};
if (start == null || end == null)
{
return null;
}
if (stringToken.Text.Length < start.Length + end.Length ||
stringToken.Text.Substring(0, start.Length) != start ||
stringToken.Text.Substring(stringToken.Text.Length - end.Length) != end)
{
// any lexer-generated token should not hit this problem as the start & end are already verified
return null;
}
var contents = stringToken.Text.Substring(start.Length, stringToken.Text.Length - start.Length - end.Length);
var window = new SlidingTextWindow(contents);
// the value of the string will be shorter because escapes are longer than the characters they represent
var buffer = new StringBuilder(contents.Length);
while (!window.IsAtEnd())
{
var nextChar = window.Next();
if (nextChar == '\'')
{
return null;
}
if (nextChar == '\\')
{
// escape sequence begins
if (window.IsAtEnd())
{
return null;
}
char escapeChar = window.Next();
if (escapeChar == 'u')
{
// unicode escape
char openCurly = window.Next();
if (openCurly != '{')
{
return null;
}
var codePointText = ScanHexNumber(window);
if (!TryParseCodePoint(codePointText, out uint codePoint))
{
// invalid codepoint
return null;
}
char closeCurly = window.Next();
if (closeCurly != '}')
{
return null;
}
char charOrHighSurrogate = CodepointToString(codePoint, out char lowSurrogate);
buffer.Append(charOrHighSurrogate);
if (lowSurrogate != SlidingTextWindow.InvalidCharacter)
{
// previous char was a high surrogate
// also append the low surrogate
buffer.Append(lowSurrogate);
}
continue;
}
if (SingleCharacterEscapes.TryGetValue(escapeChar, out char escapeCharValue) == false)
{
// invalid escape character
return null;
}
buffer.Append(escapeCharValue);
// continue to next iteration
continue;
}
// regular string char - append to buffer
buffer.Append(nextChar);
}
return buffer.ToString();
}
private static bool TryParseCodePoint(string text, out uint codePoint) => uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint) && codePoint <= 0x10FFFF;
/// <summary>
/// Determines if the specified string is a valid identifier. To be considered a valid identifier, the string must start
/// with the identifier start character and remaining characters must be identifier continuation characters.
/// </summary>
/// <param name="value">The value</param>
public static bool IsValidIdentifier(string value)
{
if (value.Length <= 0)
{
return false;
}
var result = IsIdentifierStart(value[0]);
var index = 1;
while (result && index < value.Length)
{
result = result && IsIdentifierContinuation(value[index]);
index++;
}
return result;
}
private static char CodepointToString(uint codePoint, out char lowSurrogate)
{
if (codePoint < 0x00010000)
{
lowSurrogate = SlidingTextWindow.InvalidCharacter;
return (char)codePoint;
}
Debug.Assert(codePoint > 0x0000FFFF && codePoint <= 0x0010FFFF);
lowSurrogate = (char)((codePoint - 0x00010000) % 0x0400 + 0xDC00);
return (char)((codePoint - 0x00010000) / 0x0400 + 0xD800);
}
private IEnumerable<SyntaxTrivia> ScanTrailingTrivia()
{
if (IsWhiteSpace(textWindow.Peek()))
{
yield return ScanWhitespace();
}
if (textWindow.Peek() == '/' && textWindow.Peek(1) == '/')
{
yield return ScanSingleLineComment();
yield break;
}
if (textWindow.Peek() == '/' && textWindow.Peek(1) == '*')
{
yield return ScanMultiLineComment();
yield break;
}
}
private IEnumerable<SyntaxTrivia> ScanLeadingTrivia()
{
while (true)
{
if (IsWhiteSpace(textWindow.Peek()))
{
yield return ScanWhitespace();
}
else if (textWindow.Peek() == '/' && textWindow.Peek(1) == '/')
{
yield return ScanSingleLineComment();
}
else if (textWindow.Peek() == '/' && textWindow.Peek(1) == '*')
{
yield return ScanMultiLineComment();
yield break;
}
else if (textWindow.Peek() == '#' &&
CheckAdjacentText(LanguageConstants.DisableNextLineDiagnosticsKeyword) &&
string.IsNullOrWhiteSpace(textWindow.GetTextBetweenLineStartAndCurrentPosition()))
{
yield return ScanDisableNextLineDiagnosticsDirective();
}
else
{
yield break;
}
}
}
private SyntaxTrivia ScanDisableNextLineDiagnosticsDirective()
{
textWindow.Reset();
textWindow.Advance(LanguageConstants.DisableNextLineDiagnosticsKeyword.Length + 1); // Length of disable next statement plus #
var span = textWindow.GetSpan();
int start = span.Position;
int length = span.Length;
StringBuilder sb = new StringBuilder();
sb.Append(textWindow.GetText());
textWindow.Reset();
List<Token> codes = new();
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
if (IsIdentifierContinuation(nextChar) || nextChar == '-')
{
switch (textWindow.Peek(1))
{
case ' ':
case '\t':
case '\n':
case '\r':
case char.MaxValue:
textWindow.Advance();
if (GetToken() is { } token)
{
codes.Add(token);
length += token.Span.Length;
sb.Append(token.Text);
continue;
}
break;
default:
textWindow.Advance();
break;
}
}
else if (nextChar == ' ' || nextChar == '\t')
{
textWindow.Advance();
sb.Append(nextChar);
length++;
textWindow.Reset();
}
else
{
break;
}
}
if (codes.Count == 0)
{
AddDiagnostic(b => b.MissingDiagnosticCodes());
}
return GetDisableNextLineDiagnosticsSyntaxTrivia(codes, start, length, sb.ToString());
}
private bool CheckAdjacentText(string text)
{
for (int i = 0; i < text.Length; i++)
{
if (textWindow.Peek(i + 1) == text[i])
{
continue;
}
else
{
return false;
}
}
return true;
}
private DisableNextLineDiagnosticsSyntaxTrivia GetDisableNextLineDiagnosticsSyntaxTrivia(List<Token> codes, int start, int length, string text)
{
if (codes.Any())
{
var lastCodeSpan = codes.Last().Span;
var lastCodeSpanEnd = lastCodeSpan.GetEndPosition();
// There could be whitespace following #disable-next-line directive, in which case we need to adjust the span and text.
// E.g. #disable-next-line BCP226 // test
if (length > lastCodeSpanEnd)
{
textWindow.Rewind(length - lastCodeSpanEnd);
return new DisableNextLineDiagnosticsSyntaxTrivia(SyntaxTriviaType.DisableNextLineDiagnosticsDirective, new TextSpan(start, lastCodeSpanEnd), text.Substring(0, lastCodeSpanEnd), codes);
}
}
return new DisableNextLineDiagnosticsSyntaxTrivia(SyntaxTriviaType.DisableNextLineDiagnosticsDirective, new TextSpan(start, length), text, codes);
}
private Token? GetToken()
{
var text = textWindow.GetText();
if (!string.IsNullOrWhiteSpace(text))
{
return new Token(TokenType.StringComplete, textWindow.GetSpan(), textWindow.GetText(), Enumerable.Empty<SyntaxTrivia>(), Enumerable.Empty<SyntaxTrivia>());
}
return null;
}
private void LexToken()
{
textWindow.Reset();
// important to force enum evaluation here via .ToImmutableArray()!
var leadingTrivia = ScanLeadingTrivia().ToImmutableArray();
textWindow.Reset();
var tokenType = ScanToken();
var tokenText = textWindow.GetText();
var tokenSpan = textWindow.GetSpan();
if (tokenType == TokenType.Unrecognized)
{
if (tokenText == "\"")
{
AddDiagnostic(b => b.DoubleQuoteToken(tokenText));
}
else
{
AddDiagnostic(b => b.UnrecognizedToken(tokenText));
}
}
textWindow.Reset();
// important to force enum evaluation here via .ToImmutableArray()!
var trailingTrivia = ScanTrailingTrivia().ToImmutableArray();
var token = new Token(tokenType, tokenSpan, tokenText, leadingTrivia, trailingTrivia);
this.tokens.Add(token);
}
private SyntaxTrivia ScanWhitespace()
{
textWindow.Reset();
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
switch (nextChar)
{
case ' ':
case '\t':
textWindow.Advance();
continue;
}
break;
}
return new SyntaxTrivia(SyntaxTriviaType.Whitespace, textWindow.GetSpan(), textWindow.GetText());
}
private SyntaxTrivia ScanSingleLineComment()
{
textWindow.Reset();
textWindow.Advance(2);
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
// make sure we don't include the newline in the comment trivia
if (IsNewLine(nextChar))
{
break;
}
textWindow.Advance();
}
return new SyntaxTrivia(SyntaxTriviaType.SingleLineComment, textWindow.GetSpan(), textWindow.GetText());
}
private SyntaxTrivia ScanMultiLineComment()
{
textWindow.Reset();
textWindow.Advance(2);
while (true)
{
if (textWindow.IsAtEnd())
{
AddDiagnostic(b => b.UnterminatedMultilineComment());
break;
}
var nextChar = textWindow.Peek();
textWindow.Advance();
if (nextChar != '*')
{
continue;
}
if (textWindow.IsAtEnd())
{
AddDiagnostic(b => b.UnterminatedMultilineComment());
break;
}
nextChar = textWindow.Peek();
textWindow.Advance();
if (nextChar == '/')
{
break;
}
}
return new SyntaxTrivia(SyntaxTriviaType.MultiLineComment, textWindow.GetSpan(), textWindow.GetText());
}
private void ScanNewLine()
{
while (true)
{
if (textWindow.IsAtEnd())
{
return;
}
var nextChar = textWindow.Peek();
if (IsNewLine(nextChar) == false)
{
return;
}
textWindow.Advance();
}
}
private TokenType ScanMultilineString()
{
var successiveQuotes = 0;
// we've already scanned the "'''", so get straight to scanning the string contents.
while (!textWindow.IsAtEnd())
{
var nextChar = textWindow.Peek();
textWindow.Advance();
switch (nextChar)
{
case '\'':
successiveQuotes++;
if (successiveQuotes == MultilineStringTerminatingQuoteCount)
{
// we've scanned the terminating "'''". Keep scanning as long as we find more "'" characters;
// it is possible for the verbatim string's last character to be "'", and we should accept this.
while (textWindow.Peek() == '\'')
{
textWindow.Advance();
}
return TokenType.MultilineString;
}
break;
default:
successiveQuotes = 0;
break;
}
}
// We've reached the end of the file without finding terminating quotes.
// We still want to return a string token so that highlighting shows up.
AddDiagnostic(b => b.UnterminatedMultilineString());
return TokenType.MultilineString;
}
private TokenType ScanStringSegment(bool isAtStartOfString)
{
// to handle interpolation, strings are broken down into multiple segments, to detect the portions of string between the 'holes'.
// 'complete' string: a string with no holes (no interpolation), e.g. "'hello'"
// string 'left piece': the portion of an interpolated string up to the first hole, e.g. "'hello$"
// string 'middle piece': the portion of an interpolated string between two holes, e.g. "}hello${"
// string 'right piece': the portion of an interpolated string after the last hole, e.g. "}hello'"
while (true)
{
if (textWindow.IsAtEnd())
{
AddDiagnostic(b => b.UnterminatedString());
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
var nextChar = textWindow.Peek();
if (IsNewLine(nextChar))
{
// do not consume the new line character
AddDiagnostic(b => b.UnterminatedStringWithNewLine());
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
int escapeBeginPosition = textWindow.GetAbsolutePosition();
textWindow.Advance();
if (nextChar == '\'')
{
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
if (nextChar == '$' && !textWindow.IsAtEnd() && textWindow.Peek() == '{')
{
textWindow.Advance();
return isAtStartOfString ? TokenType.StringLeftPiece : TokenType.StringMiddlePiece;
}
if (nextChar != '\\')
{
continue;
}
// an escape sequence was started with \
if (textWindow.IsAtEnd())
{
// the escape was unterminated
AddDiagnostic(b => b.UnterminatedStringEscapeSequenceAtEof());
return isAtStartOfString ? TokenType.StringComplete : TokenType.StringRightPiece;
}
// the escape sequence has a char after the \
// consume it
nextChar = textWindow.Peek();
textWindow.Advance();
if (nextChar == 'u')
{
// unicode escape
if (textWindow.IsAtEnd())
{
// string was prematurely terminated
// reusing the first check in the loop body to produce the diagnostic
continue;
}
nextChar = textWindow.Peek();
if (nextChar != '{')
{
// \u must be followed by {, but it's not
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
textWindow.Advance();
if (textWindow.IsAtEnd())
{
// string was prematurely terminated
// reusing the first check in the loop body to produce the diagnostic
continue;
}
string codePointText = ScanHexNumber(textWindow);
if (textWindow.IsAtEnd())
{
// string was prematurely terminated
// reusing the first check in the loop body to produce the diagnostic
continue;
}
if (string.IsNullOrEmpty(codePointText))
{
// we didn't get any hex digits
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
nextChar = textWindow.Peek();
if (nextChar != '}')
{
// hex digits must be followed by }, but it's not
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
textWindow.Advance();
if (!TryParseCodePoint(codePointText, out _))
{
// code point is not actually valid
AddDiagnostic(textWindow.GetSpanFromPosition(escapeBeginPosition), b => b.InvalidUnicodeEscape());
continue;
}
}
else
{
// not a unicode escape
if (SingleCharacterEscapes.ContainsKey(nextChar) == false)
{
// the span of the error is the incorrect escape sequence
AddDiagnostic(textWindow.GetLookbehindSpan(2), b => b.UnterminatedStringEscapeSequenceUnrecognized(CharacterEscapeSequences));
}
}
}
}
private static string ScanHexNumber(SlidingTextWindow window)
{
var buffer = new StringBuilder();
while (true)
{
if (window.IsAtEnd())
{
return buffer.ToString();
}
char current = window.Peek();
if (!IsHexDigit(current))
{
return buffer.ToString();
}
buffer.Append(current);
window.Advance();
}
}
private void ScanNumber()
{
while (true)
{
if (textWindow.IsAtEnd())
{
return;
}
if (!IsDigit(textWindow.Peek()))
{
return;
}
textWindow.Advance();
}
}
private TokenType GetIdentifierTokenType()
{
var identifier = textWindow.GetText();
if (LanguageConstants.Keywords.TryGetValue(identifier, out var tokenType))
{
return tokenType;
}
return TokenType.Identifier;
}
private TokenType ScanIdentifier()
{
while (true)
{
if (textWindow.IsAtEnd())
{
return GetIdentifierTokenType();
}
if (!IsIdentifierContinuation(textWindow.Peek()))
{
return GetIdentifierTokenType();
}
textWindow.Advance();
}
}
private TokenType ScanToken()
{
if (textWindow.IsAtEnd())
{
return TokenType.EndOfFile;
}
var nextChar = textWindow.Peek();
textWindow.Advance();
switch (nextChar)
{
case '{':
if (templateStack.Any())
{
// if we're inside a string interpolation hole, and we find an object open brace,
// push it to the stack, so that we can match it up against an object close brace.
// this allows us to determine whether we're terminating an object or closing an interpolation hole.
templateStack.Push(TokenType.LeftBrace);
}
return TokenType.LeftBrace;
case '}':
if (templateStack.Any())
{
var prevTemplateToken = templateStack.Peek();
if (prevTemplateToken != TokenType.LeftBrace)
{
var stringToken = ScanStringSegment(false);
if (stringToken == TokenType.StringRightPiece)
{
templateStack.Pop();
}
return stringToken;
}
}
return TokenType.RightBrace;
case '(':
return TokenType.LeftParen;
case ')':
return TokenType.RightParen;
case '[':
return TokenType.LeftSquare;
case ']':
return TokenType.RightSquare;
case '@':
return TokenType.At;
case ',':
return TokenType.Comma;
case '.':
return TokenType.Dot;
case '?':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '?':
textWindow.Advance();
return TokenType.DoubleQuestion;
}
}
return TokenType.Question;
case ':':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case ':':
textWindow.Advance();
return TokenType.DoubleColon;
}
}
return TokenType.Colon;
case ';':
return TokenType.Semicolon;
case '+':
return TokenType.Plus;
case '-':
return TokenType.Minus;
case '%':
return TokenType.Modulo;
case '*':
return TokenType.Asterisk;
case '/':
return TokenType.Slash;
case '!':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.NotEquals;
case '~':
textWindow.Advance();
return TokenType.NotEqualsInsensitive;
}
}
return TokenType.Exclamation;
case '<':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.LessThanOrEqual;
}
}
return TokenType.LessThan;
case '>':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.GreaterThanOrEqual;
}
}
return TokenType.GreaterThan;
case '=':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '=':
textWindow.Advance();
return TokenType.Equals;
case '~':
textWindow.Advance();
return TokenType.EqualsInsensitive;
}
}
return TokenType.Assignment;
case '&':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '&':
textWindow.Advance();
return TokenType.LogicalAnd;
}
}
return TokenType.Unrecognized;
case '|':
if (!textWindow.IsAtEnd())
{
switch (textWindow.Peek())
{
case '|':
textWindow.Advance();
return TokenType.LogicalOr;
}
}
return TokenType.Unrecognized;
case '\'':
// "'''" means we're starting a multiline string.
if (textWindow.Peek(0) == '\'' && textWindow.Peek(1) == '\'')
{
textWindow.Advance(2);
return ScanMultilineString();
}
var token = ScanStringSegment(true);
if (token == TokenType.StringLeftPiece)
{
// if we're beginning a string interpolation statement, we need to keep track of it
templateStack.Push(token);
}
return token;
case '\n':
case '\r':
if (templateStack.Any())
{
// need to re-check the newline token on next pass
textWindow.Rewind();
// do not consume the new line character
// TODO: figure out a way to avoid returning this multiple times for nested interpolation
AddDiagnostic(b => b.UnterminatedStringWithNewLine());
templateStack.Clear();
return TokenType.StringRightPiece;
}
this.ScanNewLine();
return TokenType.NewLine;
default:
if (IsDigit(nextChar))
{
this.ScanNumber();
return TokenType.Integer;
}
if (IsIdentifierStart(nextChar))
{
return this.ScanIdentifier();
}
return TokenType.Unrecognized;
}
}
// obtaining the unicode category is expensive and should be avoided in the main cases
private static bool IsIdentifierStart(char c) => c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_';
// obtaining the unicode category is expensive and should be avoided in the main cases
private static bool IsIdentifierContinuation(char c) => IsIdentifierStart(c) || IsDigit(c);
private static bool IsDigit(char c) => c >= '0' && c <= '9';
private static bool IsHexDigit(char c) => IsDigit(c) || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
private static bool IsWhiteSpace(char c) => c == ' ' || c == '\t';
private static bool IsNewLine(char c) => c == '\n' || c == '\r';
}
}
| 36.092323 | 205 | 0.449554 | [
"MIT"
] | marknic/BicepXray | src/Bicep.Core/Parsing/Lexer.cs | 37,139 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Rekognition.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Rekognition.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for StartCelebrityRecognition operation
/// </summary>
public class StartCelebrityRecognitionResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
StartCelebrityRecognitionResponse response = new StartCelebrityRecognitionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("JobId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.JobId = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("IdempotentParameterMismatchException"))
{
return new IdempotentParameterMismatchException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerError"))
{
return new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException"))
{
return new InvalidParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidS3ObjectException"))
{
return new InvalidS3ObjectException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ProvisionedThroughputExceededException"))
{
return new ProvisionedThroughputExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return new ThrottlingException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("VideoTooLargeException"))
{
return new VideoTooLargeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonRekognitionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static StartCelebrityRecognitionResponseUnmarshaller _instance = new StartCelebrityRecognitionResponseUnmarshaller();
internal static StartCelebrityRecognitionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static StartCelebrityRecognitionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 46.496241 | 182 | 0.672704 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/StartCelebrityRecognitionResponseUnmarshaller.cs | 6,184 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Markup;
namespace FileChecksumUtility
{
public class EnumBindingSourceExtension : MarkupExtension
{
public Type EnumType { get; private set; }
public EnumBindingSourceExtension(Type enumType)
{
if (enumType is null || !enumType.IsEnum)
{
throw new Exception("EnumType must be of type Enum and not be null.");
}
EnumType = enumType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Enum.GetValues(EnumType);
}
}
}
| 25.222222 | 86 | 0.621145 | [
"MIT"
] | thedevbc/FileChecksumUtility | EnumBindingSourceExtension.cs | 683 | 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.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System.Data.Odbc
{
internal static class ODBC
{
internal static Exception ConnectionClosed()
{
return ADP.InvalidOperation(SR.GetString(SR.Odbc_ConnectionClosed));
}
internal static Exception OpenConnectionNoOwner()
{
return ADP.InvalidOperation(SR.GetString(SR.Odbc_OpenConnectionNoOwner));
}
internal static Exception UnknownSQLType(ODBC32.SQL_TYPE sqltype)
{
return ADP.Argument(SR.GetString(SR.Odbc_UnknownSQLType, sqltype.ToString()));
}
internal static Exception ConnectionStringTooLong()
{
return ADP.Argument(SR.GetString(SR.OdbcConnection_ConnectionStringTooLong, ODBC32.MAX_CONNECTION_STRING_LENGTH));
}
internal static ArgumentException GetSchemaRestrictionRequired()
{
return ADP.Argument(SR.GetString(SR.ODBC_GetSchemaRestrictionRequired));
}
internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value)
{
return ADP.ArgumentOutOfRange(SR.GetString(SR.ODBC_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
}
internal static ArgumentOutOfRangeException NotSupportedCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
Debug.Assert(false, "valid CommandType " + value.ToString());
break;
case CommandType.TableDirect:
break;
default:
Debug.Assert(false, "invalid CommandType " + value.ToString());
break;
}
#endif
return ODBC.NotSupportedEnumerationValue(typeof(CommandType), (int)value);
}
internal static ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.ReadCommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Assert(false, "valid IsolationLevel " + value.ToString());
break;
case IsolationLevel.Chaos:
break;
default:
Debug.Assert(false, "invalid IsolationLevel " + value.ToString());
break;
}
#endif
return ODBC.NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value);
}
internal static InvalidOperationException NoMappingForSqlTransactionLevel(int value)
{
return ADP.DataAdapter(SR.GetString(SR.Odbc_NoMappingForSqlTransactionLevel, value.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception NegativeArgument()
{
return ADP.Argument(SR.GetString(SR.Odbc_NegativeArgument));
}
internal static Exception CantSetPropertyOnOpenConnection()
{
return ADP.InvalidOperation(SR.GetString(SR.Odbc_CantSetPropertyOnOpenConnection));
}
internal static Exception CantEnableConnectionpooling(ODBC32.RetCode retcode)
{
return ADP.DataAdapter(SR.GetString(SR.Odbc_CantEnableConnectionpooling, ODBC32.RetcodeToString(retcode)));
}
internal static Exception CantAllocateEnvironmentHandle(ODBC32.RetCode retcode)
{
return ADP.DataAdapter(SR.GetString(SR.Odbc_CantAllocateEnvironmentHandle, ODBC32.RetcodeToString(retcode)));
}
internal static Exception FailedToGetDescriptorHandle(ODBC32.RetCode retcode)
{
return ADP.DataAdapter(SR.GetString(SR.Odbc_FailedToGetDescriptorHandle, ODBC32.RetcodeToString(retcode)));
}
internal static Exception NotInTransaction()
{
return ADP.InvalidOperation(SR.GetString(SR.Odbc_NotInTransaction));
}
internal static Exception UnknownOdbcType(OdbcType odbctype)
{
return ADP.InvalidEnumerationValue(typeof(OdbcType), (int)odbctype);
}
internal const string Pwd = "pwd";
internal static void TraceODBC(int level, string method, ODBC32.RetCode retcode)
{
}
internal static short ShortStringLength(string inputString)
{
return checked((short)ADP.StringLength(inputString));
}
}
internal static class ODBC32
{
internal enum SQL_HANDLE : short
{
ENV = 1,
DBC = 2,
STMT = 3,
DESC = 4,
}
// from .\public\sdk\inc\sqlext.h: and .\public\sdk\inc\sql.h
// must be public because it is serialized by OdbcException
public enum RETCODE : int
{ // must be int instead of short for Everett OdbcException Serializablity.
SUCCESS = 0,
SUCCESS_WITH_INFO = 1,
ERROR = -1,
INVALID_HANDLE = -2,
NO_DATA = 100,
}
// must be public because it is serialized by OdbcException
internal enum RetCode : short
{
SUCCESS = 0,
SUCCESS_WITH_INFO = 1,
ERROR = -1,
INVALID_HANDLE = -2,
NO_DATA = 100,
}
internal static string RetcodeToString(RetCode retcode)
{
switch (retcode)
{
case RetCode.SUCCESS: return "SUCCESS";
case RetCode.SUCCESS_WITH_INFO: return "SUCCESS_WITH_INFO";
case RetCode.ERROR: return "ERROR";
case RetCode.INVALID_HANDLE: return "INVALID_HANDLE";
case RetCode.NO_DATA: return "NO_DATA";
default:
Debug.Assert(false, "Unknown enumerator passed to RetcodeToString method");
goto case RetCode.ERROR;
}
}
internal enum SQL_CONVERT : ushort
{
BIGINT = 53,
BINARY = 54,
BIT = 55,
CHAR = 56,
DATE = 57,
DECIMAL = 58,
DOUBLE = 59,
FLOAT = 60,
INTEGER = 61,
LONGVARCHAR = 62,
NUMERIC = 63,
REAL = 64,
SMALLINT = 65,
TIME = 66,
TIMESTAMP = 67,
TINYINT = 68,
VARBINARY = 69,
VARCHAR = 70,
LONGVARBINARY = 71,
}
[Flags]
internal enum SQL_CVT
{
CHAR = 0x00000001,
NUMERIC = 0x00000002,
DECIMAL = 0x00000004,
INTEGER = 0x00000008,
SMALLINT = 0x00000010,
FLOAT = 0x00000020,
REAL = 0x00000040,
DOUBLE = 0x00000080,
VARCHAR = 0x00000100,
LONGVARCHAR = 0x00000200,
BINARY = 0x00000400,
VARBINARY = 0x00000800,
BIT = 0x00001000,
TINYINT = 0x00002000,
BIGINT = 0x00004000,
DATE = 0x00008000,
TIME = 0x00010000,
TIMESTAMP = 0x00020000,
LONGVARBINARY = 0x00040000,
INTERVAL_YEAR_MONTH = 0x00080000,
INTERVAL_DAY_TIME = 0x00100000,
WCHAR = 0x00200000,
WLONGVARCHAR = 0x00400000,
WVARCHAR = 0x00800000,
GUID = 0x01000000,
}
internal enum STMT : short
{
CLOSE = 0,
DROP = 1,
UNBIND = 2,
RESET_PARAMS = 3,
}
internal enum SQL_MAX
{
NUMERIC_LEN = 16,
}
internal enum SQL_IS
{
POINTER = -4,
INTEGER = -6,
UINTEGER = -5,
SMALLINT = -8,
}
//SQL Server specific defines
//
internal enum SQL_HC // from Odbcss.h
{
OFF = 0, // FOR BROWSE columns are hidden
ON = 1, // FOR BROWSE columns are exposed
}
internal enum SQL_NB // from Odbcss.h
{
OFF = 0, // NO_BROWSETABLE is off
ON = 1, // NO_BROWSETABLE is on
}
// SQLColAttributes driver specific defines.
// SQLSet/GetDescField driver specific defines.
// Microsoft has 1200 thru 1249 reserved for Microsoft SQL Server driver usage.
//
internal enum SQL_CA_SS // from Odbcss.h
{
BASE = 1200, // SQL_CA_SS_BASE
COLUMN_HIDDEN = BASE + 11, // Column is hidden (FOR BROWSE)
COLUMN_KEY = BASE + 12, // Column is key column (FOR BROWSE)
VARIANT_TYPE = BASE + 15,
VARIANT_SQL_TYPE = BASE + 16,
VARIANT_SERVER_TYPE = BASE + 17,
}
internal enum SQL_SOPT_SS // from Odbcss.h
{
BASE = 1225, // SQL_SOPT_SS_BASE
HIDDEN_COLUMNS = BASE + 2, // Expose FOR BROWSE hidden columns
NOBROWSETABLE = BASE + 3, // Set NOBROWSETABLE option
}
internal const Int16 SQL_COMMIT = 0; //Commit
internal const Int16 SQL_ROLLBACK = 1; //Abort
internal static readonly IntPtr SQL_AUTOCOMMIT_OFF = ADP.PtrZero;
internal static readonly IntPtr SQL_AUTOCOMMIT_ON = new IntPtr(1);
internal enum SQL_TRANSACTION
{
READ_UNCOMMITTED = 0x00000001,
READ_COMMITTED = 0x00000002,
REPEATABLE_READ = 0x00000004,
SERIALIZABLE = 0x00000008,
SNAPSHOT = 0x00000020, // VSDD 414121: SQL_TXN_SS_SNAPSHOT == 0x20 (sqlncli.h)
}
internal enum SQL_PARAM
{
// unused TYPE_UNKNOWN = 0, // SQL_PARAM_TYPE_UNKNOWN
INPUT = 1, // SQL_PARAM_INPUT
INPUT_OUTPUT = 2, // SQL_PARAM_INPUT_OUTPUT
// unused RESULT_COL = 3, // SQL_RESULT_COL
OUTPUT = 4, // SQL_PARAM_OUTPUT
RETURN_VALUE = 5, // SQL_RETURN_VALUE
}
// SQL_API_* values
// there are a gillion of these I am only defining the ones currently needed
// others can be added as needed
internal enum SQL_API : ushort
{
SQLCOLUMNS = 40,
SQLEXECDIRECT = 11,
SQLGETTYPEINFO = 47,
SQLPROCEDURECOLUMNS = 66,
SQLPROCEDURES = 67,
SQLSTATISTICS = 53,
SQLTABLES = 54,
}
internal enum SQL_DESC : short
{
// from sql.h (ODBCVER >= 3.0)
//
COUNT = 1001,
TYPE = 1002,
LENGTH = 1003,
OCTET_LENGTH_PTR = 1004,
PRECISION = 1005,
SCALE = 1006,
DATETIME_INTERVAL_CODE = 1007,
NULLABLE = 1008,
INDICATOR_PTR = 1009,
DATA_PTR = 1010,
NAME = 1011,
UNNAMED = 1012,
OCTET_LENGTH = 1013,
ALLOC_TYPE = 1099,
// from sqlext.h (ODBCVER >= 3.0)
//
CONCISE_TYPE = SQL_COLUMN.TYPE,
DISPLAY_SIZE = SQL_COLUMN.DISPLAY_SIZE,
UNSIGNED = SQL_COLUMN.UNSIGNED,
UPDATABLE = SQL_COLUMN.UPDATABLE,
AUTO_UNIQUE_VALUE = SQL_COLUMN.AUTO_INCREMENT,
TYPE_NAME = SQL_COLUMN.TYPE_NAME,
TABLE_NAME = SQL_COLUMN.TABLE_NAME,
SCHEMA_NAME = SQL_COLUMN.OWNER_NAME,
CATALOG_NAME = SQL_COLUMN.QUALIFIER_NAME,
BASE_COLUMN_NAME = 22,
BASE_TABLE_NAME = 23,
}
// ODBC version 2.0 style attributes
// All IdentifierValues are ODBC 1.0 unless marked differently
//
internal enum SQL_COLUMN
{
COUNT = 0,
NAME = 1,
TYPE = 2,
LENGTH = 3,
PRECISION = 4,
SCALE = 5,
DISPLAY_SIZE = 6,
NULLABLE = 7,
UNSIGNED = 8,
MONEY = 9,
UPDATABLE = 10,
AUTO_INCREMENT = 11,
CASE_SENSITIVE = 12,
SEARCHABLE = 13,
TYPE_NAME = 14,
TABLE_NAME = 15, // (ODBC 2.0)
OWNER_NAME = 16, // (ODBC 2.0)
QUALIFIER_NAME = 17, // (ODBC 2.0)
LABEL = 18,
}
internal enum SQL_GROUP_BY
{
NOT_SUPPORTED = 0, // SQL_GB_NOT_SUPPORTED
GROUP_BY_EQUALS_SELECT = 1, // SQL_GB_GROUP_BY_EQUALS_SELECT
GROUP_BY_CONTAINS_SELECT = 2, // SQL_GB_GROUP_BY_CONTAINS_SELECT
NO_RELATION = 3, // SQL_GB_NO_RELATION
COLLATE = 4, // SQL_GB_COLLATE - added in ODBC 3.0
}
// values from sqlext.h
internal enum SQL_SQL92_RELATIONAL_JOIN_OPERATORS
{
CORRESPONDING_CLAUSE = 0x00000001, // SQL_SRJO_CORRESPONDING_CLAUSE
CROSS_JOIN = 0x00000002, // SQL_SRJO_CROSS_JOIN
EXCEPT_JOIN = 0x00000004, // SQL_SRJO_EXCEPT_JOIN
FULL_OUTER_JOIN = 0x00000008, // SQL_SRJO_FULL_OUTER_JOIN
INNER_JOIN = 0x00000010, // SQL_SRJO_INNER_JOIN
INTERSECT_JOIN = 0x00000020, // SQL_SRJO_INTERSECT_JOIN
LEFT_OUTER_JOIN = 0x00000040, // SQL_SRJO_LEFT_OUTER_JOIN
NATURAL_JOIN = 0x00000080, // SQL_SRJO_NATURAL_JOIN
RIGHT_OUTER_JOIN = 0x00000100, // SQL_SRJO_RIGHT_OUTER_JOIN
UNION_JOIN = 0x00000200, // SQL_SRJO_UNION_JOIN
}
// values from sql.h
internal enum SQL_OJ_CAPABILITIES
{
LEFT = 0x00000001, // SQL_OJ_LEFT
RIGHT = 0x00000002, // SQL_OJ_RIGHT
FULL = 0x00000004, // SQL_OJ_FULL
NESTED = 0x00000008, // SQL_OJ_NESTED
NOT_ORDERED = 0x00000010, // SQL_OJ_NOT_ORDERED
INNER = 0x00000020, // SQL_OJ_INNER
ALL_COMPARISON_OPS = 0x00000040, //SQL_OJ_ALLCOMPARISION+OPS
}
internal enum SQL_UPDATABLE
{
READONLY = 0, // SQL_ATTR_READ_ONLY
WRITE = 1, // SQL_ATTR_WRITE
READWRITE_UNKNOWN = 2, // SQL_ATTR_READWRITE_UNKNOWN
}
internal enum SQL_IDENTIFIER_CASE
{
UPPER = 1, // SQL_IC_UPPER
LOWER = 2, // SQL_IC_LOWER
SENSITIVE = 3, // SQL_IC_SENSITIVE
MIXED = 4, // SQL_IC_MIXED
}
// Uniqueness parameter in the SQLStatistics function
internal enum SQL_INDEX : short
{
UNIQUE = 0,
ALL = 1,
}
// Reserved parameter in the SQLStatistics function
internal enum SQL_STATISTICS_RESERVED : short
{
QUICK = 0, // SQL_QUICK
ENSURE = 1, // SQL_ENSURE
}
// Identifier type parameter in the SQLSpecialColumns function
internal enum SQL_SPECIALCOLS : ushort
{
BEST_ROWID = 1, // SQL_BEST_ROWID
ROWVER = 2, // SQL_ROWVER
}
// Scope parameter in the SQLSpecialColumns function
internal enum SQL_SCOPE : ushort
{
CURROW = 0, // SQL_SCOPE_CURROW
TRANSACTION = 1, // SQL_SCOPE_TRANSACTION
SESSION = 2, // SQL_SCOPE_SESSION
}
internal enum SQL_NULLABILITY : ushort
{
NO_NULLS = 0, // SQL_NO_NULLS
NULLABLE = 1, // SQL_NULLABLE
UNKNOWN = 2, // SQL_NULLABLE_UNKNOWN
}
internal enum SQL_SEARCHABLE
{
UNSEARCHABLE = 0, // SQL_UNSEARCHABLE
LIKE_ONLY = 1, // SQL_LIKE_ONLY
ALL_EXCEPT_LIKE = 2, // SQL_ALL_EXCEPT_LIKE
SEARCHABLE = 3, // SQL_SEARCHABLE
}
internal enum SQL_UNNAMED
{
NAMED = 0, // SQL_NAMED
UNNAMED = 1, // SQL_UNNAMED
}
// todo:move
// internal constants
// not odbc specific
//
internal enum HANDLER
{
IGNORE = 0x00000000,
THROW = 0x00000001,
}
// values for SQLStatistics TYPE column
internal enum SQL_STATISTICSTYPE
{
TABLE_STAT = 0, // TABLE Statistics
INDEX_CLUSTERED = 1, // CLUSTERED index statistics
INDEX_HASHED = 2, // HASHED index statistics
INDEX_OTHER = 3, // OTHER index statistics
}
// values for SQLProcedures PROCEDURE_TYPE column
internal enum SQL_PROCEDURETYPE
{
UNKNOWN = 0, // procedure is of unknow type
PROCEDURE = 1, // procedure is a procedure
FUNCTION = 2, // procedure is a function
}
// private constants
// to define data types (see below)
//
private const Int32 SIGNED_OFFSET = -20; // SQL_SIGNED_OFFSET
private const Int32 UNSIGNED_OFFSET = -22; // SQL_UNSIGNED_OFFSET
//C Data Types - used when getting data (SQLGetData)
internal enum SQL_C : short
{
CHAR = 1, //SQL_C_CHAR
WCHAR = -8, //SQL_C_WCHAR
SLONG = 4 + SIGNED_OFFSET, //SQL_C_LONG+SQL_SIGNED_OFFSET
// ULONG = 4 + UNSIGNED_OFFSET, //SQL_C_LONG+SQL_UNSIGNED_OFFSET
SSHORT = 5 + SIGNED_OFFSET, //SQL_C_SSHORT+SQL_SIGNED_OFFSET
// USHORT = 5 + UNSIGNED_OFFSET, //SQL_C_USHORT+SQL_UNSIGNED_OFFSET
REAL = 7, //SQL_C_REAL
DOUBLE = 8, //SQL_C_DOUBLE
BIT = -7, //SQL_C_BIT
// STINYINT = -6 + SIGNED_OFFSET, //SQL_C_STINYINT+SQL_SIGNED_OFFSET
UTINYINT = -6 + UNSIGNED_OFFSET, //SQL_C_UTINYINT+SQL_UNSIGNED_OFFSET
SBIGINT = -5 + SIGNED_OFFSET, //SQL_C_SBIGINT+SQL_SIGNED_OFFSET
UBIGINT = -5 + UNSIGNED_OFFSET, //SQL_C_UBIGINT+SQL_UNSIGNED_OFFSET
BINARY = -2, //SQL_C_BINARY
TIMESTAMP = 11, //SQL_C_TIMESTAMP
TYPE_DATE = 91, //SQL_C_TYPE_DATE
TYPE_TIME = 92, //SQL_C_TYPE_TIME
TYPE_TIMESTAMP = 93, //SQL_C_TYPE_TIMESTAMP
NUMERIC = 2, //SQL_C_NUMERIC
GUID = -11, //SQL_C_GUID
DEFAULT = 99, //SQL_C_DEFAULT
ARD_TYPE = -99, //SQL_ARD_TYPE
}
//SQL Data Types - returned as column types (SQLColAttribute)
internal enum SQL_TYPE : short
{
CHAR = SQL_C.CHAR, //SQL_CHAR
VARCHAR = 12, //SQL_VARCHAR
LONGVARCHAR = -1, //SQL_LONGVARCHAR
WCHAR = SQL_C.WCHAR, //SQL_WCHAR
WVARCHAR = -9, //SQL_WVARCHAR
WLONGVARCHAR = -10, //SQL_WLONGVARCHAR
DECIMAL = 3, //SQL_DECIMAL
NUMERIC = SQL_C.NUMERIC, //SQL_NUMERIC
SMALLINT = 5, //SQL_SMALLINT
INTEGER = 4, //SQL_INTEGER
REAL = SQL_C.REAL, //SQL_REAL
FLOAT = 6, //SQL_FLOAT
DOUBLE = SQL_C.DOUBLE, //SQL_DOUBLE
BIT = SQL_C.BIT, //SQL_BIT
TINYINT = -6, //SQL_TINYINT
BIGINT = -5, //SQL_BIGINT
BINARY = SQL_C.BINARY, //SQL_BINARY
VARBINARY = -3, //SQL_VARBINARY
LONGVARBINARY = -4, //SQL_LONGVARBINARY
// DATE = 9, //SQL_DATE
TYPE_DATE = SQL_C.TYPE_DATE, //SQL_TYPE_DATE
TYPE_TIME = SQL_C.TYPE_TIME, //SQL_TYPE_TIME
TIMESTAMP = SQL_C.TIMESTAMP, //SQL_TIMESTAMP
TYPE_TIMESTAMP = SQL_C.TYPE_TIMESTAMP, //SQL_TYPE_TIMESTAMP
GUID = SQL_C.GUID, //SQL_GUID
// from odbcss.h in mdac 9.0 sources!
// Driver specific SQL type defines.
// Microsoft has -150 thru -199 reserved for Microsoft SQL Server driver usage.
//
SS_VARIANT = -150,
SS_UDT = -151,
SS_XML = -152,
SS_UTCDATETIME = -153,
SS_TIME_EX = -154,
}
internal const Int16 SQL_ALL_TYPES = 0;
internal static readonly IntPtr SQL_HANDLE_NULL = ADP.PtrZero;
internal const Int32 SQL_NULL_DATA = -1; // sql.h
internal const Int32 SQL_NO_TOTAL = -4; // sqlext.h
internal const Int32 SQL_DEFAULT_PARAM = -5;
// internal const Int32 SQL_IGNORE = -6;
// column ordinals for SQLProcedureColumns result set
// this column ordinals are not defined in any c/c++ header but in the ODBC Programmer's Reference under SQLProcedureColumns
//
internal const Int32 COLUMN_NAME = 4;
internal const Int32 COLUMN_TYPE = 5;
internal const Int32 DATA_TYPE = 6;
internal const Int32 COLUMN_SIZE = 8;
internal const Int32 DECIMAL_DIGITS = 10;
internal const Int32 NUM_PREC_RADIX = 11;
internal enum SQL_ATTR
{
APP_ROW_DESC = 10010, // (ODBC 3.0)
APP_PARAM_DESC = 10011, // (ODBC 3.0)
IMP_ROW_DESC = 10012, // (ODBC 3.0)
IMP_PARAM_DESC = 10013, // (ODBC 3.0)
METADATA_ID = 10014, // (ODBC 3.0)
ODBC_VERSION = 200,
CONNECTION_POOLING = 201,
AUTOCOMMIT = 102,
TXN_ISOLATION = 108,
CURRENT_CATALOG = 109,
LOGIN_TIMEOUT = 103,
QUERY_TIMEOUT = 0, // from sqlext.h
CONNECTION_DEAD = 1209, // from sqlext.h
// from sqlncli.h
SQL_COPT_SS_BASE = 1200,
SQL_COPT_SS_ENLIST_IN_DTC = (SQL_COPT_SS_BASE + 7),
SQL_COPT_SS_TXN_ISOLATION = (SQL_COPT_SS_BASE + 27), // Used to set/get any driver-specific or ODBC-defined TXN iso level
}
//SQLGetInfo
internal enum SQL_INFO : ushort
{
DATA_SOURCE_NAME = 2, // SQL_DATA_SOURCE_NAME in sql.h
SERVER_NAME = 13, // SQL_SERVER_NAME in sql.h
DRIVER_NAME = 6, // SQL_DRIVER_NAME as defined in sqlext.h
DRIVER_VER = 7, // SQL_DRIVER_VER as defined in sqlext.h
ODBC_VER = 10, // SQL_ODBC_VER as defined in sqlext.h
SEARCH_PATTERN_ESCAPE = 14, // SQL_SEARCH_PATTERN_ESCAPE from sql.h
DBMS_VER = 18,
DBMS_NAME = 17, // SQL_DBMS_NAME as defined in sqlext.h
IDENTIFIER_CASE = 28, // SQL_IDENTIFIER_CASE from sql.h
IDENTIFIER_QUOTE_CHAR = 29, // SQL_IDENTIFIER_QUOTE_CHAR from sql.h
CATALOG_NAME_SEPARATOR = 41, // SQL_CATALOG_NAME_SEPARATOR
DRIVER_ODBC_VER = 77, // SQL_DRIVER_ODBC_VER as defined in sqlext.h
GROUP_BY = 88, // SQL_GROUP_BY as defined in sqlext.h
KEYWORDS = 89, // SQL_KEYWORDS as defined in sqlext.h
ORDER_BY_COLUMNS_IN_SELECT = 90, // SQL_ORDER_BY_COLUNS_IN_SELECT in sql.h
QUOTED_IDENTIFIER_CASE = 93, // SQL_QUOTED_IDENTIFIER_CASE in sqlext.h
SQL_OJ_CAPABILITIES_30 = 115, //SQL_OJ_CAPABILITIES from sql.h
SQL_OJ_CAPABILITIES_20 = 65003, //SQL_OJ_CAPABILITIES from sqlext.h
SQL_SQL92_RELATIONAL_JOIN_OPERATORS = 161, //SQL_SQL92_RELATIONAL_JOIN_OPERATORS from sqlext.h
}
internal static readonly IntPtr SQL_OV_ODBC3 = new IntPtr(3);
internal const Int32 SQL_NTS = -3; //flags for null-terminated string
//Pooling
internal static readonly IntPtr SQL_CP_OFF = new IntPtr(0); //Connection Pooling disabled
internal static readonly IntPtr SQL_CP_ONE_PER_DRIVER = new IntPtr(1); //One pool per driver
internal static readonly IntPtr SQL_CP_ONE_PER_HENV = new IntPtr(2); //One pool per environment
/* values for SQL_ATTR_CONNECTION_DEAD */
internal const Int32 SQL_CD_TRUE = 1;
internal const Int32 SQL_CD_FALSE = 0;
internal const Int32 SQL_DTC_DONE = 0;
internal const Int32 SQL_IS_POINTER = -4;
internal const Int32 SQL_IS_PTR = 1;
internal enum SQL_DRIVER
{
NOPROMPT = 0,
COMPLETE = 1,
PROMPT = 2,
COMPLETE_REQUIRED = 3,
}
// todo:move
// internal const. not odbc specific
//
// Connection string max length
internal const Int32 MAX_CONNECTION_STRING_LENGTH = 1024;
// Column set for SQLPrimaryKeys
internal enum SQL_PRIMARYKEYS : short
{
/*
CATALOGNAME = 1, // TABLE_CAT
SCHEMANAME = 2, // TABLE_SCHEM
TABLENAME = 3, // TABLE_NAME
*/
COLUMNNAME = 4, // COLUMN_NAME
/*
KEY_SEQ = 5, // KEY_SEQ
PKNAME = 6, // PK_NAME
*/
}
// Column set for SQLStatistics
internal enum SQL_STATISTICS : short
{
/*
CATALOGNAME = 1, // TABLE_CAT
SCHEMANAME = 2, // TABLE_SCHEM
TABLENAME = 3, // TABLE_NAME
NONUNIQUE = 4, // NON_UNIQUE
INDEXQUALIFIER = 5, // INDEX_QUALIFIER
*/
INDEXNAME = 6, // INDEX_NAME
/*
TYPE = 7, // TYPE
*/
ORDINAL_POSITION = 8, // ORDINAL_POSITION
COLUMN_NAME = 9, // COLUMN_NAME
/*
ASC_OR_DESC = 10, // ASC_OR_DESC
CARDINALITY = 11, // CARDINALITY
PAGES = 12, // PAGES
FILTER_CONDITION = 13, // FILTER_CONDITION
*/
}
// Column set for SQLSpecialColumns
internal enum SQL_SPECIALCOLUMNSET : short
{
/*
SCOPE = 1, // SCOPE
*/
COLUMN_NAME = 2, // COLUMN_NAME
/*
DATA_TYPE = 3, // DATA_TYPE
TYPE_NAME = 4, // TYPE_NAME
COLUMN_SIZE = 5, // COLUMN_SIZE
BUFFER_LENGTH = 6, // BUFFER_LENGTH
DECIMAL_DIGITS = 7, // DECIMAL_DIGITS
PSEUDO_COLUMN = 8, // PSEUDO_COLUMN
*/
}
internal const short SQL_DIAG_SQLSTATE = 4;
internal const short SQL_RESULT_COL = 3;
// Helpers
internal static OdbcErrorCollection GetDiagErrors(string source, OdbcHandle hrHandle, RetCode retcode)
{
OdbcErrorCollection errors = new OdbcErrorCollection();
GetDiagErrors(errors, source, hrHandle, retcode);
return errors;
}
internal static void GetDiagErrors(OdbcErrorCollection errors, string source, OdbcHandle hrHandle, RetCode retcode)
{
Debug.Assert(retcode != ODBC32.RetCode.INVALID_HANDLE, "retcode must never be ODBC32.RetCode.INVALID_HANDLE");
if (RetCode.SUCCESS != retcode)
{
Int32 NativeError;
Int16 iRec = 0;
Int16 cchActual = 0;
StringBuilder message = new StringBuilder(1024);
string sqlState;
bool moreerrors = true;
while (moreerrors)
{
++iRec;
retcode = hrHandle.GetDiagnosticRecord(iRec, out sqlState, message, out NativeError, out cchActual);
if ((RetCode.SUCCESS_WITH_INFO == retcode) && (message.Capacity - 1 < cchActual))
{
message.Capacity = cchActual + 1;
retcode = hrHandle.GetDiagnosticRecord(iRec, out sqlState, message, out NativeError, out cchActual);
}
//Note: SUCCESS_WITH_INFO from SQLGetDiagRec would be because
//the buffer is not large enough for the error string.
moreerrors = (retcode == RetCode.SUCCESS || retcode == RetCode.SUCCESS_WITH_INFO);
if (moreerrors)
{
//Sets up the InnerException as well...
errors.Add(new OdbcError(
source,
message.ToString(),
sqlState,
NativeError
)
);
}
}
}
}
}
internal sealed class TypeMap
{ // MDAC 68988
// private TypeMap (OdbcType odbcType, DbType dbType, Type type, ODBC32.SQL_TYPE sql_type, ODBC32.SQL_C sql_c, ODBC32.SQL_C param_sql_c, int bsize, int csize, bool signType)
// --------------- ------------------ -------------- ---------- ------------------------- ------------------- ------------------------- -----------------------
private static readonly TypeMap s_bigInt = new TypeMap(OdbcType.BigInt, DbType.Int64, typeof(Int64), ODBC32.SQL_TYPE.BIGINT, ODBC32.SQL_C.SBIGINT, ODBC32.SQL_C.SBIGINT, 8, 20, true);
private static readonly TypeMap s_binary = new TypeMap(OdbcType.Binary, DbType.Binary, typeof(byte[]), ODBC32.SQL_TYPE.BINARY, ODBC32.SQL_C.BINARY, ODBC32.SQL_C.BINARY, -1, -1, false);
private static readonly TypeMap s_bit = new TypeMap(OdbcType.Bit, DbType.Boolean, typeof(Boolean), ODBC32.SQL_TYPE.BIT, ODBC32.SQL_C.BIT, ODBC32.SQL_C.BIT, 1, 1, false);
internal static readonly TypeMap _Char = new TypeMap(OdbcType.Char, DbType.AnsiStringFixedLength, typeof(String), ODBC32.SQL_TYPE.CHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.CHAR, -1, -1, false);
private static readonly TypeMap s_dateTime = new TypeMap(OdbcType.DateTime, DbType.DateTime, typeof(DateTime), ODBC32.SQL_TYPE.TYPE_TIMESTAMP, ODBC32.SQL_C.TYPE_TIMESTAMP, ODBC32.SQL_C.TYPE_TIMESTAMP, 16, 23, false);
private static readonly TypeMap s_date = new TypeMap(OdbcType.Date, DbType.Date, typeof(DateTime), ODBC32.SQL_TYPE.TYPE_DATE, ODBC32.SQL_C.TYPE_DATE, ODBC32.SQL_C.TYPE_DATE, 6, 10, false);
private static readonly TypeMap s_time = new TypeMap(OdbcType.Time, DbType.Time, typeof(TimeSpan), ODBC32.SQL_TYPE.TYPE_TIME, ODBC32.SQL_C.TYPE_TIME, ODBC32.SQL_C.TYPE_TIME, 6, 12, false);
private static readonly TypeMap s_decimal = new TypeMap(OdbcType.Decimal, DbType.Decimal, typeof(Decimal), ODBC32.SQL_TYPE.DECIMAL, ODBC32.SQL_C.NUMERIC, ODBC32.SQL_C.NUMERIC, 19, ADP.DecimalMaxPrecision28, false);
// static private readonly TypeMap _Currency = new TypeMap(OdbcType.Decimal, DbType.Currency, typeof(Decimal), ODBC32.SQL_TYPE.DECIMAL, ODBC32.SQL_C.NUMERIC, ODBC32.SQL_C.NUMERIC, 19, ADP.DecimalMaxPrecision28, false);
private static readonly TypeMap s_double = new TypeMap(OdbcType.Double, DbType.Double, typeof(Double), ODBC32.SQL_TYPE.DOUBLE, ODBC32.SQL_C.DOUBLE, ODBC32.SQL_C.DOUBLE, 8, 15, false);
internal static readonly TypeMap _Image = new TypeMap(OdbcType.Image, DbType.Binary, typeof(Byte[]), ODBC32.SQL_TYPE.LONGVARBINARY, ODBC32.SQL_C.BINARY, ODBC32.SQL_C.BINARY, -1, -1, false);
private static readonly TypeMap s_int = new TypeMap(OdbcType.Int, DbType.Int32, typeof(Int32), ODBC32.SQL_TYPE.INTEGER, ODBC32.SQL_C.SLONG, ODBC32.SQL_C.SLONG, 4, 10, true);
private static readonly TypeMap s_NChar = new TypeMap(OdbcType.NChar, DbType.StringFixedLength, typeof(String), ODBC32.SQL_TYPE.WCHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.WCHAR, -1, -1, false);
internal static readonly TypeMap _NText = new TypeMap(OdbcType.NText, DbType.String, typeof(String), ODBC32.SQL_TYPE.WLONGVARCHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.WCHAR, -1, -1, false);
private static readonly TypeMap s_numeric = new TypeMap(OdbcType.Numeric, DbType.Decimal, typeof(Decimal), ODBC32.SQL_TYPE.NUMERIC, ODBC32.SQL_C.NUMERIC, ODBC32.SQL_C.NUMERIC, 19, ADP.DecimalMaxPrecision28, false);
internal static readonly TypeMap _NVarChar = new TypeMap(OdbcType.NVarChar, DbType.String, typeof(String), ODBC32.SQL_TYPE.WVARCHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.WCHAR, -1, -1, false);
private static readonly TypeMap s_real = new TypeMap(OdbcType.Real, DbType.Single, typeof(Single), ODBC32.SQL_TYPE.REAL, ODBC32.SQL_C.REAL, ODBC32.SQL_C.REAL, 4, 7, false);
private static readonly TypeMap s_uniqueId = new TypeMap(OdbcType.UniqueIdentifier, DbType.Guid, typeof(Guid), ODBC32.SQL_TYPE.GUID, ODBC32.SQL_C.GUID, ODBC32.SQL_C.GUID, 16, 36, false);
private static readonly TypeMap s_smallDT = new TypeMap(OdbcType.SmallDateTime, DbType.DateTime, typeof(DateTime), ODBC32.SQL_TYPE.TYPE_TIMESTAMP, ODBC32.SQL_C.TYPE_TIMESTAMP, ODBC32.SQL_C.TYPE_TIMESTAMP, 16, 23, false);
private static readonly TypeMap s_smallInt = new TypeMap(OdbcType.SmallInt, DbType.Int16, typeof(Int16), ODBC32.SQL_TYPE.SMALLINT, ODBC32.SQL_C.SSHORT, ODBC32.SQL_C.SSHORT, 2, 5, true);
internal static readonly TypeMap _Text = new TypeMap(OdbcType.Text, DbType.AnsiString, typeof(String), ODBC32.SQL_TYPE.LONGVARCHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.CHAR, -1, -1, false);
private static readonly TypeMap s_timestamp = new TypeMap(OdbcType.Timestamp, DbType.Binary, typeof(Byte[]), ODBC32.SQL_TYPE.BINARY, ODBC32.SQL_C.BINARY, ODBC32.SQL_C.BINARY, -1, -1, false);
private static readonly TypeMap s_tinyInt = new TypeMap(OdbcType.TinyInt, DbType.Byte, typeof(Byte), ODBC32.SQL_TYPE.TINYINT, ODBC32.SQL_C.UTINYINT, ODBC32.SQL_C.UTINYINT, 1, 3, true);
private static readonly TypeMap s_varBinary = new TypeMap(OdbcType.VarBinary, DbType.Binary, typeof(Byte[]), ODBC32.SQL_TYPE.VARBINARY, ODBC32.SQL_C.BINARY, ODBC32.SQL_C.BINARY, -1, -1, false);
internal static readonly TypeMap _VarChar = new TypeMap(OdbcType.VarChar, DbType.AnsiString, typeof(String), ODBC32.SQL_TYPE.VARCHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.CHAR, -1, -1, false);
private static readonly TypeMap s_variant = new TypeMap(OdbcType.Binary, DbType.Binary, typeof(object), ODBC32.SQL_TYPE.SS_VARIANT, ODBC32.SQL_C.BINARY, ODBC32.SQL_C.BINARY, -1, -1, false);
private static readonly TypeMap s_UDT = new TypeMap(OdbcType.Binary, DbType.Binary, typeof(object), ODBC32.SQL_TYPE.SS_UDT, ODBC32.SQL_C.BINARY, ODBC32.SQL_C.BINARY, -1, -1, false);
private static readonly TypeMap s_XML = new TypeMap(OdbcType.Text, DbType.AnsiString, typeof(String), ODBC32.SQL_TYPE.LONGVARCHAR, ODBC32.SQL_C.WCHAR, ODBC32.SQL_C.CHAR, -1, -1, false);
internal readonly OdbcType _odbcType;
internal readonly DbType _dbType;
internal readonly Type _type;
internal readonly ODBC32.SQL_TYPE _sql_type;
internal readonly ODBC32.SQL_C _sql_c;
internal readonly ODBC32.SQL_C _param_sql_c;
internal readonly int _bufferSize; // fixed length byte size to reserve for buffer
internal readonly int _columnSize; // column size passed to SQLBindParameter
internal readonly bool _signType; // this type may be has signature information
private TypeMap(OdbcType odbcType, DbType dbType, Type type, ODBC32.SQL_TYPE sql_type, ODBC32.SQL_C sql_c, ODBC32.SQL_C param_sql_c, int bsize, int csize, bool signType)
{
_odbcType = odbcType;
_dbType = dbType;
_type = type;
_sql_type = sql_type;
_sql_c = sql_c;
_param_sql_c = param_sql_c; // alternative sql_c type for parameters
_bufferSize = bsize;
_columnSize = csize;
_signType = signType;
}
internal static TypeMap FromOdbcType(OdbcType odbcType)
{
switch (odbcType)
{
case OdbcType.BigInt: return s_bigInt;
case OdbcType.Binary: return s_binary;
case OdbcType.Bit: return s_bit;
case OdbcType.Char: return _Char;
case OdbcType.DateTime: return s_dateTime;
case OdbcType.Date: return s_date;
case OdbcType.Time: return s_time;
case OdbcType.Double: return s_double;
case OdbcType.Decimal: return s_decimal;
case OdbcType.Image: return _Image;
case OdbcType.Int: return s_int;
case OdbcType.NChar: return s_NChar;
case OdbcType.NText: return _NText;
case OdbcType.Numeric: return s_numeric;
case OdbcType.NVarChar: return _NVarChar;
case OdbcType.Real: return s_real;
case OdbcType.UniqueIdentifier: return s_uniqueId;
case OdbcType.SmallDateTime: return s_smallDT;
case OdbcType.SmallInt: return s_smallInt;
case OdbcType.Text: return _Text;
case OdbcType.Timestamp: return s_timestamp;
case OdbcType.TinyInt: return s_tinyInt;
case OdbcType.VarBinary: return s_varBinary;
case OdbcType.VarChar: return _VarChar;
default: throw ODBC.UnknownOdbcType(odbcType);
}
}
internal static TypeMap FromDbType(DbType dbType)
{
switch (dbType)
{
case DbType.AnsiString: return _VarChar;
case DbType.AnsiStringFixedLength: return _Char;
case DbType.Binary: return s_varBinary;
case DbType.Byte: return s_tinyInt;
case DbType.Boolean: return s_bit;
case DbType.Currency: return s_decimal;
// case DbType.Currency: return _Currency;
case DbType.Date: return s_date;
case DbType.Time: return s_time;
case DbType.DateTime: return s_dateTime;
case DbType.Decimal: return s_decimal;
case DbType.Double: return s_double;
case DbType.Guid: return s_uniqueId;
case DbType.Int16: return s_smallInt;
case DbType.Int32: return s_int;
case DbType.Int64: return s_bigInt;
case DbType.Single: return s_real;
case DbType.String: return _NVarChar;
case DbType.StringFixedLength: return s_NChar;
case DbType.Object:
case DbType.SByte:
case DbType.UInt16:
case DbType.UInt32:
case DbType.UInt64:
case DbType.VarNumeric:
default: throw ADP.DbTypeNotSupported(dbType, typeof(OdbcType));
}
}
internal static TypeMap FromSystemType(Type dataType)
{
switch (Type.GetTypeCode(dataType))
{
case TypeCode.Empty: throw ADP.InvalidDataType(TypeCode.Empty);
case TypeCode.Object:
if (dataType == typeof(System.Byte[]))
{
return s_varBinary;
}
else if (dataType == typeof(System.Guid))
{
return s_uniqueId;
}
else if (dataType == typeof(System.TimeSpan))
{
return s_time;
}
else if (dataType == typeof(System.Char[]))
{
return _NVarChar;
}
throw ADP.UnknownDataType(dataType);
case TypeCode.DBNull: throw ADP.InvalidDataType(TypeCode.DBNull);
case TypeCode.Boolean: return s_bit;
// devnote: Char is actually not supported. Our _Char type is actually a fixed length string, not a single character
// case TypeCode.Char: return _Char;
case TypeCode.SByte: return s_smallInt;
case TypeCode.Byte: return s_tinyInt;
case TypeCode.Int16: return s_smallInt;
case TypeCode.UInt16: return s_int;
case TypeCode.Int32: return s_int;
case TypeCode.UInt32: return s_bigInt;
case TypeCode.Int64: return s_bigInt;
case TypeCode.UInt64: return s_numeric;
case TypeCode.Single: return s_real;
case TypeCode.Double: return s_double;
case TypeCode.Decimal: return s_numeric;
case TypeCode.DateTime: return s_dateTime;
case TypeCode.Char:
case TypeCode.String: return _NVarChar;
default: throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType));
}
}
internal static TypeMap FromSqlType(ODBC32.SQL_TYPE sqltype)
{
switch (sqltype)
{
case ODBC32.SQL_TYPE.CHAR: return _Char;
case ODBC32.SQL_TYPE.VARCHAR: return _VarChar;
case ODBC32.SQL_TYPE.LONGVARCHAR: return _Text;
case ODBC32.SQL_TYPE.WCHAR: return s_NChar;
case ODBC32.SQL_TYPE.WVARCHAR: return _NVarChar;
case ODBC32.SQL_TYPE.WLONGVARCHAR: return _NText;
case ODBC32.SQL_TYPE.DECIMAL: return s_decimal;
case ODBC32.SQL_TYPE.NUMERIC: return s_numeric;
case ODBC32.SQL_TYPE.SMALLINT: return s_smallInt;
case ODBC32.SQL_TYPE.INTEGER: return s_int;
case ODBC32.SQL_TYPE.REAL: return s_real;
case ODBC32.SQL_TYPE.FLOAT: return s_double;
case ODBC32.SQL_TYPE.DOUBLE: return s_double;
case ODBC32.SQL_TYPE.BIT: return s_bit;
case ODBC32.SQL_TYPE.TINYINT: return s_tinyInt;
case ODBC32.SQL_TYPE.BIGINT: return s_bigInt;
case ODBC32.SQL_TYPE.BINARY: return s_binary;
case ODBC32.SQL_TYPE.VARBINARY: return s_varBinary;
case ODBC32.SQL_TYPE.LONGVARBINARY: return _Image;
case ODBC32.SQL_TYPE.TYPE_DATE: return s_date;
case ODBC32.SQL_TYPE.TYPE_TIME: return s_time;
case ODBC32.SQL_TYPE.TIMESTAMP:
case ODBC32.SQL_TYPE.TYPE_TIMESTAMP: return s_dateTime;
case ODBC32.SQL_TYPE.GUID: return s_uniqueId;
case ODBC32.SQL_TYPE.SS_VARIANT: return s_variant;
case ODBC32.SQL_TYPE.SS_UDT: return s_UDT;
case ODBC32.SQL_TYPE.SS_XML: return s_XML;
case ODBC32.SQL_TYPE.SS_UTCDATETIME:
case ODBC32.SQL_TYPE.SS_TIME_EX:
throw ODBC.UnknownSQLType(sqltype);
default:
throw ODBC.UnknownSQLType(sqltype);
}
}
// Upgrade integer datatypes to missinterpretaion of the highest bit
// (e.g. 0xff could be 255 if unsigned but is -1 if signed)
//
internal static TypeMap UpgradeSignedType(TypeMap typeMap, bool unsigned)
{
// upgrade unsigned types to be able to hold data that has the highest bit set
//
if (unsigned == true)
{
switch (typeMap._dbType)
{
case DbType.Int64:
return s_decimal; // upgrade to decimal
case DbType.Int32:
return s_bigInt; // upgrade to 64 bit
case DbType.Int16:
return s_int; // upgrade to 32 bit
default:
return typeMap;
} // end switch
}
else
{
switch (typeMap._dbType)
{
case DbType.Byte:
return s_smallInt; // upgrade to 16 bit
default:
return typeMap;
} // end switch
}
} // end UpgradeSignedType
}
}
| 44.680077 | 280 | 0.548514 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs | 46,646 | C# |
/*
* nMQTT, a .Net MQTT v3 client implementation.
* http://wiki.github.com/markallanson/nmqtt
*
* Copyright (c) 2009 Mark Allanson (mark@markallanson.net) & Contributors
*
* Licensed under the MIT License. You may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/mit-license.php
*/
using System.IO;
using System.Text;
namespace Nmqtt
{
internal sealed partial class MqttSubscribeMessage : MqttMessage
{
/// <summary>
/// Gets or sets the variable header contents. Contains extended metadata about the message
/// </summary>
/// <value>The variable header.</value>
public MqttSubscribeVariableHeader VariableHeader { get; set; }
/// <summary>
/// Gets or sets the payload of the Mqtt Message.
/// </summary>
/// <value>The payload of the Mqtt Message.</value>
public MqttSubscribePayload Payload { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MqttSubscribeMessage" /> class.
/// </summary>
/// <remarks>
/// Only called via the MqttMessage.Create operation during processing of an Mqtt message stream.
/// </remarks>
public MqttSubscribeMessage() {
this.Header = new MqttHeader().AsType(MqttMessageType.Subscribe);
this.VariableHeader = new MqttSubscribeVariableHeader();
this.Payload = new MqttSubscribePayload();
}
/// <summary>
/// Initializes a new instance of the <see cref="MqttSubscribeMessage" /> class.
/// </summary>
/// <param name="header">The header to use for the message.</param>
/// <param name="messageStream">The message stream positioned after the header.</param>
internal MqttSubscribeMessage(MqttHeader header, Stream messageStream) {
this.Header = header;
ReadFrom(messageStream);
}
/// <summary>
/// Writes the message to the supplied stream.
/// </summary>
/// <param name="messageStream">The stream to write the message to.</param>
public override void WriteTo(Stream messageStream) {
this.Header.WriteTo(this.VariableHeader.GetWriteLength() + this.Payload.GetWriteLength(),
messageStream);
this.VariableHeader.WriteTo(messageStream);
this.Payload.WriteTo(messageStream);
}
/// <summary>
/// Reads a message from the supplied stream.
/// </summary>
/// <param name="messageStream">The message stream.</param>
public override void ReadFrom(Stream messageStream) {
this.VariableHeader = new MqttSubscribeVariableHeader(messageStream);
this.Payload = new MqttSubscribePayload(Header, VariableHeader, messageStream);
}
/// <summary>
/// Returns a <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// A <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
/// </returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append(base.ToString());
sb.AppendLine(VariableHeader.ToString());
sb.AppendLine(Payload.ToString());
return sb.ToString();
}
}
} | 39.577778 | 116 | 0.607243 | [
"MIT"
] | huguoya/nmqtt | nMQTT/Messages/Subscribe/MqttSubscribeMessage.cs | 3,562 | C# |
namespace DeafTelephone.Web.Controllers.LogiServer.BulkLogOperation
{
using DeafTelephone.Hubs;
using DeafTelephone.Web.Core.Domain;
using DeafTelephone.Web.Core.Extensions;
using DeafTelephone.Web.Core.Services;
using DeafTelephone.Web.Hub.Models;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class BulkLogOperationProcessor : IRequestHandler<BulkLogOperationQuery, BulkLogOperationResult>
{
internal const string CACHE_LOCAL_SCOPE_MAP = "CACHE_LOCAL_SCOPE_MAP_{0}";
private readonly IMemoryCache _cache;
private readonly ILogsStoreService _logStoreService;
private readonly IHubContext<LogHub> _hubAccess;
private readonly ILogger<BulkLogOperationProcessor> _logger;
public BulkLogOperationProcessor(
IMemoryCache cache,
ILogsStoreService logStoreService,
IHubContext<LogHub> hub,
ILogger<BulkLogOperationProcessor> logger)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_logStoreService = logStoreService ?? throw new ArgumentNullException(nameof(logStoreService));
_hubAccess = hub ?? throw new ArgumentNullException(nameof(hub));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<BulkLogOperationResult> Handle(BulkLogOperationQuery request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
MapCacheItem cacheMap;
string buildedCacheKey;
if (!string.IsNullOrEmpty(request.Request.CacheKey))
{
buildedCacheKey = request.Request.CacheKey;
// we should have cache for this request
if (!_cache.TryGetValue<MapCacheItem>(buildedCacheKey, out var gettedCacheMap))
throw new Exception($"Can't find cacheKey={buildedCacheKey} in memory cache");
cacheMap = gettedCacheMap;
}
else
{
// create new cache map
cacheMap = new MapCacheItem();
buildedCacheKey = string.Format(CACHE_LOCAL_SCOPE_MAP, cacheMap.CacheKey);
using (var cacheEntry = _cache.CreateEntry(buildedCacheKey))
{
cacheEntry.SetValue(cacheMap);
cacheEntry
.SetSlidingExpiration(TimeSpan.FromMinutes(15))
.SetAbsoluteExpiration(TimeSpan.FromHours(2));
cacheEntry.RegisterPostEvictionCallback(OnCacheEntryChanges);
}
_logger.LogInformation($"[{DateTime.Now:dd.MM.yyyy HH:mm}] Start new BuldOperation Messages.Count={request.Request.Messages.Count} SetCache.Key={buildedCacheKey}");
}
var scopeMapVal = cacheMap.CalculatedIds;
var needToFinalize = false;
for (var i = 0; i < request.Request.Messages.Count; i++)
{
var messageToProceed = request.Request.Messages[i];
switch (messageToProceed.OperationType)
{
case Server.BulkOperationType.CreateInitialScope:
if (!cacheMap.ScopeIdsMap.IsEmpty)
throw new Exception($"Can't create initial scope because it already should be existing!");
var targetProject = request.Request.Parameters[nameof(LogScopeRecord.Project)];
var targetEnv = request.Request.Parameters[nameof(LogScopeRecord.Environment)];
_logger.LogInformation($"[{DateTime.Now:dd.MM.yyyy HH:mm}] {nameof(Server.BulkOperationType)} {nameof(Server.BulkOperationType.CreateInitialScope)} proj={targetProject} env={targetEnv} Cache.Key={buildedCacheKey}");
var initialScope = await _logStoreService.CreateRootScope(targetProject, targetEnv, messageToProceed.CreatedAt.ToDateTime());
if (!cacheMap.ScopeIdsMap.TryAdd(++scopeMapVal, initialScope.Id))
throw new Exception($"Failed at setting initial scope id for {buildedCacheKey}");
cacheMap.RootScopeId = initialScope.Id;
await _hubAccess
.Clients
.Group(LogHub.ALL_LOGS_GROUP)
.SendAsync(NewScopeEvent.BROADCAST_NEW_SCOPE_MESSAGE, new NewScopeEvent(initialScope), cancellationToken);
break;
case Server.BulkOperationType.CreateScope:
var innerScope = await _logStoreService.CreateScope(
cacheMap.ScopeIdsMap[messageToProceed.RootScopeId],
cacheMap.ScopeIdsMap[messageToProceed.ScopeOwnerId],
messageToProceed.CreatedAt.ToDateTime());
if (!cacheMap.ScopeIdsMap.TryAdd(++scopeMapVal, innerScope.Id))
throw new Exception($"Failed at setting scope id ({scopeMapVal}) for {buildedCacheKey}");
await _hubAccess
.Clients
.Group(LogHub.ALL_LOGS_GROUP)
.SendAsync(NewScopeEvent.BROADCAST_NEW_SCOPE_MESSAGE, new NewScopeEvent(innerScope), cancellationToken);
break;
case Server.BulkOperationType.LogMessage:
case Server.BulkOperationType.LogException:
var newRcord = new LogRecord()
{
CreatedAt = messageToProceed.CreatedAt.ToDateTime(),
LogLevel = (LogLevelEnum)(int)messageToProceed.Level,
Message = messageToProceed.LogMessage.Truncate(255),
StackTrace = messageToProceed.ExceptionStackTrace.Truncate(1024),
ErrorTitle = messageToProceed.ExceptionMessage.Truncate(255),
OwnerScopeId = cacheMap.ScopeIdsMap[messageToProceed.ScopeOwnerId],
RootScopeId = cacheMap.ScopeIdsMap[messageToProceed.RootScopeId],
};
await _logStoreService.InsertLogRecordAsync(newRcord);
await _hubAccess
.Clients
.Group(LogHub.ALL_LOGS_GROUP)
.SendAsync(NewLogInScopeEvent.BROADCAST_LOG_MESSAGE_NAME, new NewLogInScopeEvent(newRcord), cancellationToken);
break;
case Server.BulkOperationType.FinalRequest:
needToFinalize = true;
break;
}
}
cacheMap.CalculatedIds = scopeMapVal;
if (needToFinalize)
{
_cache.Remove(buildedCacheKey);
_logger.LogInformation($"[{DateTime.Now:dd.MM.yyyy HH:mm}] {nameof(Server.BulkOperationType)} {nameof(Server.BulkOperationType.FinalRequest)} Cache.Key={buildedCacheKey}");
}
return new BulkLogOperationResult()
{
CacheKey = buildedCacheKey
};
}
private void OnCacheEntryChanges(object key, object value, EvictionReason reason, object state)
{
if(reason == EvictionReason.Expired
|| reason == EvictionReason.Removed
|| reason == EvictionReason.TokenExpired)
{
_logger.LogInformation($"{nameof(Server.BulkOperationType)} {nameof(OnCacheEntryChanges)} key={key} reason={reason}");
}
}
public class MapCacheItem
{
public readonly ConcurrentDictionary<long, long> ScopeIdsMap;
public readonly string CacheKey;
public int CalculatedIds { get; set; }
public long RootScopeId;
public MapCacheItem()
{
CalculatedIds = 0;
CacheKey = Guid.NewGuid().ToString();
ScopeIdsMap = new ConcurrentDictionary<long, long>();
}
}
}
}
| 45.248677 | 239 | 0.5884 | [
"MIT"
] | kitakun/DeafTelephone | DeafTelephone.Web/Controllers/LogiServer/BulkLogOperation/BulkLogOperationProcessor.cs | 8,554 | C# |
using AurelienRibon.Ui.SyntaxHighlightBox;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using System.Xml.Linq;
namespace Sigged.CsC.NetFx.Wpf
{
/// <summary>
/// An IHighlighter built from an Xml syntax file
/// To support SyntaxHightlightBox
/// </summary>
internal class XmlHighlighter : IHighlighter
{
private List<HighlightWordsRule> wordsRules;
private List<HighlightLineRule> lineRules;
private List<AdvancedHighlightRule> regexRules;
public XmlHighlighter(XElement root)
{
wordsRules = new List<HighlightWordsRule>();
lineRules = new List<HighlightLineRule>();
regexRules = new List<AdvancedHighlightRule>();
foreach (XElement elem in root.Elements())
{
switch (elem.Name.ToString())
{
case "HighlightWordsRule": wordsRules.Add(new HighlightWordsRule(elem)); break;
case "HighlightLineRule": lineRules.Add(new HighlightLineRule(elem)); break;
case "AdvancedHighlightRule": regexRules.Add(new AdvancedHighlightRule(elem)); break;
}
}
}
public int Highlight(FormattedText text, int previousBlockCode)
{
//
// WORDS RULES
//
Regex wordsRgx = new Regex("[a-zA-Z_][a-zA-Z0-9_]*");
foreach (Match m in wordsRgx.Matches(text.Text))
{
foreach (HighlightWordsRule rule in wordsRules)
{
foreach (string word in rule.Words)
{
if (rule.Options.IgnoreCase)
{
if (m.Value.Equals(word, StringComparison.InvariantCultureIgnoreCase))
{
text.SetForegroundBrush(rule.Options.Foreground, m.Index, m.Length);
text.SetFontWeight(rule.Options.FontWeight, m.Index, m.Length);
text.SetFontStyle(rule.Options.FontStyle, m.Index, m.Length);
}
}
else
{
if (m.Value == word)
{
text.SetForegroundBrush(rule.Options.Foreground, m.Index, m.Length);
text.SetFontWeight(rule.Options.FontWeight, m.Index, m.Length);
text.SetFontStyle(rule.Options.FontStyle, m.Index, m.Length);
}
}
}
}
}
//
// REGEX RULES
//
foreach (AdvancedHighlightRule rule in regexRules)
{
Regex regexRgx = new Regex(rule.Expression);
foreach (Match m in regexRgx.Matches(text.Text))
{
text.SetForegroundBrush(rule.Options.Foreground, m.Index, m.Length);
text.SetFontWeight(rule.Options.FontWeight, m.Index, m.Length);
text.SetFontStyle(rule.Options.FontStyle, m.Index, m.Length);
}
}
//
// LINES RULES
//
foreach (HighlightLineRule rule in lineRules)
{
Regex lineRgx = new Regex(Regex.Escape(rule.LineStart) + ".*");
foreach (Match m in lineRgx.Matches(text.Text))
{
text.SetForegroundBrush(rule.Options.Foreground, m.Index, m.Length);
text.SetFontWeight(rule.Options.FontWeight, m.Index, m.Length);
text.SetFontStyle(rule.Options.FontStyle, m.Index, m.Length);
}
}
return -1;
}
}
/// <summary>
/// A set of words and their RuleOptions.
/// </summary>
internal class HighlightWordsRule
{
public List<string> Words { get; private set; }
public RuleOptions Options { get; private set; }
public HighlightWordsRule(XElement rule)
{
Words = new List<string>();
Options = new RuleOptions(rule);
string wordsStr = rule.Element("Words").Value;
string[] words = Regex.Split(wordsStr, "\\s+");
foreach (string word in words)
if (!string.IsNullOrWhiteSpace(word))
Words.Add(word.Trim());
}
}
/// <summary>
/// A line start definition and its RuleOptions.
/// </summary>
internal class HighlightLineRule
{
public string LineStart { get; private set; }
public RuleOptions Options { get; private set; }
public HighlightLineRule(XElement rule)
{
LineStart = rule.Element("LineStart").Value.Trim();
Options = new RuleOptions(rule);
}
}
/// <summary>
/// A regex and its RuleOptions.
/// </summary>
internal class AdvancedHighlightRule
{
public string Expression { get; private set; }
public RuleOptions Options { get; private set; }
public AdvancedHighlightRule(XElement rule)
{
Expression = rule.Element("Expression").Value.Trim();
Options = new RuleOptions(rule);
}
}
/// <summary>
/// A set of options liked to each rule.
/// </summary>
internal class RuleOptions
{
public bool IgnoreCase { get; private set; }
public Brush Foreground { get; private set; }
public FontWeight FontWeight { get; private set; }
public FontStyle FontStyle { get; private set; }
public RuleOptions(XElement rule)
{
string ignoreCaseStr = rule.Element("IgnoreCase").Value.Trim();
string foregroundStr = rule.Element("Foreground").Value.Trim();
string fontWeightStr = rule.Element("FontWeight").Value.Trim();
string fontStyleStr = rule.Element("FontStyle").Value.Trim();
IgnoreCase = bool.Parse(ignoreCaseStr);
Foreground = (Brush)new BrushConverter().ConvertFrom(foregroundStr);
FontWeight = (FontWeight)new FontWeightConverter().ConvertFrom(fontWeightStr);
FontStyle = (FontStyle)new FontStyleConverter().ConvertFrom(fontStyleStr);
}
}
}
| 35.432432 | 105 | 0.537147 | [
"MIT"
] | sigged/research-compiling | Compile.and.Execute/src/Sigged.CsC.NetFx.Wpf/XmlHighlighter.cs | 6,557 | C# |
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (C) Lluis Sanchez Gual, 2004
//
#if !MONOTOUCH
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace Mono.CodeGeneration
{
public class CodeAssignment: CodeExpression
{
new CodeValueReference var;
CodeExpression exp;
public CodeAssignment (CodeValueReference var, CodeExpression exp)
{
if (var == null)
throw new ArgumentNullException ("var");
if (exp == null)
throw new ArgumentNullException ("exp");
this.exp = exp;
this.var = var;
}
public override void Generate (ILGenerator gen)
{
var.GenerateSet (gen, exp);
exp.Generate (gen);
}
public override void GenerateAsStatement (ILGenerator gen)
{
CodeExpression val = exp;
if (var.GetResultType () == typeof(object) && exp.GetResultType ().IsValueType)
var.GenerateSet (gen, new CodeCast (typeof(object), exp));
else
var.GenerateSet (gen, exp);
}
public override void PrintCode (CodeWriter cp)
{
var.PrintCode (cp);
cp.Write (" = ");
exp.PrintCode (cp);
}
public override Type GetResultType ()
{
return var.GetResultType ();
}
}
}
#endif
| 29.573333 | 82 | 0.717764 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/System.ServiceModel/Mono.CodeGeneration/CodeAssignment.cs | 2,218 | C# |
namespace Exemplum.Application.Todo.Commands;
using Common.Exceptions;
using Common.Security;
using Domain.Todo;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Persistence;
[Authorize(Policy = Security.Policy.TodoWriteAccess)]
public record MarkTodoCompleteCommand(int ListId, int TodoId) : IRequest
{
}
public class MarkTodoCompleteCommandValidator : AbstractValidator<MarkTodoCompleteCommand>
{
public MarkTodoCompleteCommandValidator()
{
RuleFor(x => x.ListId).GreaterThan(0);
RuleFor(x => x.TodoId).GreaterThan(0);
}
}
public class MarkTodoCompleteHandler : IRequestHandler<MarkTodoCompleteCommand>
{
private readonly IApplicationDbContext _context;
public MarkTodoCompleteHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(MarkTodoCompleteCommand request, CancellationToken cancellationToken)
{
var todo = await _context.TodoItems
.SingleOrDefaultAsync(x => x.ListId == request.ListId &&
x.Id == request.TodoId, cancellationToken);
if (todo == null)
{
throw new NotFoundException(nameof(TodoItem), request);
}
if (todo.Done)
{
todo.MarkAsIncomplete();
}
else
{
todo.MarkAsDone();
}
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
} | 24.983333 | 104 | 0.668446 | [
"MIT"
] | ForrestTech/Exemplum | src/Application/Todo/Commands/MarkTodoCompleteCommand.cs | 1,501 | C# |
using Funkin.NET.Graphics.Sprites;
using Funkin.NET.Graphics.Utilities;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osuTK;
namespace Funkin.NET.Graphics.Cursor
{
public class BasicTooltip : TooltipContainer.Tooltip
{
public Box Background;
public BasicSpriteText Text;
public bool InstantMovement = true;
public BasicTooltip()
{
AutoSizeEasing = Easing.OutQuint;
CornerRadius = 5;
Masking = true;
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Colour4.Black.Opacity(40),
Radius = 5
};
Children = new Drawable[]
{
Background = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.9f,
Colour = Color4Extensions.FromHex("333")
},
Text = new BasicSpriteText
{
Padding = new MarginPadding(5f),
Font = FunkinFont.GetFont(weight: FunkinFont.FontWeight.Regular)
}
};
}
public override void SetContent(LocalisableString content)
{
if (Text.Text == content)
return;
Text.Text = content;
if (IsPresent)
{
AutoSizeDuration = 250;
Background.FlashColour(ColorUtils.Gray(0.4f), 1000D, Easing.OutQuint);
}
else
AutoSizeDuration = 0;
}
protected override void PopIn()
{
InstantMovement |= !IsPresent;
this.FadeIn(500D, Easing.OutQuint);
}
protected override void PopOut() => this.Delay(150D).FadeOut(500D, Easing.OutQuint);
public override void Move(Vector2 pos)
{
if (InstantMovement)
{
Position = pos;
InstantMovement = false;
}
else
{
this.MoveTo(pos, 200D, Easing.OutQuint);
}
}
}
} | 27.55814 | 92 | 0.518565 | [
"MIT"
] | GetFunkin/Funkin.NET | Funkin.NET/Graphics/Cursor/BasicTooltip.cs | 2,372 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Gribble.Mapping;
using Gribble.Model;
using Gribble.TransactSql;
using NUnit.Framework;
using Should;
namespace Tests.TransactSql
{
[TestFixture]
public class DeleteWriterTests
{
public class Entity
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
public DateTime? Created { get; set; }
public int Age { get; set; }
public float Price { get; set; }
public double Distance { get; set; }
public byte Flag { get; set; }
public bool Active { get; set; }
public decimal Length { get; set; }
public long Miles { get; set; }
public IDictionary<string, object> Values {get; set;}
}
public class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
Id(x => x.Id).Column("id");
Map(x => x.Name).Column("name");
Map(x => x.Birthdate).Column("birthdate");
Map(x => x.Created).Column("created");
Map(x => x.Age).Column("age");
Map(x => x.Price).Column("price");
Map(x => x.Distance).Column("distance");
Map(x => x.Flag).Column("flag");
Map(x => x.Active).Column("active");
Map(x => x.Length).Column("length");
Map(x => x.Miles).Column("miles");
Map(x => x.Values).Dynamic();
}
}
private static readonly EntityMapping Map = new EntityMapping(new EntityMap());
public const string TableName = "some_table_in_the_db";
[Test]
public void Delete_Single_Test()
{
var delete = new Delete(TableName, Operator.Create.FieldEqualsConstant("Id", Guid.Empty), false);
var statement = DeleteWriter<Entity>.CreateStatement(delete, Map);
statement.Result.ShouldEqual(Statement.ResultType.None);
statement.Parameters.Count.ShouldEqual(1);
statement.Parameters.First().Value.ShouldEqual(Guid.Empty);
statement.Text.ShouldEqual(string.Format("DELETE TOP (1) FROM [{0}] WHERE ([id] = @{1})", TableName,
statement.Parameters.First().Key));
}
[Test]
public void Delete_Multi_Test()
{
var delete = new Delete(TableName, Operator.Create.FieldAndConstant("Age", Operator.OperatorType.GreaterThan, 20), true);
var statement = DeleteWriter<Entity>.CreateStatement(delete, Map);
statement.Result.ShouldEqual(Statement.ResultType.None);
statement.Parameters.Count.ShouldEqual(1);
statement.Parameters.First().Value.ShouldEqual(20);
statement.Text.ShouldEqual(string.Format("DELETE FROM [{0}] WHERE ([age] > @{1})", TableName,
statement.Parameters.First().Key));
}
[Test]
public void should_render_multi_delete_by_query_sql()
{
var delete = new Delete(TableName, new Select {
From = { Type = Data.DataType.Table, Table = new Table { Name = TableName }},
Where = Operator.Create.FieldAndConstant("Age", Operator.OperatorType.GreaterThan, 20)}, true);
var statement = DeleteWriter<Entity>.CreateStatement(delete, Map);
statement.Result.ShouldEqual(Statement.ResultType.None);
statement.Parameters.Count.ShouldEqual(1);
statement.Parameters.First().Value.ShouldEqual(20);
statement.Text.ShouldEqual(string.Format("DELETE FROM [{0}] WHERE EXISTS (SELECT [id] FROM (SELECT * FROM [{0}] {1} WHERE ([age] > @{2})) AS [__SubQuery__] WHERE [__SubQuery__].[id] = [{0}].[id])",
TableName, delete.Select.From.Alias, statement.Parameters.First().Key));
}
}
}
| 44.096774 | 211 | 0.561814 | [
"MIT"
] | mikeobrien/Gribble | src/Tests/TransactSql/DeleteWriterTests.cs | 4,103 | C# |
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace WebAppConfig
{
public class AlbumsConfigurationSetup : IPostConfigureOptions<AlbumsConfiguration>
{
private static SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
private static Dictionary<string, Func<Album, bool>> _visibleAlbumFilters = new Dictionary<string, Func<Album, bool>>();
private async Task<Func<Album, bool>> GetVisibleAlbumsFilter(string filter)
{
if (_visibleAlbumFilters.ContainsKey(filter))
{
return _visibleAlbumFilters[filter];
}
await _lock.WaitAsync();
try
{
var options = ScriptOptions.Default.AddReferences(typeof(Album).Assembly);
var compiledFilter = await CSharpScript.EvaluateAsync<Func<Album, bool>>(filter, options);
_visibleAlbumFilters[filter] = compiledFilter;
return compiledFilter;
}
finally
{
_lock.Release();
}
}
public void PostConfigure(string name, AlbumsConfiguration options)
{
options.VisibleAlbumsFilterLambda = GetVisibleAlbumsFilter(options.VisibleAlbumsFilter).GetAwaiter().GetResult();
}
}
}
| 34.465116 | 128 | 0.647099 | [
"MIT"
] | filipw/update-conf-2018-demos | scripting/WebAppConfig/WebAppConfig/AlbumsConfigurationSetup.cs | 1,484 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the servicecatalog-2015-12-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ServiceCatalog.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ServiceCatalog.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeServiceAction operation
/// </summary>
public class DescribeServiceActionResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeServiceActionResponse response = new DescribeServiceActionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("ServiceActionDetail", targetDepth))
{
var unmarshaller = ServiceActionDetailUnmarshaller.Instance;
response.ServiceActionDetail = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonServiceCatalogException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribeServiceActionResponseUnmarshaller _instance = new DescribeServiceActionResponseUnmarshaller();
internal static DescribeServiceActionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeServiceActionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.636364 | 197 | 0.659903 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ServiceCatalog/Generated/Model/Internal/MarshallTransformations/DescribeServiceActionResponseUnmarshaller.cs | 4,140 | C# |
using Newtonsoft.Json;
using System;
namespace GitHubNotifier.DataTypes
{
[Serializable]
[JsonObject]
public class GithubRepo
{
[JsonProperty("id")] public int Id { get; set; }
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("full_name")] public string FullName { get; set; }
[JsonProperty("fork")] public bool Fork { get; set; }
[JsonProperty("private")] public bool Private { get; set; }
[JsonProperty("description")] public string Description { get; set; }
[JsonProperty("stargazers_count")] public int Stargazers { get; set; }
[JsonProperty("watchers_count")] public int Watchers { get; set; }
[JsonProperty("subscribers_count")] public int Subscribers { get; set; }
[JsonProperty("forks_count")] public int Forks { get; set; }
[JsonProperty("open_issues_count")] public int OpenIssues { get; set; }
}
}
| 40.869565 | 80 | 0.643617 | [
"MIT"
] | LiorBanai/GitHub-Notifier | GitHubNotifier/DataTypes/GithubRepo.cs | 942 | 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.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using Newtonsoft.Json;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Sarif.UnitTests.Core
{
public class SarifLogTests
{
private readonly ITestOutputHelper output;
public SarifLogTests(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void SarifLog_DoesNotSerializeNonNullEmptyCollections()
{
var run = new Run
{
Graphs = new Graph[] { },
Artifacts = new Artifact[] { },
Invocations = new Invocation[] { },
LogicalLocations = new LogicalLocation[] { }
};
run.Graphs.Should().NotBeNull();
run.Artifacts.Should().NotBeNull();
run.Invocations.Should().NotBeNull();
run.LogicalLocations.Should().NotBeNull();
run = SerializeAndDeserialize(run);
// Certain non-null but entirely empty collections should not
// be persisted during serialization. As a result, these properties
// should be null after round-tripping, reflecting the actual
// (i.e., entirely absent) representation on disk when saved.
run.Graphs.Should().BeNull();
run.Artifacts.Should().BeNull();
run.Invocations.Should().BeNull();
run.LogicalLocations.Should().BeNull();
// If arrays are non-empty but only contain object instances
// that consist of nothing but default values, these also
// should not be persisted to disk
run.Graphs = new Graph[] { new Graph() };
run.Artifacts = new Artifact[] { new Artifact() };
run.LogicalLocations = new LogicalLocation[] { new LogicalLocation() };
// Invocations are special, they have a required property,
// ExecutionSuccessful. This means even an entirely default instance
// should be retained when serialized.
run.Invocations = new Invocation[] { new Invocation() };
run = SerializeAndDeserialize(run);
run.Graphs.Should().BeNull();
run.Artifacts.Should().BeNull();
run.LogicalLocations.Should().BeNull();
run.Invocations.Should().NotBeNull();
}
[Fact]
public void SarifLog_ApplyPoliciesShouldNotThrowWhenRunsDoesNotExist()
{
var sarifLog = new SarifLog();
Action action = () => sarifLog.ApplyPolicies();
action.Should().NotThrow();
}
[Fact]
public void SarifLog_SplitPerRun()
{
var random = new Random();
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
sarifLog.Split(SplittingStrategy.PerRun).Should().HaveCount(1);
sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 3);
sarifLog.Split(SplittingStrategy.PerRun).Should().HaveCount(3);
}
[Fact]
public void SarifLog_SplitPerResult()
{
var random = new Random();
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, runCount: 1, resultCount: 5);
int countOfDistinctRules = sarifLog.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
IList<SarifLog> logs = sarifLog.Split(SplittingStrategy.PerResult).ToList();
logs.Count.Should().Be(countOfDistinctRules);
foreach (SarifLog log in logs)
{
// optimized partitioned log should only include rules referenced by its results
log.Runs.Count.Should().Be(1);
int ruleCount = log.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
ruleCount.Should().Be(log.Runs[0].Tool.Driver.Rules.Count);
}
}
[Fact]
public void SarifLog_SplitPerTarget()
{
var random = new Random();
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
IList<SarifLog> logs = sarifLog.Split(SplittingStrategy.PerRunPerTarget).ToList();
logs.Count.Should().Be(
sarifLog.Runs[0].Results.Select(r => r.Locations[0].PhysicalLocation.ArtifactLocation.Uri).Distinct().Count());
foreach (SarifLog log in logs)
{
// optimized partitioned log should only include rules referenced by its results
log.Runs.Count.Should().Be(1);
int ruleCount = log.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
ruleCount.Should().Be(log.Runs[0].Tool.Driver.Rules.Count);
// verify result's RuleIndex reference to right rule
foreach (Result result in log.Runs[0].Results)
{
result.RuleId.Should().Be(
log.Runs[0].Tool.Driver.Rules.ElementAt(result.RuleIndex).Id);
}
}
}
[Fact]
public void SarifLog_SplitPerTarget_WithEmptyLocations()
{
var random = new Random();
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
// set random result's location to empty
IList<Result> results = sarifLog.Runs.First().Results;
Result randomResult = results.ElementAt(random.Next(results.Count));
randomResult.Locations = null;
randomResult = results.ElementAt(random.Next(results.Count));
if (randomResult.Locations?.FirstOrDefault()?.PhysicalLocation != null)
{
randomResult.Locations.FirstOrDefault().PhysicalLocation = null;
}
randomResult = results.ElementAt(random.Next(results.Count));
if (randomResult.Locations?.FirstOrDefault()?.PhysicalLocation?.ArtifactLocation != null)
{
randomResult.Locations.FirstOrDefault().PhysicalLocation.ArtifactLocation = null;
}
randomResult = results.ElementAt(random.Next(results.Count));
if (randomResult.Locations?.FirstOrDefault()?.PhysicalLocation?.ArtifactLocation?.Uri != null)
{
randomResult.Locations.FirstOrDefault().PhysicalLocation.ArtifactLocation.Uri = null;
}
IList<SarifLog> logs = sarifLog.Split(SplittingStrategy.PerRunPerTarget).ToList();
logs.Count.Should().Be(
sarifLog.Runs[0].Results.Select(r => r.Locations?.FirstOrDefault()?.PhysicalLocation?.ArtifactLocation?.Uri).Distinct().Count());
foreach (SarifLog log in logs)
{
// optimized partitioned log should only include rules referenced by its results
log.Runs.Count.Should().Be(1);
int ruleCount = log.Runs[0].Results.Select(r => r.RuleId).Distinct().Count();
ruleCount.Should().Be(log.Runs[0].Tool.Driver.Rules.Count);
// verify result's RuleIndex reference to right rule
foreach (Result result in log.Runs[0].Results)
{
result.RuleId.Should().Be(
log.Runs[0].Tool.Driver.Rules.ElementAt(result.RuleIndex).Id);
}
}
}
[Fact]
public void SarifLog_LoadDeferred()
{
byte[] data = new byte[4];
RandomNumberGenerator.Fill(data);
int seed = BitConverter.ToInt32(data);
var random = new Random(seed);
this.output.WriteLine($"The seed passed to the Random instance was : {seed}.");
SarifLog sarifLog = RandomSarifLogGenerator.GenerateSarifLogWithRuns(random, 1);
string sarifLogText = JsonConvert.SerializeObject(sarifLog);
byte[] byteArray = Encoding.ASCII.GetBytes(sarifLogText);
using var stream = new MemoryStream(byteArray);
var newSarifLog = SarifLog.Load(stream, deferred: true);
newSarifLog.Runs[0].Tool.Driver.Name.Should().Be(sarifLog.Runs[0].Tool.Driver.Name);
newSarifLog.Runs[0].Results.Count.Should().Be(sarifLog.Runs[0].Results.Count);
}
[Fact]
public async Task SarifLog_PostStream_WithInvalidParameters_ShouldThrowArgumentNullException()
{
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(postUri: null,
new MemoryStream(),
new HttpClient());
});
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(new Uri("https://github.com/microsoft/sarif-sdk"),
null,
new HttpClient());
});
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(new Uri("https://github.com/microsoft/sarif-sdk"),
new MemoryStream(),
null);
});
}
[Fact]
public async Task SarifLog_PostFile_WithInvalidParameters_ShouldThrowException()
{
string filePath = string.Empty;
var fileSystem = new Mock<IFileSystem>();
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await SarifLog.Post(postUri: null,
filePath,
fileSystem.Object,
httpClient: null);
});
filePath = "SomeFile.txt";
fileSystem
.Setup(f => f.FileExists(It.IsAny<string>()))
.Returns(false);
await Assert.ThrowsAsync<ArgumentException>(async () =>
{
await SarifLog.Post(postUri: null,
filePath,
fileSystem.Object,
httpClient: null);
});
}
[Fact]
public async Task SarifLog_Post_WithValidParameters_ShouldNotThrownAnExceptionWhenRequestIsValid()
{
var postUri = new Uri("https://github.com/microsoft/sarif-sdk");
var sarifLog = new SarifLog();
var httpMock = new HttpMockHelper();
var memoryStream = new MemoryStream();
sarifLog.Save(memoryStream);
httpMock.Mock(
new HttpRequestMessage(HttpMethod.Post, postUri) { Content = new StreamContent(memoryStream) },
HttpMockHelper.BadRequestResponse);
await Assert.ThrowsAsync<HttpRequestException>(async () =>
{
await SarifLog.Post(postUri,
memoryStream,
new HttpClient(httpMock));
});
httpMock.Clear();
memoryStream = new MemoryStream();
sarifLog.Save(memoryStream);
httpMock.Mock(
new HttpRequestMessage(HttpMethod.Post, postUri) { Content = new StreamContent(memoryStream) },
HttpMockHelper.OKResponse);
try
{
await SarifLog.Post(postUri,
memoryStream,
new HttpClient(httpMock));
}
catch (Exception ex)
{
Assert.True(false, "Expected no exception, but got: " + ex.Message);
}
httpMock.Clear();
string filePath = "SomeFile.txt";
var fileSystem = new Mock<IFileSystem>();
memoryStream = new MemoryStream();
sarifLog.Save(memoryStream);
fileSystem
.Setup(f => f.FileExists(It.IsAny<string>()))
.Returns(true);
fileSystem
.Setup(f => f.FileOpenRead(It.IsAny<string>()))
.Returns(memoryStream);
httpMock.Mock(
new HttpRequestMessage(HttpMethod.Post, postUri) { Content = new StreamContent(memoryStream) },
HttpMockHelper.OKResponse);
try
{
await SarifLog.Post(postUri,
filePath,
fileSystem.Object,
new HttpClient(httpMock));
}
catch (Exception ex)
{
Assert.True(false, "Expected no exception, but got: " + ex.Message);
}
httpMock.Clear();
}
private Run SerializeAndDeserialize(Run run)
{
return JsonConvert.DeserializeObject<Run>(JsonConvert.SerializeObject(run));
}
}
}
| 39.946429 | 145 | 0.557816 | [
"MIT"
] | Yiwei-Ding/sarif-sdk | src/Test.UnitTests.Sarif/Core/SarifLogTests.cs | 13,424 | C# |
// Copyright (c) 2018 Daniel A Hill. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using ApiActions.Authorization;
namespace ApiActions.Initialization
{
public class GlobalAuthFilterApplicationFactoryTypeWrapper : GlobalApplicationFactoryTypeWrapper<IAuthFilter>,
IGlobalAuthFilterApplicationFactory
{
public GlobalAuthFilterApplicationFactoryTypeWrapper(Type type, params IActionTypeFilter[] filters) : base(type,
filters)
{
}
}
} | 37.142857 | 120 | 0.741346 | [
"Apache-2.0"
] | DanielAHill/ApiActions | src/ApiActions/Initialization/GlobalAuthFilterApplicationFactoryTypeWrapper.cs | 1,042 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TicketingSystem.Server.Areas.HelpPage.ModelDescriptions;
using TicketingSystem.Server.Areas.HelpPage.Models;
namespace TicketingSystem.Server.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| 51.521368 | 196 | 0.623341 | [
"MIT"
] | d-georgiev-91/Ticketing-System | TicketingSystem.Server/Areas/HelpPage/HelpPageConfigurationExtensions.cs | 24,112 | C# |
using System;
namespace Gwen.Control
{
public enum BorderType
{
ToolTip,
StatusBar,
MenuStrip,
Selection,
PanelNormal,
PanelBright,
PanelDark,
PanelHighlight,
ListBox,
TreeControl,
CategoryList
}
/// <summary>
/// A Border Control
/// </summary>
[Xml.XmlControl]
public class Border : ControlBase
{
private BorderType m_BorderType;
[Xml.XmlProperty]
public BorderType BorderType { get { return m_BorderType; } set { if (m_BorderType == value) return; m_BorderType = value; } }
public Border(ControlBase parent)
: base(parent)
{
m_BorderType = BorderType.PanelNormal;
}
protected override void Render(Skin.SkinBase skin)
{
skin.DrawBorder(this, m_BorderType);
}
}
}
| 16.906977 | 128 | 0.700138 | [
"MIT"
] | phinoox/Gwen.CS | GwenNet/Control/Border.cs | 729 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NiceHashBot")]
[assembly: AssemblyDescription("NiceHash Bot for automatic managing of orders for NiceHash")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NiceHashBot")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("18c4deca-0541-4bc1-83a0-4cf6e0e34a2f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.4")]
[assembly: AssemblyFileVersion("1.0.3.4")]
| 39.27027 | 93 | 0.749484 | [
"MIT"
] | cryptopool-builders/NiceHashBot | src/NiceHashBot/Properties/AssemblyInfo.cs | 1,456 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Pinpoint.Model
{
/// <summary>
/// Container for the parameters to the GetExportJobs operation.
/// Retrieves information about the status and settings of all the export jobs for an
/// application.
/// </summary>
public partial class GetExportJobsRequest : AmazonPinpointRequest
{
private string _applicationId;
private string _pageSize;
private string _token;
/// <summary>
/// Gets and sets the property ApplicationId.
/// <para>
/// The unique identifier for the application. This identifier is displayed as the <b>Project
/// ID</b> on the Amazon Pinpoint console.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ApplicationId
{
get { return this._applicationId; }
set { this._applicationId = value; }
}
// Check to see if ApplicationId property is set
internal bool IsSetApplicationId()
{
return this._applicationId != null;
}
/// <summary>
/// Gets and sets the property PageSize.
/// <para>
/// The maximum number of items to include in each page of a paginated response. This
/// parameter is currently not supported for application, campaign, and journey metrics.
/// </para>
/// </summary>
public string PageSize
{
get { return this._pageSize; }
set { this._pageSize = value; }
}
// Check to see if PageSize property is set
internal bool IsSetPageSize()
{
return this._pageSize != null;
}
/// <summary>
/// Gets and sets the property Token.
/// <para>
/// The NextToken string that specifies which page of results to return in a paginated
/// response.
/// </para>
/// </summary>
public string Token
{
get { return this._token; }
set { this._token = value; }
}
// Check to see if Token property is set
internal bool IsSetToken()
{
return this._token != null;
}
}
} | 31.06 | 106 | 0.609466 | [
"Apache-2.0"
] | TallyUpTeam/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/GetExportJobsRequest.cs | 3,106 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PhotoFrameServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PhotoFrameServer")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ecd980d3-4351-4b01-b94c-337d612994b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.945946 | 85 | 0.727967 | [
"MIT"
] | bp2008/PhotoFrameServer | PhotoFrameServer/PhotoFrameServer/Properties/AssemblyInfo.cs | 1,444 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Cactus.Fileserver.Core.Model;
namespace Cactus.Fileserver.Core
{
public interface IFileStorageService
{
/// <summary>
/// Get file content by URI
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
Task<Stream> Get(Uri uri);
/// <summary>
/// Store a new file from stream
/// </summary>
/// <param name="stream"></param>
/// <param name="fileInfo"></param>
/// <returns></returns>
Task<MetaInfo> Create(Stream stream, IFileInfo fileInfo);
/// <summary>
/// Delete file by URI
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
Task Delete(Uri uri);
/// <summary>
/// Get file information
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
IFileInfo GetInfo(Uri uri);
}
} | 27.25641 | 66 | 0.494826 | [
"MIT"
] | SergeyGil/Cactus.Fileserver | Cactus.Fileserver.Core/IFileStorageService.cs | 1,063 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Firebend.AutoCrud.Core.Implementations.Defaults;
using Firebend.AutoCrud.Core.Interfaces.Models;
using Firebend.AutoCrud.Core.Interfaces.Services.DomainEvents;
using Firebend.AutoCrud.Core.Models.DomainEvents;
using Firebend.AutoCrud.EntityFramework.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace Firebend.AutoCrud.EntityFramework.Abstractions.Client
{
public abstract class EntityFrameworkCreateClient<TKey, TEntity> : AbstractDbContextRepo<TKey, TEntity>, IEntityFrameworkCreateClient<TKey, TEntity>
where TKey : struct
where TEntity : class, IEntity<TKey>, new()
{
private readonly IDomainEventContextProvider _domainEventContextProvider;
private readonly IEntityFrameworkDbUpdateExceptionHandler<TKey, TEntity> _exceptionHandler;
private readonly IEntityDomainEventPublisher _domainEventPublisher;
protected EntityFrameworkCreateClient(IDbContextProvider<TKey, TEntity> provider,
IEntityDomainEventPublisher domainEventPublisher,
IDomainEventContextProvider domainEventContextProvider,
IEntityFrameworkDbUpdateExceptionHandler<TKey, TEntity> exceptionHandler) : base(provider)
{
_domainEventPublisher = domainEventPublisher;
_domainEventContextProvider = domainEventContextProvider;
_exceptionHandler = exceptionHandler;
}
protected virtual async Task<TEntity> AddInternalAsync(TEntity entity, IEntityTransaction transaction, CancellationToken cancellationToken)
{
var context = await GetDbContextAsync(transaction, cancellationToken).ConfigureAwait(false);
var set = GetDbSet(context);
if (entity is IModifiedEntity modified)
{
var now = DateTimeOffset.Now;
modified.CreatedDate = now;
modified.ModifiedDate = now;
}
var entry = await set
.AddAsync(entity, cancellationToken)
.ConfigureAwait(false);
var savedEntity = entry.Entity;
try
{
await context
.SaveChangesAsync(cancellationToken)
.ConfigureAwait(false);
}
catch (DbUpdateException ex)
{
if (!(_exceptionHandler?.HandleException(context, entity, ex) ?? false))
{
throw;
}
}
await PublishDomainEventAsync(savedEntity, transaction, cancellationToken).ConfigureAwait(false);
return savedEntity;
}
public virtual Task<TEntity> AddAsync(TEntity entity, CancellationToken cancellationToken)
=> AddInternalAsync(entity, null, cancellationToken);
public virtual Task<TEntity> AddAsync(TEntity entity, IEntityTransaction transaction, CancellationToken cancellationToken)
=> AddInternalAsync(entity, transaction, cancellationToken);
private Task PublishDomainEventAsync(TEntity savedEntity, IEntityTransaction transaction, CancellationToken cancellationToken = default)
{
if (_domainEventPublisher == null || _domainEventPublisher is DefaultEntityDomainEventPublisher)
{
return Task.CompletedTask;
}
var domainEvent = new EntityAddedDomainEvent<TEntity> { Entity = savedEntity, EventContext = _domainEventContextProvider?.GetContext() };
return _domainEventPublisher.PublishEntityAddEventAsync(domainEvent, transaction, cancellationToken);
}
}
}
| 41.088889 | 152 | 0.683883 | [
"MIT"
] | djayd/auto-crud | Firebend.AutoCrud.EntityFramework/Abstractions/Client/EntityFrameworkCreateClient.cs | 3,698 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Mac OSCustom App Configuration.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class MacOSCustomAppConfiguration : DeviceConfiguration
{
///<summary>
/// The MacOSCustomAppConfiguration constructor
///</summary>
public MacOSCustomAppConfiguration()
{
this.ODataType = "microsoft.graph.macOSCustomAppConfiguration";
}
/// <summary>
/// Gets or sets bundle id.
/// Bundle id for targeting.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "bundleId", Required = Newtonsoft.Json.Required.Default)]
public string BundleId { get; set; }
/// <summary>
/// Gets or sets configuration xml.
/// Configuration xml. (UTF8 encoded byte array)
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "configurationXml", Required = Newtonsoft.Json.Required.Default)]
public byte[] ConfigurationXml { get; set; }
/// <summary>
/// Gets or sets file name.
/// Configuration file name (.plist
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "fileName", Required = Newtonsoft.Json.Required.Default)]
public string FileName { get; set; }
}
}
| 36.561404 | 153 | 0.604607 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/MacOSCustomAppConfiguration.cs | 2,084 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Harmony
{
/// <summary>
/// Représente une Activité. Une activité est un lot de <see cref="Fragment">Fragments</see> et de <see cref="Menu">Menus</see>.
/// </summary>
/// <remarks>
/// <para>
/// Une seule activité est affichée à la fois. Si une autre activité est démarrée, l'activité courante est déchargée
/// au profit de la nouvelle activité. La nouvelle activité est ensuite mise sur le dessus de la pile d'activités en cours.
/// </para>
/// <para>
/// Lorsque l'activité courante est arrêtée, cette dernière est déchargée, retirée de la pile, et c'est la nouvelle
/// activité sur le dessus de la pile qui est chargée.
/// </para>
/// <para>
/// S'il n'y a plus aucune activité sur la pile, mais que l'on demande tout de même d'arrêter l'activité courante,
/// alors c'est l'application au complet qui est arrêtée.
/// </para>
/// <para>
/// Pour charger des Activités, utilisez un IActivityStack.
/// </para>
/// </remarks>
/// <seealso cref="Fragment"/>
/// <seealso cref="Menu"/>
/// <seealso cref="ActivityStack"/>
[CreateAssetMenu(fileName = "New Activity", menuName = "Game/Activities/Activity")]
public class Activity : ScriptableObject
{
[SerializeField]
private R.E.Scene scene = R.E.Scene.None;
[SerializeField]
private R.E.GameObject controller = R.E.GameObject.None;
[SerializeField]
private Fragment[] fragments = new Fragment[0];
[SerializeField]
private Menu[] menus = new Menu[0];
[SerializeField]
private Fragment activeFragmentOnLoad = null;
/// <summary>
/// Scène de l'activité. (Facultatif)
/// </summary>
public R.E.Scene Scene
{
get { return scene; }
}
/// <summary>
/// Identifiant du GameObject contenant le controleur de l'activité. (Facultatif)
/// </summary>
public R.E.GameObject Controller
{
get { return controller; }
}
/// <summary>
/// Lot de fragments de l'activité. (Facultatif)
/// </summary>
public IList<Fragment> Fragments
{
get { return fragments; }
}
/// <summary>
/// Lot de menus de l'activité. (Facultatif)
/// </summary>
public IList<Menu> Menus
{
get { return menus; }
}
/// <summary>
/// Fragment à marquer comme actif lors du chargement de l'activité (Facultatif).
/// </summary>
public Fragment ActiveFragmentOnLoad
{
get { return activeFragmentOnLoad; }
}
}
} | 32 | 132 | 0.581537 | [
"MIT"
] | Allcatraz/Nullptr_ProjetSynthese | Assets/Libraries/Harmony/Scripts/Playmode/Activity/Data/Activity.cs | 2,824 | C# |
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using System;
using System.Linq;
using Tensorflow.Operations;
using static Tensorflow.Binding;
namespace Tensorflow.Gradients
{
/// <summary>
/// Gradients for operators defined in math_ops.py.
/// </summary>
[RegisterGradient("math_grad")]
public class math_grad
{
[RegisterGradient("Abs")]
public static Tensor[] _AbsGrad(Operation op, Tensor[] grads)
{
var x = op.inputs[0];
var grad = grads[0];
return new Tensor[] { gen_ops.mul(grad, gen_math_ops.sign(x)) };
}
[RegisterGradient("Add")]
public static Tensor[] _AddGrad(Operation op, Tensor[] grads)
{
var x = op.inputs[0];
var y = op.inputs[1];
var grad = grads[0];
if (grad is Tensor &&
_ShapesFullySpecifiedAndEqual(x, y, grad))
return new Tensor[] { grad, grad };
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
var sum1 = math_ops.reduce_sum(grad, rx);
var r1 = gen_array_ops.reshape(sum1, sx);
var sum2 = math_ops.reduce_sum(grad, ry);
var r2 = gen_array_ops.reshape(sum2, sy);
return new Tensor[] { r1, r2 };
}
[RegisterGradient("DivNoNan")]
public static Tensor[] _DivNoNanGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
var y = op.inputs[1];
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
x = math_ops.conj(x);
y = math_ops.conj(y);
var reduce_sum1 = math_ops.reduce_sum(math_ops.div_no_nan(grad, y), rx);
var reduce_sum2 = math_ops.reduce_sum(grad * math_ops.div_no_nan(math_ops.div_no_nan(-x, y), y), ry);
return new Tensor[]
{
array_ops.reshape(reduce_sum1, sx),
array_ops.reshape(reduce_sum2, sy)
};
}
/// <summary>
/// Returns grad * exp(x).
/// </summary>
/// <param name="op"></param>
/// <param name="grads"></param>
/// <returns></returns>
[RegisterGradient("Exp")]
public static Tensor[] _ExpGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var y = op.outputs[0]; // y = e^x
return tf_with(ops.control_dependencies(new Operation[] { grad }), dp => {
y = math_ops.conj(y);
return new Tensor[] { math_ops.mul_no_nan(y, grad) };
});
}
[RegisterNoGradient("GreaterEqual")]
public static Tensor[] _GreaterEqualGrad(Operation op, Tensor[] grads) => null;
[RegisterNoGradient("ZerosLike")]
public static Tensor[] _ZerosLike(Operation op, Tensor[] grads) => null;
[RegisterGradient("Identity")]
public static Tensor[] _IdGrad(Operation op, Tensor[] grads)
{
return new Tensor[] { grads[0] };
}
[RegisterGradient("Lgamma")]
public static Tensor[] _LgammaGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
return tf_with(ops.control_dependencies(new Operation[] { grad }), dp => {
x = math_ops.conj(x);
return new Tensor[] { grad * math_ops.digamma(x) };
});
}
[RegisterGradient("Log")]
public static Tensor[] _LogGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
return tf_with(ops.control_dependencies(new Operation[] { grad }), dp => {
x = math_ops.conj(x);
return new Tensor[] { grad * math_ops.reciprocal(x) };
});
}
[RegisterGradient("Log1p")]
public static Tensor[] _Log1pGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
return tf_with(ops.control_dependencies(new Operation[] { grad }), dp => {
x = math_ops.conj(x);
return new Tensor[] { grad * math_ops.reciprocal(1 + x) };
});
}
[RegisterGradient("Mul")]
public static Tensor[] _MulGrad(Operation op, Tensor[] grads)
{
var x = op.inputs[0];
var y = op.inputs[1];
var grad = grads[0];
if (grad is Tensor &&
_ShapesFullySpecifiedAndEqual(x, y, grad) &&
new TF_DataType[] { tf.int32, tf.float32 }.Contains(grad.dtype))
return new Tensor[] { gen_math_ops.mul(grad, y), gen_math_ops.mul(grad, x) };
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
x = math_ops.conj(x);
y = math_ops.conj(y);
var mul1 = gen_math_ops.mul(grad, y);
var reduce_sum1 = math_ops.reduce_sum(mul1, rx);
var reshape1 = gen_array_ops.reshape(reduce_sum1, sx);
var mul2 = gen_math_ops.mul(x, grad);
var reduce_sum2 = math_ops.reduce_sum(mul2, ry);
var reshape2 = gen_array_ops.reshape(reduce_sum2, sy);
return new Tensor[] { reshape1, reshape2 };
}
[RegisterGradient("MatMul")]
public static Tensor[] _MatMulGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
Tensor grad_a = null, grad_b = null;
var t_a = (bool)op.get_attr("transpose_a");
var t_b = (bool)op.get_attr("transpose_b");
var a = math_ops.conj(op.inputs[0]);
var b = math_ops.conj(op.inputs[1]);
if(!t_a && !t_b)
{
grad_a = gen_math_ops.mat_mul(grad, b, transpose_b: true);
grad_b = gen_math_ops.mat_mul(a, grad, transpose_a: true);
}
else if (!t_a && t_b)
{
grad_a = gen_math_ops.mat_mul(grad, b);
grad_b = gen_math_ops.mat_mul(grad, a, transpose_a: true);
}
else if (t_a && !t_b)
{
grad_a = gen_math_ops.mat_mul(grad, b);
grad_b = gen_math_ops.mat_mul(grad, a, transpose_a: true);
}
else if (t_a && t_b)
{
grad_a = gen_math_ops.mat_mul(b, grad, transpose_a: true, transpose_b: true);
grad_b = gen_math_ops.mat_mul(grad, a, transpose_a: true, transpose_b: true);
}
return new Tensor[] { grad_a, grad_b };
}
[RegisterGradient("BatchMatMul")]
public static Tensor[] _BatchMatMul(Operation op, Tensor[] grads)
{
var grad = grads[0];
Tensor grad_a = null, grad_b = null;
var t_a = (bool)op.get_attr("adj_x");
var t_b = (bool)op.get_attr("adj_y");
var a = math_ops.conj(op.inputs[0]);
var b = math_ops.conj(op.inputs[1]);
if (!t_a && !t_b)
{
grad_a = gen_math_ops.batch_mat_mul(grad, b, adj_y: true);
grad_b = gen_math_ops.batch_mat_mul(a, grad, adj_x: true);
}
else if (!t_a && t_b)
{
grad_a = gen_math_ops.batch_mat_mul(grad, b);
grad_b = gen_math_ops.batch_mat_mul(grad, a, adj_x: true);
}
else if (t_a && !t_b)
{
grad_a = gen_math_ops.batch_mat_mul(grad, b);
grad_b = gen_math_ops.batch_mat_mul(grad, a, adj_x: true);
}
else if (t_a && t_b)
{
grad_a = gen_math_ops.batch_mat_mul(b, grad, adj_x: true, adj_y: true);
grad_b = gen_math_ops.batch_mat_mul(grad, a, adj_x: true, adj_y: true);
}
return new Tensor[] { grad_a, grad_b };
}
[RegisterGradient("Mean")]
public static Tensor[] _MeanGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var sum_grad = _SumGrad(op, grads)[0];
var input_shape = op.inputs[0]._shape_tuple();
var output_shape = op.outputs[0]._shape_tuple();
var input_shape_tensor = array_ops.shape(op.inputs[0]);
var output_shape_tensor = array_ops.shape(op.outputs[0]);
var factor = _safe_shape_div(math_ops.reduce_prod(input_shape_tensor), math_ops.reduce_prod(output_shape_tensor));
return new Tensor[] { math_ops.truediv(sum_grad, math_ops.cast(factor, sum_grad.dtype)), null };
}
/// <summary>
/// Gradient for Max.
/// </summary>
/// <param name="op"></param>
/// <param name="grads"></param>
/// <returns></returns>
[RegisterGradient("Max")]
public static Tensor[] _MaxGrad(Operation op, Tensor[] grads)
{
return _MinOrMaxGrad(op, grads);
}
/// <summary>
/// Gradient for Min.
/// </summary>
/// <param name="op"></param>
/// <param name="grads"></param>
/// <returns></returns>
[RegisterGradient("Min")]
public static Tensor[] _MinGrad(Operation op, Tensor[] grads)
{
return _MinOrMaxGrad(op, grads);
}
private static Tensor[] _MinOrMaxGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var input_shape = array_ops.shape(op.inputs[0]);
var output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]);
var y = op.outputs[0];
y = array_ops.reshape(y, output_shape_kept_dims);
grad = array_ops.reshape(grad, output_shape_kept_dims);
// Compute the number of selected (maximum or minimum) elements in each
// reduction dimension. If there are multiple minimum or maximum elements
// then the gradient will be divided between them.
var indicators = math_ops.cast(math_ops.equal(y, op.inputs[0]), grad.dtype);
var num_selected = array_ops.reshape(math_ops.reduce_sum(indicators, op.inputs[1]), output_shape_kept_dims);
return new Tensor[] { math_ops.div(indicators, num_selected) * grad, null };
}
/// <summary>
/// Returns grad*(x > y, x <= y) with type of grad.
/// </summary>
/// <param name="op"></param>
/// <param name="grads"></param>
/// <returns></returns>
[RegisterGradient("Maximum")]
public static Tensor[] _MaximumGrad(Operation op, Tensor[] grads)
{
return _MaximumMinimumGrad(op, grads[0]);
}
/// <summary>
/// Returns grad*(x < y, x >= y) with type of grad.
/// </summary>
/// <param name="op"></param>
/// <param name="grads"></param>
/// <returns></returns>
[RegisterGradient("Minimum")]
public static Tensor[] _MinimumGrad(Operation op, Tensor[] grads)
{
return _MaximumMinimumGrad(op, grads[0]);
}
/// <summary>
/// Factor out the code for the gradient of Maximum or Minimum.
/// </summary>
/// <param name="op"></param>
/// <param name="grad"></param>
/// <returns></returns>
private static Tensor[] _MaximumMinimumGrad(Operation op, Tensor grad)
{
var x = op.inputs[0];
var y = op.inputs[1];
var gdtype = grad.dtype;
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var gradshape = array_ops.shape(grad);
var zeros = array_ops.zeros(gradshape, gdtype);
var xmask = gen_math_ops.greater_equal(x, y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
var xgrad = array_ops.where(xmask, grad, zeros);
var ygrad = array_ops.where(xmask, zeros, grad);
var gx = array_ops.reshape(math_ops.reduce_sum(xgrad, rx), sx);
var gy = array_ops.reshape(math_ops.reduce_sum(ygrad, ry), sy);
return new Tensor[] { gx, gy };
}
[RegisterGradient("Neg")]
public static Tensor[] _NegGrad(Operation op, Tensor[] grads)
{
return new Tensor[] { -grads[0] };
}
[RegisterGradient("Select")]
public static Tensor[] _SelectGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var c = op.inputs[0];
var x = op.inputs[1];
var zeros = array_ops.zeros_like(x);
return new Tensor[]
{
null,
array_ops.where(c, grad, zeros),
array_ops.where(c, zeros, grad)
};
}
private static Tensor _safe_shape_div(Tensor x, Tensor y)
{
return math_ops.floordiv(x, gen_math_ops.maximum(y, 1));
}
[RegisterGradient("Sub")]
public static Tensor[] _SubGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
var y = op.inputs[1];
if (grad is Tensor &&
_ShapesFullySpecifiedAndEqual(x, y, grad))
return new Tensor[] { grad, -grad };
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
var r1 = gen_array_ops.reshape(math_ops.reduce_sum(grad, rx), sx);
var r2 = gen_array_ops.reshape(-math_ops.reduce_sum(grad, ry), sy);
return new Tensor[] { r1, r2 };
}
public static bool _ShapesFullySpecifiedAndEqual(Tensor x, Tensor y, Tensor grad)
{
var x_shape = x._shape_tuple();
var y_shape = y._shape_tuple();
var grad_shape = grad._shape_tuple();
return x_shape != null &&
y_shape != null &&
Enumerable.SequenceEqual(x_shape, y_shape) &&
Enumerable.SequenceEqual(y_shape, grad_shape) &&
!x_shape.Contains(-1);
}
[RegisterGradient("Sum")]
public static Tensor[] _SumGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var input_0_shape = op.inputs[0]._shape_tuple();
Tensor input_shape = null;
if (input_0_shape != null)
{
var axes = tensor_util.constant_value(op.inputs[1]);
if(!(axes is null))
{
var rank = input_0_shape.Length;
if (Enumerable.SequenceEqual(Enumerable.Range(0, rank), axes.Data<int>()))
{
var new_shape = range(rank).Select(x => 1).ToArray();
grad = array_ops.reshape(grad, new_shape);
// If shape is not fully defined (but rank is), we use Shape.
if (!input_0_shape.Contains(-1))
input_shape = constant_op.constant(input_0_shape);
else
input_shape = array_ops.shape(op.inputs[0]);
return new Tensor[] { gen_array_ops.tile(grad, input_shape), null };
}
}
}
input_shape = array_ops.shape(op.inputs[0]);
ops.colocate_with(input_shape);
var output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]);
var tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims);
grad = gen_array_ops.reshape(grad, output_shape_kept_dims);
return new Tensor[] { gen_array_ops.tile(grad, tile_scaling), null };
}
[RegisterGradient("RealDiv")]
public static Tensor[] _RealDivGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
var y = op.inputs[1];
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
x = math_ops.conj(x);
y = math_ops.conj(y);
var realdiv1 = gen_math_ops.real_div(-x, y);
var realdiv2 = gen_math_ops.real_div(realdiv1, y);
var reduce_sum1 = math_ops.reduce_sum(grad * realdiv2, ry);
var reshape1 = gen_array_ops.reshape(reduce_sum1, sy);
var realdiv3 = gen_math_ops.real_div(grad, y);
var reduce_sum2 = math_ops.reduce_sum(realdiv3, rx);
var reshape2 = gen_array_ops.reshape(reduce_sum2, sx);
return new Tensor[] { reshape2, reshape1 };
}
[RegisterGradient("Sigmoid")]
public static Tensor[] _SigmoidGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var y = op.outputs[0];
return tf_with(ops.control_dependencies(grads), delegate
{
y = math_ops.conj(y);
return new Tensor[] { gen_math_ops.sigmoid_grad(y, grad) };
});
}
[RegisterGradient("Sign")]
public static Tensor[] _SignGrad(Operation op, Tensor[] grads)
{
var x = op.inputs[0];
var zero = constant_op.constant(0.0f, x.dtype, x.shape);
return new Tensor[] {zero};
}
[RegisterGradient("Square")]
public static Tensor[] _SquareGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
return tf_with(ops.control_dependencies(grads), delegate
{
x = math_ops.conj(x);
var y = constant_op.constant(2.0f, dtype: x.dtype);
return new Tensor[] { math_ops.multiply(grad, math_ops.multiply(x, y)) };
});
}
[RegisterGradient("Tanh")]
public static Tensor[] _TanhGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var y = op.outputs[0];
return tf_with(ops.control_dependencies(grads), delegate
{
y = math_ops.conj(y);
return new Tensor[] { gen_math_ops.tanh_grad(y, grad) };
});
}
[RegisterGradient("Pow")]
public static Tensor[] _PowGrad(Operation op, Tensor[] grads)
{
var grad = grads[0];
var x = op.inputs[0];
var y = op.inputs[1];
var z = op.outputs[0];
var sx = array_ops.shape(x);
var sy = array_ops.shape(y);
var (rx, ry) = gen_array_ops.broadcast_gradient_args(sx, sy);
x = math_ops.conj(x);
y = math_ops.conj(y);
z = math_ops.conj(z);
var pow = gen_math_ops.pow(x, y - 1.0f);
var mul = grad * y * pow;
var reduce_sum = math_ops.reduce_sum(mul, rx);
var gx = gen_array_ops.reshape(reduce_sum, sx);
// Avoid false singularity at x = 0
Tensor mask = null;
if (x.dtype.is_complex())
throw new NotImplementedException("x.dtype.is_complex()");
else
mask = x > 0.0f;
var ones = array_ops.ones_like(x);
var safe_x = array_ops.where(mask, x, ones);
var x1 = gen_array_ops.log(safe_x);
var y1 = array_ops.zeros_like(x);
var log_x = array_ops.where(mask, x1, y1);
var mul1 = grad * z * log_x;
var reduce_sum1 = math_ops.reduce_sum(mul1, ry);
var gy = gen_array_ops.reshape(reduce_sum1, sy);
return new Tensor[] { gx, gy };
}
}
}
| 37.927536 | 126 | 0.530331 | [
"Apache-2.0"
] | Oceania2018/TensorFlow.NET | src/TensorFlowNET.Core/Gradients/math_grad.cs | 20,938 | C# |
using System;
using System.Linq;
using NUnit.Framework;
namespace EventStore.Core.Tests.Services.ElectionsService.Randomized
{
[TestFixture]
public class elections_service_5_nodes_full_gossip_no_http_loss_no_dup
{
private RandomizedElectionsTestCase _randomCase;
[SetUp]
public void SetUp()
{
_randomCase = new RandomizedElectionsTestCase(ElectionParams.MaxIterationCount,
instancesCnt: 5,
httpLossProbability: 0.0,
httpDupProbability: 0.0,
httpMaxDelay: 20,
timerMinDelay: 100,
timerMaxDelay: 200);
_randomCase.Init();
}
[Test, Category("LongRunning"), Category("Network")]
public void should_always_arrive_at_coherent_results([Range(0, ElectionParams.TestRunCount - 1)]int run)
{
var success = _randomCase.Run();
if (!success)
_randomCase.Logger.LogMessages();
Console.WriteLine("There were a total of {0} messages in this run.", _randomCase.Logger.ProcessedItems.Count());
Assert.True(success);
}
}
} | 40.857143 | 124 | 0.51049 | [
"Apache-2.0",
"CC0-1.0"
] | BertschiAG/EventStore | src/EventStore.Core.Tests/Services/ElectionsService/Randomized/elections_service_5_nodes_full_gossip_no_http_loss_no_dup.cs | 1,430 | C# |
using Microsoft.Extensions.Options;
using SF.Module.SimpleAuth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SF.Module.SimpleAuth.Services
{
public class DefaultUserLookupProvider : IUserLookupProvider
{
public DefaultUserLookupProvider(IOptions<List<SimpleAuthUser>> usersAccessor)
{
allUsers = usersAccessor.Value;
}
private List<SimpleAuthUser> allUsers;
public SimpleAuthUser GetUser(string userName)
{
foreach (SimpleAuthUser u in allUsers)
{
if (u.UserName == userName) { return u; }
}
return null;
}
}
}
| 23.548387 | 86 | 0.641096 | [
"Apache-2.0"
] | ZHENGZHENGRONG/SF-Boilerplate | Modules/SF.Module.SimpleAuth/Services/DefaultUserLookupProvider.cs | 732 | C# |
using Orchard.UI.Resources;
namespace Laser.Orchard.jQueryPlugins {
public class ResourceManifest : IResourceManifestProvider {
public void BuildManifests(ResourceManifestBuilder builder) {
var manifest = builder.Add();
//Scripts
manifest.DefineScript("jQuery_DataTables").SetUrl("jquery.dataTables.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_textcounter").SetUrl("textcounter.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_ImagePicker").SetUrl("image-picker.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Print").SetUrl("jquery.print.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Cycle").SetUrl("jquery.cycle.all.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Cycle2").SetUrl("jquery.cycle2.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_MultiSelect").SetUrl("jquery.multiSelect.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Tools").SetUrl("jquery.tools.min.js").SetDependencies("jQuery", "jQueryUI_Core", "jQueryMigrate");
// manifest.DefineScript("jQuery_MultiSelect").SetUrl("jquery.multiSelect.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_CarouFredSel").SetUrl("jquery.carouFredSel.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Carousel").SetUrl("jquery.carousel.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Contactable").SetUrl("jquery.contactable.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_UI_Multiselect_Widget").SetUrl("jquery.ui.multiselect.widget.min.js").SetDependencies("jQuery", "jQueryUI_Widget", "jQueryUI_Core", "jQueryUI_Position");
manifest.DefineScript("jQuery_Validate_Unobtrusive").SetUrl("jquery.validate.unobtrusive.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Validate").SetUrl("jquery.validate.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Validate_Vsdoc").SetUrl("jquery.validate-vsdoc.js").SetDependencies("jQuery");
manifest.DefineScript("jQuery_Unobtrusive_Ajax").SetUrl("jquery.unobtrusive-ajax.min.js").SetDependencies("jQuery");
manifest.DefineScript("jQueryUI_DatePicker_it").SetUrl("jquery.ui.datepicker-it.js").SetDependencies("jQuery", "jQueryUI_DatePicker");
manifest.DefineScript("jQueryUI_DatePicker_fr").SetUrl("jquery.ui.datepicker-fr.js").SetDependencies("jQuery", "jQueryUI_DatePicker");
manifest.DefineScript("jQueryUI_DatePicker_en").SetUrl("jquery.ui.datepicker-en.js").SetDependencies("jQuery", "jQueryUI_DatePicker");
manifest.DefineScript("jQueryUI_DatePicker_de").SetUrl("jquery.ui.datepicker-de.js").SetDependencies("jQuery", "jQueryUI_DatePicker");
manifest.DefineScript("jQueryUI_DatePicker_es").SetUrl("jquery.ui.datepicker-es.js").SetDependencies("jQuery", "jQueryUI_DatePicker");
manifest.DefineScript("jQueryUI_DatePicker_ru").SetUrl("jquery.ui.datepicker-ru.js").SetDependencies("jQuery", "jQueryUI_DatePicker");
manifest.DefineScript("jQuery_NestedModels").SetUrl("custom/jquery.nestedmodels.js").SetDependencies("jQuery");
manifest.DefineScript("Jssor_Core").SetUrl("Jssor/jssor.core.js").SetDependencies("jQuery");
manifest.DefineScript("Jssor_Slider").SetUrl("Jssor/jssor.slider.js").SetDependencies("jQuery");
manifest.DefineScript("Jssor_Utils").SetUrl("Jssor/jssor.utils.js").SetDependencies("jQuery");
manifest.DefineScript("Jssor_Mini").SetUrl("Jssor/jssor.slider.mini.js").SetDependencies("jQuery");
manifest.DefineScript("jsTree").SetUrl("jsTree/jstree.js").SetDependencies("jQuery");
manifest.DefineScript("jsTree_Mini").SetUrl("jsTree/jstree.min.js").SetDependencies("jQuery");
manifest.DefineScript("jsTreeGrid").SetUrl("jsTree/jstreegrid.js").SetDependencies("jsTree");
manifest.DefineScript("rcswitcher").SetUrl("rcswitcher.min.js").SetDependencies("jQuery");
manifest.DefineScript("jqPlot").SetUrl("jqPlot/jquery.jqplot.js").SetDependencies("jQuery");
manifest.DefineScript("jqPlot_Mini").SetUrl("jqPlot/jquery.jqplot.min.js").SetDependencies("jQuery");
manifest.DefineScript("jqPlotPieChart").SetUrl("jqPlot/plugins/jqplot.pieRenderer.js").SetDependencies("jqPlot");
manifest.DefineScript("jqPlotEnhancedPieLegendRenderer").SetUrl("jqPlot/plugins/jqplot.enhancedPieLegendRenderer.js").SetDependencies("jqPlot");
manifest.DefineScript("jsonViewer").SetUrl("json-browse/jquery.json-browse.js").SetDependencies("jQuery");
manifest.DefineScript("animsition").SetCdn("https://cdnjs.cloudflare.com/ajax/libs/animsition/4.0.2/js/animsition.min.js","https://cdnjs.cloudflare.com/ajax/libs/animsition/4.0.2/js/animsition.js").SetDependencies("jQuery");
manifest.DefineScript("Select2")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js")
.SetDependencies("jQuery");
//Styles
manifest.DefineStyle("jQuery_DataTables").SetUrl("jqDataTable/jquery.dataTables.min.css");
manifest.DefineStyle("jQuery_ImagePicker_Low").SetUrl("image-picker_low.css");
manifest.DefineStyle("jQuery_ImagePicker").SetUrl("image-picker.css");
manifest.DefineStyle("jQuery_MultiSelect").SetUrl("jquery.multiSelect.css");
manifest.DefineStyle("jQuery_Autocomplete").SetUrl("jquery.autocomplete.css");
manifest.DefineStyle("jQuery_Cycle").SetUrl("jquery.cycle.css");
manifest.DefineStyle("jQuery_CarouFredSel_Responsive").SetUrl("jquery.caroufredsel.responsive.css");
manifest.DefineStyle("jQuery_UI_Multiselect_Widget").SetUrl("jquery.ui.multiselect.widget.css").SetDependencies("jQueryUI_Orchard");
manifest.DefineStyle("DivTableLayouts").SetUrl("custom/divtablelayouts.css");
manifest.DefineStyle("Jssor_BannerSlider").SetUrl("Jssor/jssor.bannerslider.css");
manifest.DefineStyle("jsTree_Default").SetUrl("jsTree/Default/style.css");
manifest.DefineStyle("jsTree_Default_Mini").SetUrl("jsTree/Default/style.min.css");
manifest.DefineStyle("jsTree_DefaultDark").SetUrl("jsTree/DefaultDark/style.css");
manifest.DefineStyle("jsTree_DefaultDark_Mini").SetUrl("jsTree/DefaultDark/style.min.css");
manifest.DefineStyle("Accordion").SetUrl("accordion.css");
manifest.DefineStyle("rcswitcher").SetUrl("rcswitcher.min.css");
manifest.DefineStyle("jqPlot").SetUrl("jqPlot/jquery.jqplot.css");
manifest.DefineStyle("jqPlot_Mini").SetUrl("jqPlot/jquery.jqplot.min.css");
manifest.DefineStyle("jsonViewer").SetUrl("json-browse/jquery.json-browse.css");
manifest.DefineStyle("animsition").SetCdn("https://cdnjs.cloudflare.com/ajax/libs/animsition/4.0.2/css/animsition.css", "https://cdnjs.cloudflare.com/ajax/libs/animsition/4.0.2/css/animsition.min.css");
manifest.DefineStyle("Select2")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css");
}
}
} | 79.234043 | 236 | 0.711332 | [
"Apache-2.0"
] | mkbiltek2019/Laser.Orchard.Platform | src/Modules/Laser.Orchard.jQueryPlugins/ResourceManifest.cs | 7,450 | C# |
using Microsoft.EntityFrameworkCore;
namespace WebApi.Model
{
public partial class NewsSiteProjeContext : DbContext
{
public static string ConnectionString { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
public virtual DbSet<CATEGORY> CATEGORY { get; set; }
public virtual DbSet<EDITOR> EDITOR { get; set; }
public virtual DbSet<NEWS> NEWS { get; set; }
public virtual DbSet<USER> USER { get; set; }
public virtual DbSet<XUSERS> XUSER { get; set; }
public virtual DbSet<TAGS> TAG { get; set; }
public virtual DbSet<SLIDER> SLIDER { get; set; }
}
}
| 32.956522 | 85 | 0.653034 | [
"MIT"
] | yesmancan/akdenizUniversitesi2Sinif2DonemWebOdevi | WebApi/Model/NewsSiteProjeContext.cs | 758 | C# |
using Microsoft.AspNetCore.Mvc;
using Shriek.Notifications;
using System.Threading.Tasks;
namespace Shriek.Samples.CQRS.EFCore.ViewComponents
{
public class SummaryViewComponent : ViewComponent
{
private readonly IDomainNotificationHandler<DomainNotification> _notifications;
public SummaryViewComponent(IDomainNotificationHandler<DomainNotification> notifications)
{
_notifications = notifications;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var notificacoes = await Task.FromResult((_notifications.Notifications));
notificacoes.ForEach(c => ViewData.ModelState.AddModelError(string.Empty, c.Value));
return View();
}
}
} | 31.583333 | 97 | 0.704485 | [
"MIT"
] | 1071157808/shriek-fx | samples/Shriek.Samples.CQRS.EFCore/ViewComponents/SummaryViewComponent.cs | 760 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobCancellationsOperations operations.
/// </summary>
internal partial class JobCancellationsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IJobCancellationsOperations
{
/// <summary>
/// Initializes a new instance of the JobCancellationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal JobCancellationsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Cancels a job. This is an asynchronous operation. To know the status of
/// the cancellation, call GetCancelOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='jobName'>
/// Name of the job to cancel.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> TriggerWithHttpMessagesAsync(string vaultName, string resourceGroupName, string jobName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (jobName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "jobName");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Trigger", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}/cancel").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 48.201878 | 391 | 0.597838 | [
"MIT"
] | samtoubia/azure-sdk-for-net | src/ResourceManagement/RecoveryServices.Backup/Microsoft.Azure.Management.RecoveryServices.Backup/Generated/JobCancellationsOperations.cs | 10,267 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IMethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IReportRootGetOffice365ActivationsUserCountsRequest.
/// </summary>
public partial interface IReportRootGetOffice365ActivationsUserCountsRequest : IBaseRequest
{
/// <summary>
/// Issues the GET request.
/// </summary>
System.Threading.Tasks.Task<Report> GetAsync();
/// <summary>
/// Issues the GET request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<Report> GetAsync(
CancellationToken cancellationToken);
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name="report">The Report object set with the properties to update.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<Report> PatchAsync(Report report);
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name="report">The Report object set with the properties to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<Report> PatchAsync(Report report,
CancellationToken cancellationToken);
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name="report">The Report object to update.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<Report> PutAsync(Report report);
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name="report">The Report object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<Report> PutAsync(Report report,
CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IReportRootGetOffice365ActivationsUserCountsRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IReportRootGetOffice365ActivationsUserCountsRequest Select(string value);
}
}
| 40.267442 | 153 | 0.603812 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IReportRootGetOffice365ActivationsUserCountsRequest.cs | 3,463 | C# |
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class EscapeRoom : ModuleRules
{
public EscapeRoom(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
| 31.958333 | 128 | 0.750978 | [
"MIT"
] | scarriere/udemy-escape-room | Source/EscapeRoom/EscapeRoom.Build.cs | 767 | C# |
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
namespace Blog.Models
{
public class BlogDbContext : IdentityDbContext<ApplicationUser>
{
public BlogDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public IDbSet<Article> Articles { get; set; }
public static BlogDbContext Create()
{
return new BlogDbContext();
}
}
} | 21.857143 | 67 | 0.620915 | [
"MIT"
] | ilyogri/SoftUni | Software Technologies/17. C# - Blog Basic Functionality/Blog/Models/BlogDbContext.cs | 461 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*Autocad Related Imports*/
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
namespace Khal_Deafting
{
public class Label_Annotation
{
public Point2d drafting_orgin;
public Point2d geometric_orgin;
public Point2d text_Location;
public double xscale_factor;
public double yscale_factor;
public string text_content;
public bool hasLeader;
// public Point2d pointer;
public double Draftingwidth;
public double text_Rotation_Angle;
public int alignment_index;
public Label_Annotation(string annotation_text,
Point2d anotation_location,Point2d Geometric_origin,
Point2d Drafting_origin,bool withLeader,
double sx,double sy,double drafting_width)
{
this.text_content = annotation_text;
this.text_Location =anotation_location;
this.geometric_orgin = Geometric_origin;
this.drafting_orgin = Drafting_origin;
this.xscale_factor = sx;
this.yscale_factor = sy;
this.hasLeader = withLeader;
this.Draftingwidth = drafting_width;
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor edt = doc.Editor;
edt.WriteMessage("\n testing constructor...");
this.displayPoint("text Location",anotation_location);
this.displayPoint("text Location", this.text_Location);
this.displayPoint("geometric_origin", Geometric_origin);
this.displayPoint("geometric_origin", this.geometric_orgin);
this.displayPoint("drafting_origin", Drafting_origin);
this.displayPoint("drafting_origin", this.drafting_orgin);
this.displayAnnotaion();
}
public void displayPoint(string point_name, Point2d p)
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor edt = doc.Editor;
edt.WriteMessage("\n"+point_name+" x="+p.X+"y="+p.Y);
}
private void populateAlignment()
{
}
public void displayAnnotaion()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor edt = doc.Editor;
edt.WriteMessage("\n displaying annotaion oject information......");
edt.WriteMessage("\n geometric origin x=" + this.geometric_orgin.X + "y=" + this.geometric_orgin.Y);
edt.WriteMessage("\n drafting origin x=" + this.drafting_orgin.X + "y=" + this.drafting_orgin.Y);
edt.WriteMessage("\n Text Location x=" + this.text_Location.X + "y=" + this.text_Location.Y);
edt.WriteMessage("\n sx=" + this.xscale_factor + "y=" + this.yscale_factor);
}
public void drawAnnotation(double text_rotation,int alignment)
{
/*
alignment 1=midle.center;
alignment 2=
*/
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor edt = doc.Editor;
using (Transaction trans = doc.TransactionManager.StartTransaction())
{
BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
try {
this.displayAnnotaion();
MText txtLabel = new MText();
txtLabel.Contents = this.text_content;
double w = this.Draftingwidth;
txtLabel.TextHeight = w * 0.008;
/* Calculating Drfting Location*/
Mytransformation trs = new Mytransformation();
Point2d tog = trs.Translate(this.text_Location, -this.geometric_orgin.X, -this.geometric_orgin.Y);
//edt.WriteMessage("\n x" + draftingOrigin.X + " y=" + draftingOrigin.Y);
Point2d scaledPoint = trs.Scale(tog, this.xscale_factor, this.yscale_factor);
Point2d draftingPoint = trs.Translate(scaledPoint, this.drafting_orgin.X, this.drafting_orgin.Y);
edt.WriteMessage("\n drafting x=" + draftingPoint.X + " y=" + draftingPoint.Y);
Point3d insPt = new Point3d(draftingPoint.X, draftingPoint.Y, 0);
txtLabel.Location = insPt;
if (alignment == 1)
{
txtLabel.Attachment = AttachmentPoint.TopLeft;
}
else if (alignment == 2)
{
txtLabel.Attachment = AttachmentPoint.TopCenter;
}
else if (alignment == 3)
{
txtLabel.Attachment = AttachmentPoint.MiddleCenter;
}
else
{
txtLabel.Attachment = AttachmentPoint.TopRight;
}
txtLabel.Rotation = text_rotation;
btr.AppendEntity(txtLabel);
trans.AddNewlyCreatedDBObject(txtLabel, true);
trans.Commit();
}
catch (System.Exception ex)
{
edt.WriteMessage("\n" + ex.Message);
edt.WriteMessage("\n" + ex.Source);
edt.WriteMessage("\n" + ex.HResult);
}
}
}
}
}
| 36.3 | 127 | 0.567655 | [
"MIT"
] | jakariapervez/cmis6 | Civilworks cost/ACAD TUTORIAL/Khal_Drafting_Backup_28_5_2021/Label_Annotation.cs | 6,173 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Api.Data.Models;
using Api.Data.Models.Sys;
using Api.Models;
namespace Api.Service
{
public interface IHomeService
{
Task<BaseAnswer> GetSysUsers();
BaseAnswer GetSysUserss();
Task<Guid> Insert();
Task<Guid> InsertRole(SysRole role);
Task<Guid> UpdateRole(SysRole role);
Task<SysRole> GetRole(SysRole role);
Task<Guid> InsertUser(SysUser user);
}
} | 20.807692 | 44 | 0.630314 | [
"MIT"
] | shmilyany/framework | NW/Api/Api.Service/IHomeService.cs | 543 | C# |
using Newtonsoft.Json;
namespace ColleyMatrix.Provider.Serializer.Json.NewtonSoft
{
/// <inheritdoc />
public class NewtonSoftJsonSerializationProvider : IJsonSerializationProvider
{
/// <inheritdoc />
public string Serialize(object objectToSerialize)
{
return JsonConvert.SerializeObject(objectToSerialize);
}
}
}
| 25.133333 | 81 | 0.681698 | [
"MIT"
] | scottenriquez/colley-matrix | src/ColleyMatrix.Provider.Serializer.Json.NewtonSoft/NewtonSoftJsonSerializationProvider.cs | 379 | C# |
using System;
namespace Unity.VisualScripting
{
/// <summary>
/// Called once per frame for every collider that is touching the trigger.
/// </summary>
public sealed class OnTriggerStay : TriggerEventUnit
{
public override Type MessageListenerType => typeof(UnityOnTriggerStayMessageListener);
protected override string hookName => EventHooks.OnTriggerStay;
}
}
| 28.785714 | 94 | 0.71464 | [
"MIT"
] | 2PUEG-VRIK/UnityEscapeGame | 2P-UnityEscapeGame/Library/PackageCache/com.unity.visualscripting@1.6.1/Runtime/VisualScripting.Flow/Framework/Events/Physics/OnTriggerStay.cs | 403 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Threading.Tasks;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Nest;
using Tests.Framework.EndpointTests;
namespace Tests.Document.Multiple.UpdateByQueryRethrottle
{
public class UpdateByQueryRethrottleUrlTests : UrlTestsBase
{
private readonly TaskId _taskId = "rhtoNesNR4aXVIY2bRR4GQ:13056";
[U] public override async Task Urls() =>
await UrlTester.POST($"/_update_by_query/{UrlTester.EscapeUriString(_taskId.ToString())}/_rethrottle")
.Fluent(c => c.UpdateByQueryRethrottle(_taskId))
.Request(c => c.UpdateByQueryRethrottle(new UpdateByQueryRethrottleRequest(_taskId)))
.FluentAsync(c => c.UpdateByQueryRethrottleAsync(_taskId))
.RequestAsync(c => c.UpdateByQueryRethrottleAsync(new UpdateByQueryRethrottleRequest(_taskId)));
}
}
| 41.25 | 105 | 0.789899 | [
"Apache-2.0"
] | Brightspace/elasticsearch-net | tests/Tests/Document/Multiple/UpdateByQueryRethrottle/UpdateByQueryRethrottleUrlTests.cs | 992 | C# |
using System;
using CSF.Screenplay.Performables;
using CSF.Screenplay.Selenium.ElementMatching;
using CSF.Screenplay.Selenium.Models;
using CSF.Screenplay.Selenium.Questions;
namespace CSF.Screenplay.Selenium.Builders
{
/// <summary>
/// A builder type which returns a collection of matching elements from the current page.
/// </summary>
public class ElementsInThePageBody
{
ILocatorBasedTarget innerTarget;
IMatcher matcher;
/// <summary>
/// Indicates that only elements which match the given target specification are to be returned.
/// </summary>
/// <returns>The builder instance.</returns>
/// <param name="target">A target specification.</param>
public ElementsInThePageBody ThatAre(ILocatorBasedTarget target)
{
this.innerTarget = target;
return this;
}
/// <summary>
/// Indicates that only elements which match a given <see cref="IMatcher"/> are to be returned.
/// </summary>
/// <returns>The builder instance.</returns>
/// <param name="matcher">A matcher instance.</param>
public ElementsInThePageBody That(IMatcher matcher)
{
this.matcher = matcher;
return this;
}
/// <summary>
/// Assigns a name to the collection of elements which are returned and gets the performable question.
/// </summary>
/// <returns>A performable question instance.</returns>
/// <param name="name">A name for the returned collection of elements.</param>
public IQuestion<ElementCollection> Called(string name)
{
return new FindElementsOnPage(innerTarget, matcher, name);
}
}
}
| 32.42 | 106 | 0.692165 | [
"MIT"
] | csf-dev/CSF.Screenplay.Selenium | CSF.Screenplay.Selenium/Builders/ElementsInThePageBody.cs | 1,623 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Machine.Specifications.Explorers;
using Machine.Specifications.Model;
using Machine.Specifications.Runner.Impl.Listener;
using Machine.Specifications.Utility;
namespace Machine.Specifications.Runner.Impl
{
internal class AssemblyRunner
{
readonly AggregateRunListener _listener;
readonly RunOptions _options;
Action<Assembly> _assemblyStart;
Action<Assembly> _assemblyEnd;
readonly IList<IAssemblyContext> _executedAssemblyContexts;
readonly AssemblyExplorer _explorer;
public AssemblyRunner(ISpecificationRunListener listener, RunOptions options)
{
RedirectOutputState state = new RedirectOutputState();
_listener = new AggregateRunListener(new[]
{
new AssemblyLocationAwareListener(),
new SetUpRedirectOutputRunListener(state),
listener,
new TearDownRedirectOutputRunListener(state),
});
_options = options;
_explorer = new AssemblyExplorer();
_executedAssemblyContexts = new List<IAssemblyContext>();
_assemblyStart = OnAssemblyStart;
_assemblyEnd = OnAssemblyEnd;
}
public void Run(Assembly assembly, IEnumerable<Context> contexts)
{
var hasExecutableSpecifications = false;
try
{
hasExecutableSpecifications = contexts.Any(x => x.HasExecutableSpecifications);
var globalCleanups = _explorer.FindAssemblyWideContextCleanupsIn(assembly).ToList();
var specificationSupplements = _explorer.FindSpecificationSupplementsIn(assembly).ToList();
if (hasExecutableSpecifications)
{
_assemblyStart(assembly);
}
foreach (var context in contexts)
{
RunContext(context, globalCleanups, specificationSupplements);
}
}
catch (Exception err)
{
_listener.OnFatalError(new ExceptionResult(err));
}
finally
{
if (hasExecutableSpecifications)
{
_assemblyEnd(assembly);
}
}
}
void OnAssemblyStart(Assembly assembly)
{
try
{
_listener.OnAssemblyStart(assembly.GetInfo());
IEnumerable<IAssemblyContext> assemblyContexts = _explorer.FindAssemblyContextsIn(assembly);
assemblyContexts.Each(assemblyContext =>
{
assemblyContext.OnAssemblyStart();
_executedAssemblyContexts.Add(assemblyContext);
});
}
catch (Exception err)
{
_listener.OnFatalError(new ExceptionResult(err));
}
}
void OnAssemblyEnd(Assembly assembly)
{
try
{
_listener.OnAssemblyEnd(assembly.GetInfo());
_executedAssemblyContexts
.Reverse()
.Each(assemblyContext => assemblyContext.OnAssemblyComplete());
}
catch (Exception err)
{
_listener.OnFatalError(new ExceptionResult(err));
}
}
public void StartExplicitRunScope(Assembly assembly)
{
_assemblyStart = x => { };
_assemblyEnd = x => { };
OnAssemblyStart(assembly);
}
public void EndExplicitRunScope(Assembly assembly)
{
OnAssemblyEnd(assembly);
}
void RunContext(Context context,
IEnumerable<ICleanupAfterEveryContextInAssembly> globalCleanups,
IEnumerable<ISupplementSpecificationResults> supplements)
{
var runner = ContextRunnerFactory.GetContextRunnerFor(context);
runner.Run(context, _listener, _options, globalCleanups, supplements);
}
}
} | 34.439394 | 109 | 0.533656 | [
"MIT"
] | Slesa/machine.specifications | Source/Machine.Specifications/Runner/Impl/AssemblyRunner.cs | 4,548 | C# |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace System.Web.UI.DataVisualization.Charting.Samples
{
/// <summary>
/// Summary description for GroupingByAxisLabel.
/// </summary>
public partial class GroupingByAxisLabel : System.Web.UI.Page
{
private void PopulateData()
{
// Populate series data
double[] yValues = {645.62, 745.54, 360.45, 534.73, 585.42, 832.12, 455.18, 667.15, 256.24, 523.65, 356.56, 575.85, 156.78, 450.67};
string[] xValues = {"John", "Peter", "Dave", "Alex", "Scott", "Peter", "Alex", "Dave", "John", "Peter", "Dave", "Scott", "Alex", "Peter"};
Chart1.Series["Sales"].Points.DataBindXY(xValues, yValues);
// Group series data points by Axis Label (sales person name)
Chart1.DataManipulator.GroupByAxisLabel(GroupingFormulaList.SelectedItem.Value, "Sales", "Total by Person");
}
protected void Page_Load(object sender, System.EventArgs e)
{
PopulateData();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
protected void GroupingFormulaList_SelectedIndexChanged(object sender, System.EventArgs e)
{
PopulateData();
}
}
}
| 27.387097 | 141 | 0.699058 | [
"MIT"
] | AngeloCresta/winforms-datavisualization-net4.8 | WebSamples/WorkingWithData/DataManipulation/Grouping/GroupingByAxisLabel/GroupingByAxisLabel.aspx.cs | 1,698 | C# |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dataproc.V1
{
/// <summary>Settings for <see cref="ClusterControllerClient"/> instances.</summary>
public sealed partial class ClusterControllerSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ClusterControllerSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ClusterControllerSettings"/>.</returns>
public static ClusterControllerSettings GetDefault() => new ClusterControllerSettings();
/// <summary>Constructs a new <see cref="ClusterControllerSettings"/> object with default settings.</summary>
public ClusterControllerSettings()
{
}
private ClusterControllerSettings(ClusterControllerSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateClusterSettings = existing.CreateClusterSettings;
CreateClusterOperationsSettings = existing.CreateClusterOperationsSettings.Clone();
UpdateClusterSettings = existing.UpdateClusterSettings;
UpdateClusterOperationsSettings = existing.UpdateClusterOperationsSettings.Clone();
DeleteClusterSettings = existing.DeleteClusterSettings;
DeleteClusterOperationsSettings = existing.DeleteClusterOperationsSettings.Clone();
GetClusterSettings = existing.GetClusterSettings;
ListClustersSettings = existing.ListClustersSettings;
DiagnoseClusterSettings = existing.DiagnoseClusterSettings;
DiagnoseClusterOperationsSettings = existing.DiagnoseClusterOperationsSettings.Clone();
OnCopy(existing);
}
partial void OnCopy(ClusterControllerSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClusterControllerClient.CreateCluster</c> and <c>ClusterControllerClient.CreateClusterAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateClusterSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// Long Running Operation settings for calls to <c>ClusterControllerClient.CreateCluster</c> and
/// <c>ClusterControllerClient.CreateClusterAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings CreateClusterOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClusterControllerClient.UpdateCluster</c> and <c>ClusterControllerClient.UpdateClusterAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateClusterSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// Long Running Operation settings for calls to <c>ClusterControllerClient.UpdateCluster</c> and
/// <c>ClusterControllerClient.UpdateClusterAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings UpdateClusterOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClusterControllerClient.DeleteCluster</c> and <c>ClusterControllerClient.DeleteClusterAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteClusterSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// Long Running Operation settings for calls to <c>ClusterControllerClient.DeleteCluster</c> and
/// <c>ClusterControllerClient.DeleteClusterAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings DeleteClusterOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClusterControllerClient.GetCluster</c> and <c>ClusterControllerClient.GetClusterAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetClusterSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Internal, grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClusterControllerClient.ListClusters</c> and <c>ClusterControllerClient.ListClustersAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListClustersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Internal, grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ClusterControllerClient.DiagnoseCluster</c> and <c>ClusterControllerClient.DiagnoseClusterAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DiagnoseClusterSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// Long Running Operation settings for calls to <c>ClusterControllerClient.DiagnoseCluster</c> and
/// <c>ClusterControllerClient.DiagnoseClusterAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings DiagnoseClusterOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ClusterControllerSettings"/> object.</returns>
public ClusterControllerSettings Clone() => new ClusterControllerSettings(this);
}
/// <summary>
/// Builder class for <see cref="ClusterControllerClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class ClusterControllerClientBuilder : gaxgrpc::ClientBuilderBase<ClusterControllerClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ClusterControllerSettings Settings { get; set; }
partial void InterceptBuild(ref ClusterControllerClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ClusterControllerClient> task);
/// <summary>Builds the resulting client.</summary>
public override ClusterControllerClient Build()
{
ClusterControllerClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ClusterControllerClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ClusterControllerClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ClusterControllerClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ClusterControllerClient.Create(callInvoker, Settings);
}
private async stt::Task<ClusterControllerClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ClusterControllerClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ClusterControllerClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ClusterControllerClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ClusterControllerClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ClusterController client wrapper, for convenient use.</summary>
/// <remarks>
/// The ClusterControllerService provides methods to manage clusters
/// of Compute Engine instances.
/// </remarks>
public abstract partial class ClusterControllerClient
{
/// <summary>
/// The default endpoint for the ClusterController service, which is a host of "dataproc.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dataproc.googleapis.com:443";
/// <summary>The default ClusterController scopes.</summary>
/// <remarks>
/// The default ClusterController scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes);
/// <summary>
/// Asynchronously creates a <see cref="ClusterControllerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ClusterControllerClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ClusterControllerClient"/>.</returns>
public static stt::Task<ClusterControllerClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ClusterControllerClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ClusterControllerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ClusterControllerClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ClusterControllerClient"/>.</returns>
public static ClusterControllerClient Create() => new ClusterControllerClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ClusterControllerClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ClusterControllerSettings"/>.</param>
/// <returns>The created <see cref="ClusterControllerClient"/>.</returns>
internal static ClusterControllerClient Create(grpccore::CallInvoker callInvoker, ClusterControllerSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ClusterController.ClusterControllerClient grpcClient = new ClusterController.ClusterControllerClient(callInvoker);
return new ClusterControllerClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ClusterController client</summary>
public virtual ClusterController.ClusterControllerClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Cluster, ClusterOperationMetadata> CreateCluster(CreateClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> CreateClusterAsync(CreateClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> CreateClusterAsync(CreateClusterRequest request, st::CancellationToken cancellationToken) =>
CreateClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>CreateCluster</c>.</summary>
public virtual lro::OperationsClient CreateClusterOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Cluster, ClusterOperationMetadata> PollOnceCreateCluster(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Cluster, ClusterOperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateClusterOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>CreateCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> PollOnceCreateClusterAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Cluster, ClusterOperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateClusterOperationsClient, callSettings);
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="cluster">
/// Required. The cluster to create.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Cluster, ClusterOperationMetadata> CreateCluster(string projectId, string region, Cluster cluster, gaxgrpc::CallSettings callSettings = null) =>
CreateCluster(new CreateClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
Cluster = gax::GaxPreconditions.CheckNotNull(cluster, nameof(cluster)),
}, callSettings);
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="cluster">
/// Required. The cluster to create.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> CreateClusterAsync(string projectId, string region, Cluster cluster, gaxgrpc::CallSettings callSettings = null) =>
CreateClusterAsync(new CreateClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
Cluster = gax::GaxPreconditions.CheckNotNull(cluster, nameof(cluster)),
}, callSettings);
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="cluster">
/// Required. The cluster to create.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> CreateClusterAsync(string projectId, string region, Cluster cluster, st::CancellationToken cancellationToken) =>
CreateClusterAsync(projectId, region, cluster, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Cluster, ClusterOperationMetadata> UpdateCluster(UpdateClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> UpdateClusterAsync(UpdateClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> UpdateClusterAsync(UpdateClusterRequest request, st::CancellationToken cancellationToken) =>
UpdateClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>UpdateCluster</c>.</summary>
public virtual lro::OperationsClient UpdateClusterOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>UpdateCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Cluster, ClusterOperationMetadata> PollOnceUpdateCluster(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Cluster, ClusterOperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateClusterOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>UpdateCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> PollOnceUpdateClusterAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Cluster, ClusterOperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), UpdateClusterOperationsClient, callSettings);
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project the
/// cluster belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="cluster">
/// Required. The changes to the cluster.
/// </param>
/// <param name="updateMask">
/// Required. Specifies the path, relative to `Cluster`, of
/// the field to update. For example, to change the number of workers
/// in a cluster to 5, the `update_mask` parameter would be
/// specified as `config.worker_config.num_instances`,
/// and the `PATCH` request body would specify the new value, as follows:
///
/// {
/// "config":{
/// "workerConfig":{
/// "numInstances":"5"
/// }
/// }
/// }
/// Similarly, to change the number of preemptible workers in a cluster to 5,
/// the `update_mask` parameter would be
/// `config.secondary_worker_config.num_instances`, and the `PATCH` request
/// body would be set as follows:
///
/// {
/// "config":{
/// "secondaryWorkerConfig":{
/// "numInstances":"5"
/// }
/// }
/// }
/// &lt;strong&gt;Note:&lt;/strong&gt; Currently, only the following fields can be updated:
///
/// &lt;table&gt;
/// &lt;tbody&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;Mask&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;&lt;strong&gt;Purpose&lt;/strong&gt;&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;labels&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Update labels&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;config.worker_config.num_instances&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Resize primary worker group&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;config.secondary_worker_config.num_instances&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Resize secondary worker group&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;config.autoscaling_config.policy_uri&lt;/td&gt;&lt;td&gt;Use, stop using, or
/// change autoscaling policies&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;/tbody&gt;
/// &lt;/table&gt;
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Cluster, ClusterOperationMetadata> UpdateCluster(string projectId, string region, string clusterName, Cluster cluster, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateCluster(new UpdateClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
Cluster = gax::GaxPreconditions.CheckNotNull(cluster, nameof(cluster)),
UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)),
}, callSettings);
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project the
/// cluster belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="cluster">
/// Required. The changes to the cluster.
/// </param>
/// <param name="updateMask">
/// Required. Specifies the path, relative to `Cluster`, of
/// the field to update. For example, to change the number of workers
/// in a cluster to 5, the `update_mask` parameter would be
/// specified as `config.worker_config.num_instances`,
/// and the `PATCH` request body would specify the new value, as follows:
///
/// {
/// "config":{
/// "workerConfig":{
/// "numInstances":"5"
/// }
/// }
/// }
/// Similarly, to change the number of preemptible workers in a cluster to 5,
/// the `update_mask` parameter would be
/// `config.secondary_worker_config.num_instances`, and the `PATCH` request
/// body would be set as follows:
///
/// {
/// "config":{
/// "secondaryWorkerConfig":{
/// "numInstances":"5"
/// }
/// }
/// }
/// &lt;strong&gt;Note:&lt;/strong&gt; Currently, only the following fields can be updated:
///
/// &lt;table&gt;
/// &lt;tbody&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;Mask&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;&lt;strong&gt;Purpose&lt;/strong&gt;&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;labels&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Update labels&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;config.worker_config.num_instances&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Resize primary worker group&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;config.secondary_worker_config.num_instances&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Resize secondary worker group&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;config.autoscaling_config.policy_uri&lt;/td&gt;&lt;td&gt;Use, stop using, or
/// change autoscaling policies&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;/tbody&gt;
/// &lt;/table&gt;
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> UpdateClusterAsync(string projectId, string region, string clusterName, Cluster cluster, wkt::FieldMask updateMask, gaxgrpc::CallSettings callSettings = null) =>
UpdateClusterAsync(new UpdateClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
Cluster = gax::GaxPreconditions.CheckNotNull(cluster, nameof(cluster)),
UpdateMask = gax::GaxPreconditions.CheckNotNull(updateMask, nameof(updateMask)),
}, callSettings);
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project the
/// cluster belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="cluster">
/// Required. The changes to the cluster.
/// </param>
/// <param name="updateMask">
/// Required. Specifies the path, relative to `Cluster`, of
/// the field to update. For example, to change the number of workers
/// in a cluster to 5, the `update_mask` parameter would be
/// specified as `config.worker_config.num_instances`,
/// and the `PATCH` request body would specify the new value, as follows:
///
/// {
/// "config":{
/// "workerConfig":{
/// "numInstances":"5"
/// }
/// }
/// }
/// Similarly, to change the number of preemptible workers in a cluster to 5,
/// the `update_mask` parameter would be
/// `config.secondary_worker_config.num_instances`, and the `PATCH` request
/// body would be set as follows:
///
/// {
/// "config":{
/// "secondaryWorkerConfig":{
/// "numInstances":"5"
/// }
/// }
/// }
/// &lt;strong&gt;Note:&lt;/strong&gt; Currently, only the following fields can be updated:
///
/// &lt;table&gt;
/// &lt;tbody&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;Mask&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;&lt;strong&gt;Purpose&lt;/strong&gt;&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;labels&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Update labels&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;config.worker_config.num_instances&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Resize primary worker group&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;&lt;strong&gt;&lt;em&gt;config.secondary_worker_config.num_instances&lt;/em&gt;&lt;/strong&gt;&lt;/td&gt;
/// &lt;td&gt;Resize secondary worker group&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;tr&gt;
/// &lt;td&gt;config.autoscaling_config.policy_uri&lt;/td&gt;&lt;td&gt;Use, stop using, or
/// change autoscaling policies&lt;/td&gt;
/// &lt;/tr&gt;
/// &lt;/tbody&gt;
/// &lt;/table&gt;
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> UpdateClusterAsync(string projectId, string region, string clusterName, Cluster cluster, wkt::FieldMask updateMask, st::CancellationToken cancellationToken) =>
UpdateClusterAsync(projectId, region, clusterName, cluster, updateMask, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<wkt::Empty, ClusterOperationMetadata> DeleteCluster(DeleteClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, ClusterOperationMetadata>> DeleteClusterAsync(DeleteClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, ClusterOperationMetadata>> DeleteClusterAsync(DeleteClusterRequest request, st::CancellationToken cancellationToken) =>
DeleteClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>DeleteCluster</c>.</summary>
public virtual lro::OperationsClient DeleteClusterOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>DeleteCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<wkt::Empty, ClusterOperationMetadata> PollOnceDeleteCluster(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<wkt::Empty, ClusterOperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteClusterOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>DeleteCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, ClusterOperationMetadata>> PollOnceDeleteClusterAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<wkt::Empty, ClusterOperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteClusterOperationsClient, callSettings);
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<wkt::Empty, ClusterOperationMetadata> DeleteCluster(string projectId, string region, string clusterName, gaxgrpc::CallSettings callSettings = null) =>
DeleteCluster(new DeleteClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
}, callSettings);
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, ClusterOperationMetadata>> DeleteClusterAsync(string projectId, string region, string clusterName, gaxgrpc::CallSettings callSettings = null) =>
DeleteClusterAsync(new DeleteClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
}, callSettings);
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<wkt::Empty, ClusterOperationMetadata>> DeleteClusterAsync(string projectId, string region, string clusterName, st::CancellationToken cancellationToken) =>
DeleteClusterAsync(projectId, region, clusterName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Cluster GetCluster(GetClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Cluster> GetClusterAsync(GetClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Cluster> GetClusterAsync(GetClusterRequest request, st::CancellationToken cancellationToken) =>
GetClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Cluster GetCluster(string projectId, string region, string clusterName, gaxgrpc::CallSettings callSettings = null) =>
GetCluster(new GetClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
}, callSettings);
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Cluster> GetClusterAsync(string projectId, string region, string clusterName, gaxgrpc::CallSettings callSettings = null) =>
GetClusterAsync(new GetClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
}, callSettings);
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Cluster> GetClusterAsync(string projectId, string region, string clusterName, st::CancellationToken cancellationToken) =>
GetClusterAsync(projectId, region, clusterName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Cluster"/> resources.</returns>
public virtual gax::PagedEnumerable<ListClustersResponse, Cluster> ListClusters(ListClustersRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Cluster"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListClustersResponse, Cluster> ListClustersAsync(ListClustersRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Cluster"/> resources.</returns>
public virtual gax::PagedEnumerable<ListClustersResponse, Cluster> ListClusters(string projectId, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListClusters(new ListClustersRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Cluster"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListClustersResponse, Cluster> ListClustersAsync(string projectId, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListClustersAsync(new ListClustersRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="filter">
/// Optional. A filter constraining the clusters to list. Filters are
/// case-sensitive and have the following syntax:
///
/// field = value [AND [field = value]] ...
///
/// where **field** is one of `status.state`, `clusterName`, or `labels.[KEY]`,
/// and `[KEY]` is a label key. **value** can be `*` to match all values.
/// `status.state` can be one of the following: `ACTIVE`, `INACTIVE`,
/// `CREATING`, `RUNNING`, `ERROR`, `DELETING`, or `UPDATING`. `ACTIVE`
/// contains the `CREATING`, `UPDATING`, and `RUNNING` states. `INACTIVE`
/// contains the `DELETING` and `ERROR` states.
/// `clusterName` is the name of the cluster provided at creation time.
/// Only the logical `AND` operator is supported; space-separated items are
/// treated as having an implicit `AND` operator.
///
/// Example filter:
///
/// status.state = ACTIVE AND clusterName = mycluster
/// AND labels.env = staging AND labels.starred = *
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Cluster"/> resources.</returns>
public virtual gax::PagedEnumerable<ListClustersResponse, Cluster> ListClusters(string projectId, string region, string filter, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListClusters(new ListClustersRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
Filter = filter ?? "",
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="filter">
/// Optional. A filter constraining the clusters to list. Filters are
/// case-sensitive and have the following syntax:
///
/// field = value [AND [field = value]] ...
///
/// where **field** is one of `status.state`, `clusterName`, or `labels.[KEY]`,
/// and `[KEY]` is a label key. **value** can be `*` to match all values.
/// `status.state` can be one of the following: `ACTIVE`, `INACTIVE`,
/// `CREATING`, `RUNNING`, `ERROR`, `DELETING`, or `UPDATING`. `ACTIVE`
/// contains the `CREATING`, `UPDATING`, and `RUNNING` states. `INACTIVE`
/// contains the `DELETING` and `ERROR` states.
/// `clusterName` is the name of the cluster provided at creation time.
/// Only the logical `AND` operator is supported; space-separated items are
/// treated as having an implicit `AND` operator.
///
/// Example filter:
///
/// status.state = ACTIVE AND clusterName = mycluster
/// AND labels.env = staging AND labels.starred = *
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Cluster"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListClustersResponse, Cluster> ListClustersAsync(string projectId, string region, string filter, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListClustersAsync(new ListClustersRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
Filter = filter ?? "",
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata> DiagnoseCluster(DiagnoseClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>> DiagnoseClusterAsync(DiagnoseClusterRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>> DiagnoseClusterAsync(DiagnoseClusterRequest request, st::CancellationToken cancellationToken) =>
DiagnoseClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>DiagnoseCluster</c>.</summary>
public virtual lro::OperationsClient DiagnoseClusterOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>DiagnoseCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata> PollOnceDiagnoseCluster(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DiagnoseClusterOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>DiagnoseCluster</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>> PollOnceDiagnoseClusterAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DiagnoseClusterOperationsClient, callSettings);
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata> DiagnoseCluster(string projectId, string region, string clusterName, gaxgrpc::CallSettings callSettings = null) =>
DiagnoseCluster(new DiagnoseClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
}, callSettings);
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>> DiagnoseClusterAsync(string projectId, string region, string clusterName, gaxgrpc::CallSettings callSettings = null) =>
DiagnoseClusterAsync(new DiagnoseClusterRequest
{
ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
ClusterName = gax::GaxPreconditions.CheckNotNullOrEmpty(clusterName, nameof(clusterName)),
}, callSettings);
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="projectId">
/// Required. The ID of the Google Cloud Platform project that the cluster
/// belongs to.
/// </param>
/// <param name="region">
/// Required. The Dataproc region in which to handle the request.
/// </param>
/// <param name="clusterName">
/// Required. The cluster name.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>> DiagnoseClusterAsync(string projectId, string region, string clusterName, st::CancellationToken cancellationToken) =>
DiagnoseClusterAsync(projectId, region, clusterName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ClusterController client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// The ClusterControllerService provides methods to manage clusters
/// of Compute Engine instances.
/// </remarks>
public sealed partial class ClusterControllerClientImpl : ClusterControllerClient
{
private readonly gaxgrpc::ApiCall<CreateClusterRequest, lro::Operation> _callCreateCluster;
private readonly gaxgrpc::ApiCall<UpdateClusterRequest, lro::Operation> _callUpdateCluster;
private readonly gaxgrpc::ApiCall<DeleteClusterRequest, lro::Operation> _callDeleteCluster;
private readonly gaxgrpc::ApiCall<GetClusterRequest, Cluster> _callGetCluster;
private readonly gaxgrpc::ApiCall<ListClustersRequest, ListClustersResponse> _callListClusters;
private readonly gaxgrpc::ApiCall<DiagnoseClusterRequest, lro::Operation> _callDiagnoseCluster;
/// <summary>
/// Constructs a client wrapper for the ClusterController service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ClusterControllerSettings"/> used within this client.</param>
public ClusterControllerClientImpl(ClusterController.ClusterControllerClient grpcClient, ClusterControllerSettings settings)
{
GrpcClient = grpcClient;
ClusterControllerSettings effectiveSettings = settings ?? ClusterControllerSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
CreateClusterOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateClusterOperationsSettings);
UpdateClusterOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.UpdateClusterOperationsSettings);
DeleteClusterOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.DeleteClusterOperationsSettings);
DiagnoseClusterOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.DiagnoseClusterOperationsSettings);
_callCreateCluster = clientHelper.BuildApiCall<CreateClusterRequest, lro::Operation>(grpcClient.CreateClusterAsync, grpcClient.CreateCluster, effectiveSettings.CreateClusterSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("region", request => request.Region);
Modify_ApiCall(ref _callCreateCluster);
Modify_CreateClusterApiCall(ref _callCreateCluster);
_callUpdateCluster = clientHelper.BuildApiCall<UpdateClusterRequest, lro::Operation>(grpcClient.UpdateClusterAsync, grpcClient.UpdateCluster, effectiveSettings.UpdateClusterSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("cluster_name", request => request.ClusterName);
Modify_ApiCall(ref _callUpdateCluster);
Modify_UpdateClusterApiCall(ref _callUpdateCluster);
_callDeleteCluster = clientHelper.BuildApiCall<DeleteClusterRequest, lro::Operation>(grpcClient.DeleteClusterAsync, grpcClient.DeleteCluster, effectiveSettings.DeleteClusterSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("cluster_name", request => request.ClusterName);
Modify_ApiCall(ref _callDeleteCluster);
Modify_DeleteClusterApiCall(ref _callDeleteCluster);
_callGetCluster = clientHelper.BuildApiCall<GetClusterRequest, Cluster>(grpcClient.GetClusterAsync, grpcClient.GetCluster, effectiveSettings.GetClusterSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("cluster_name", request => request.ClusterName);
Modify_ApiCall(ref _callGetCluster);
Modify_GetClusterApiCall(ref _callGetCluster);
_callListClusters = clientHelper.BuildApiCall<ListClustersRequest, ListClustersResponse>(grpcClient.ListClustersAsync, grpcClient.ListClusters, effectiveSettings.ListClustersSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("region", request => request.Region);
Modify_ApiCall(ref _callListClusters);
Modify_ListClustersApiCall(ref _callListClusters);
_callDiagnoseCluster = clientHelper.BuildApiCall<DiagnoseClusterRequest, lro::Operation>(grpcClient.DiagnoseClusterAsync, grpcClient.DiagnoseCluster, effectiveSettings.DiagnoseClusterSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("region", request => request.Region).WithGoogleRequestParam("cluster_name", request => request.ClusterName);
Modify_ApiCall(ref _callDiagnoseCluster);
Modify_DiagnoseClusterApiCall(ref _callDiagnoseCluster);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateClusterApiCall(ref gaxgrpc::ApiCall<CreateClusterRequest, lro::Operation> call);
partial void Modify_UpdateClusterApiCall(ref gaxgrpc::ApiCall<UpdateClusterRequest, lro::Operation> call);
partial void Modify_DeleteClusterApiCall(ref gaxgrpc::ApiCall<DeleteClusterRequest, lro::Operation> call);
partial void Modify_GetClusterApiCall(ref gaxgrpc::ApiCall<GetClusterRequest, Cluster> call);
partial void Modify_ListClustersApiCall(ref gaxgrpc::ApiCall<ListClustersRequest, ListClustersResponse> call);
partial void Modify_DiagnoseClusterApiCall(ref gaxgrpc::ApiCall<DiagnoseClusterRequest, lro::Operation> call);
partial void OnConstruction(ClusterController.ClusterControllerClient grpcClient, ClusterControllerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ClusterController client</summary>
public override ClusterController.ClusterControllerClient GrpcClient { get; }
partial void Modify_CreateClusterRequest(ref CreateClusterRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateClusterRequest(ref UpdateClusterRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteClusterRequest(ref DeleteClusterRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetClusterRequest(ref GetClusterRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListClustersRequest(ref ListClustersRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DiagnoseClusterRequest(ref DiagnoseClusterRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>The long-running operations client for <c>CreateCluster</c>.</summary>
public override lro::OperationsClient CreateClusterOperationsClient { get; }
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Cluster, ClusterOperationMetadata> CreateCluster(CreateClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClusterRequest(ref request, ref callSettings);
return new lro::Operation<Cluster, ClusterOperationMetadata>(_callCreateCluster.Sync(request, callSettings), CreateClusterOperationsClient);
}
/// <summary>
/// Creates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> CreateClusterAsync(CreateClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClusterRequest(ref request, ref callSettings);
return new lro::Operation<Cluster, ClusterOperationMetadata>(await _callCreateCluster.Async(request, callSettings).ConfigureAwait(false), CreateClusterOperationsClient);
}
/// <summary>The long-running operations client for <c>UpdateCluster</c>.</summary>
public override lro::OperationsClient UpdateClusterOperationsClient { get; }
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Cluster, ClusterOperationMetadata> UpdateCluster(UpdateClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateClusterRequest(ref request, ref callSettings);
return new lro::Operation<Cluster, ClusterOperationMetadata>(_callUpdateCluster.Sync(request, callSettings), UpdateClusterOperationsClient);
}
/// <summary>
/// Updates a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Cluster, ClusterOperationMetadata>> UpdateClusterAsync(UpdateClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateClusterRequest(ref request, ref callSettings);
return new lro::Operation<Cluster, ClusterOperationMetadata>(await _callUpdateCluster.Async(request, callSettings).ConfigureAwait(false), UpdateClusterOperationsClient);
}
/// <summary>The long-running operations client for <c>DeleteCluster</c>.</summary>
public override lro::OperationsClient DeleteClusterOperationsClient { get; }
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<wkt::Empty, ClusterOperationMetadata> DeleteCluster(DeleteClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteClusterRequest(ref request, ref callSettings);
return new lro::Operation<wkt::Empty, ClusterOperationMetadata>(_callDeleteCluster.Sync(request, callSettings), DeleteClusterOperationsClient);
}
/// <summary>
/// Deletes a cluster in a project. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<wkt::Empty, ClusterOperationMetadata>> DeleteClusterAsync(DeleteClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteClusterRequest(ref request, ref callSettings);
return new lro::Operation<wkt::Empty, ClusterOperationMetadata>(await _callDeleteCluster.Async(request, callSettings).ConfigureAwait(false), DeleteClusterOperationsClient);
}
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Cluster GetCluster(GetClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetClusterRequest(ref request, ref callSettings);
return _callGetCluster.Sync(request, callSettings);
}
/// <summary>
/// Gets the resource representation for a cluster in a project.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Cluster> GetClusterAsync(GetClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetClusterRequest(ref request, ref callSettings);
return _callGetCluster.Async(request, callSettings);
}
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Cluster"/> resources.</returns>
public override gax::PagedEnumerable<ListClustersResponse, Cluster> ListClusters(ListClustersRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListClustersRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListClustersRequest, ListClustersResponse, Cluster>(_callListClusters, request, callSettings);
}
/// <summary>
/// Lists all regions/{region}/clusters in a project alphabetically.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Cluster"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListClustersResponse, Cluster> ListClustersAsync(ListClustersRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListClustersRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListClustersRequest, ListClustersResponse, Cluster>(_callListClusters, request, callSettings);
}
/// <summary>The long-running operations client for <c>DiagnoseCluster</c>.</summary>
public override lro::OperationsClient DiagnoseClusterOperationsClient { get; }
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata> DiagnoseCluster(DiagnoseClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DiagnoseClusterRequest(ref request, ref callSettings);
return new lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>(_callDiagnoseCluster.Sync(request, callSettings), DiagnoseClusterOperationsClient);
}
/// <summary>
/// Gets cluster diagnostic information. The returned
/// [Operation.metadata][google.longrunning.Operation.metadata] will be
/// [ClusterOperationMetadata](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).
/// After the operation completes,
/// [Operation.response][google.longrunning.Operation.response]
/// contains
/// [DiagnoseClusterResults](https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults).
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>> DiagnoseClusterAsync(DiagnoseClusterRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DiagnoseClusterRequest(ref request, ref callSettings);
return new lro::Operation<DiagnoseClusterResults, ClusterOperationMetadata>(await _callDiagnoseCluster.Async(request, callSettings).ConfigureAwait(false), DiagnoseClusterOperationsClient);
}
}
public partial class ListClustersRequest : gaxgrpc::IPageRequest
{
}
public partial class ListClustersResponse : gaxgrpc::IPageResponse<Cluster>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Cluster> GetEnumerator() => Clusters.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public static partial class ClusterController
{
public partial class ClusterControllerClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as
/// this client.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClient() =>
new lro::Operations.OperationsClient(CallInvoker);
}
}
}
| 63.276156 | 585 | 0.668631 | [
"Apache-2.0"
] | Global19/google-cloud-dotnet | apis/Google.Cloud.Dataproc.V1/Google.Cloud.Dataproc.V1/ClusterControllerClient.g.cs | 104,026 | C# |
namespace OmniXaml.Metadata
{
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Metadata
{
public static bool IsEmpty(Metadata metadata)
{
return typeof(Metadata).GetRuntimeProperties().All(info => info.GetValue(metadata) == null);
}
public DependencyRegistrations PropertyDependencies { get; set; }
public void SetMemberDependency(string property, string dependsOn)
{
PropertyDependencies.Add(new DependencyRegistration(property, dependsOn));
}
public IEnumerable<string> GetMemberDependencies(string name)
{
if (PropertyDependencies == null)
{
return new List<string>();
}
return from dependency in PropertyDependencies
where dependency.PropertyName == name
select dependency.DependsOn;
}
public string RuntimePropertyName { get; set; }
public string ContentProperty { get; set; }
public FragmentLoaderInfo FragmentLoaderInfo { get; set; }
public bool IsNamescope { get; set; }
protected bool Equals(Metadata other)
{
return Equals(PropertyDependencies, other.PropertyDependencies) && string.Equals(RuntimePropertyName, other.RuntimePropertyName);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return Equals((Metadata)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((PropertyDependencies != null ? PropertyDependencies.GetHashCode() : 0) * 397) ^ (RuntimePropertyName != null ? RuntimePropertyName.GetHashCode() : 0);
}
}
}
} | 29.774648 | 175 | 0.566698 | [
"MIT"
] | JPTIZ/OmniXAML | OmniXaml/Metadata/Metadata.cs | 2,114 | C# |
namespace Musoq.Evaluator.Visitors
{
public interface IToCSharpTranslationExpressionVisitor : IScopeAwareExpressionVisitor
{
void SetQueryIdentifier(string identifier);
MethodAccessType SetMethodAccessType(MethodAccessType type);
void IncrementMethodIdentifier();
}
} | 27.818182 | 89 | 0.761438 | [
"MIT"
] | JTOne123/Musoq | Musoq.Evaluator/Visitors/IToCSharpTranslationExpressionVisitor.cs | 308 | C# |
using System.Threading.Tasks;
using Abp.Configuration.Startup;
using test.Sessions;
using Microsoft.AspNetCore.Mvc;
namespace test.Web.Views.Shared.Components.RightNavbarUserArea
{
public class RightNavbarUserAreaViewComponent : testViewComponent
{
private readonly ISessionAppService _sessionAppService;
private readonly IMultiTenancyConfig _multiTenancyConfig;
public RightNavbarUserAreaViewComponent(
ISessionAppService sessionAppService,
IMultiTenancyConfig multiTenancyConfig)
{
_sessionAppService = sessionAppService;
_multiTenancyConfig = multiTenancyConfig;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = new RightNavbarUserAreaViewModel
{
LoginInformations = await _sessionAppService.GetCurrentLoginInformations(),
IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled,
};
return View(model);
}
}
}
| 30.617647 | 91 | 0.68684 | [
"MIT"
] | pixelapocalypseuk/aspnetboilerplatetest | aspnet-core/src/test.Web.Mvc/Views/Shared/Components/RightNavbarUserArea/RightNavbarUserAreaViewComponent.cs | 1,043 | 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.
//
//
//
// Contents: Full text implementation of the specialized text line representing
// state of line up to the point where line break may occur
//
// Spec: Text Formatting API.doc
//
//
using System;
using System.Security;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using MS.Internal.PresentationCore;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace MS.Internal.TextFormatting
{
/// <summary>
/// Full text implementation of the specialized text line representing state
/// of line up to the point where line break may occur. Unlike a more tangible
/// type like text line , breakpoint could not draw or performs hit-testing
/// operation. It could only reflect formatting result back to the client.
/// </summary>
internal sealed class FullTextBreakpoint : TextBreakpoint
{
private TextMetrics _metrics; // full text metrics
private SecurityCriticalDataForSet<IntPtr> _ploline; // native object representing this break
private SecurityCriticalDataForSet<IntPtr> _penaltyResource; // unsafe handle to the internal factors used to determines penalty of the break. By default, the lifetime of this resource is managed by _ploline.
private bool _isDisposed; // flag indicates whether this object is disposed
private bool _isLineTruncated; // flag indicates whether the line produced at this breakpoint is truncated.
/// <summary>
/// Construct a list of potential breakpoints starting from the specified firstCharIndex
/// </summary>
/// <param name="paragraphCache">cache of paragraph content of all possible breaks within</param>
/// <param name="firstCharIndex">index to first character where formatting starts</param>
/// <param name="maxLineWidth">max format ideal width of the line being built</param>
/// <param name="previousLineBreak">LineBreak property of the previous text line, or null if this is the first line in the paragraph</param>
/// <param name="penaltyRestriction">constraint on what breakpoint is returned based on its implied calculated penalty</param>
/// <param name="bestFitIndex">index of the best fit breakpoint in the returned collection</param>
/// <returns>a list of potential breakpoints starting from firstCharIndex</returns>
internal static IList<TextBreakpoint> CreateMultiple(
TextParagraphCache paragraphCache,
int firstCharIndex,
int maxLineWidth,
TextLineBreak previousLineBreak,
IntPtr penaltyRestriction,
out int bestFitIndex
)
{
Invariant.Assert(paragraphCache != null);
// grab full text state from paragraph cache
FullTextState fullText = paragraphCache.FullText;
Invariant.Assert(fullText != null);
FormatSettings settings = fullText.TextStore.Settings;
Invariant.Assert(settings != null);
// update formatting parameters at line start
settings.UpdateSettingsForCurrentLine(
maxLineWidth,
previousLineBreak,
(firstCharIndex == fullText.TextStore.CpFirst)
);
Invariant.Assert(settings.Formatter != null);
// acquiring LS context
TextFormatterContext context = settings.Formatter.AcquireContext(fullText, IntPtr.Zero);
IntPtr previousBreakRecord = IntPtr.Zero;
if (settings.PreviousLineBreak != null)
previousBreakRecord = settings.PreviousLineBreak.BreakRecord.Value;
// need not consider marker as tab since marker does not affect line metrics and it wasnt drawn.
fullText.SetTabs(context);
LsBreaks lsbreaks = new LsBreaks();
LsErr lserr = context.CreateBreaks(
fullText.GetBreakpointInternalCp(firstCharIndex),
previousBreakRecord,
paragraphCache.Ploparabreak.Value, // para breaking session
penaltyRestriction,
ref lsbreaks,
out bestFitIndex
);
// get the exception in context before it is released
Exception callbackException = context.CallbackException;
// release the context
context.Release();
if(lserr != LsErr.None)
{
if(callbackException != null)
{
// rethrow exception thrown in callbacks
throw callbackException;
}
else
{
// throw with LS error codes
TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.CreateBreaksFailure, lserr), lserr);
}
}
// keep context alive at least till here
GC.KeepAlive(context);
TextBreakpoint[] breakpoints = new TextBreakpoint[lsbreaks.cBreaks];
for (int i = 0; i < lsbreaks.cBreaks; i++)
{
breakpoints[i] = new FullTextBreakpoint(
fullText,
firstCharIndex,
maxLineWidth,
ref lsbreaks,
i // the current break
);
}
return breakpoints;
}
/// <summary>
/// Construct breakpoint from full text info
/// </summary>
private FullTextBreakpoint(
FullTextState fullText,
int firstCharIndex,
int maxLineWidth,
ref LsBreaks lsbreaks,
int breakIndex
) : this()
{
// According to antons: PTS only uses the width of a feasible break to avoid
// clipping in subpage. At the moment, there is no good solution as of how
// PTS client would be able to compute this width efficiently using LS.
// The work around - although could be conceived would simply be too slow.
// The width should therefore be set to the paragraph width for the time being.
//
// Client of text formatter would simply pass the value of TextBreakpoint.Width
// back to PTS pfnFormatLineVariants call.
LsLineWidths lineWidths = new LsLineWidths();
lineWidths.upLimLine = maxLineWidth;
lineWidths.upStartMainText = fullText.TextStore.Settings.TextIndent;
lineWidths.upStartMarker = lineWidths.upStartMainText;
lineWidths.upStartTrailing = lineWidths.upLimLine;
lineWidths.upMinStartTrailing = lineWidths.upStartTrailing;
// construct the correspondent text metrics
unsafe
{
_metrics.Compute(
fullText,
firstCharIndex,
maxLineWidth,
null, // collapsingSymbol
ref lineWidths,
&lsbreaks.plslinfoArray[breakIndex]
);
_ploline = new SecurityCriticalDataForSet<IntPtr>(lsbreaks.pplolineArray[breakIndex]);
// keep the line penalty handle
_penaltyResource = new SecurityCriticalDataForSet<IntPtr>(lsbreaks.plinepenaltyArray[breakIndex]);
if (lsbreaks.plslinfoArray[breakIndex].fForcedBreak != 0)
_isLineTruncated = true;
}
}
/// <summary>
/// Empty private constructor
/// </summary>
private FullTextBreakpoint()
{
_metrics = new TextMetrics();
}
/// <summary>
/// Finalizing the break
/// </summary>
~FullTextBreakpoint()
{
Dispose(false);
}
/// <summary>
/// Disposing LS unmanaged memory for text line
/// </summary>
protected override void Dispose(bool disposing)
{
if(_ploline.Value != IntPtr.Zero)
{
UnsafeNativeMethods.LoDisposeLine(_ploline.Value, !disposing);
_ploline.Value = IntPtr.Zero;
_penaltyResource.Value = IntPtr.Zero;
_isDisposed = true;
GC.KeepAlive(this);
}
}
#region TextBreakpoint
/// <summary>
/// Client to acquire a state at the point where breakpoint is determined by line breaking process;
/// can be null when the line ends by the ending of the paragraph. Client may pass this
/// value back to TextFormatter as an input argument to TextFormatter.FormatParagraphBreakpoints when
/// formatting the next set of breakpoints within the same paragraph.
/// </summary>
public override TextLineBreak GetTextLineBreak()
{
if (_isDisposed)
{
throw new ObjectDisposedException(SR.Get(SRID.TextBreakpointHasBeenDisposed));
}
return _metrics.GetTextLineBreak(_ploline.Value);
}
/// <summary>
/// Client to get the handle of the internal factors that are used to determine penalty of this breakpoint.
/// </summary>
/// <remarks>
/// Calling this method means that the client will now manage the lifetime of this unmanaged resource themselves using unsafe penalty handler.
/// We would make a correspondent call to notify our unmanaged wrapper to release them from duty of managing this
/// resource.
/// </remarks>
internal override SecurityCriticalDataForSet<IntPtr> GetTextPenaltyResource()
{
if (_isDisposed)
{
throw new ObjectDisposedException(SR.Get(SRID.TextBreakpointHasBeenDisposed));
}
LsErr lserr = UnsafeNativeMethods.LoRelievePenaltyResource(_ploline.Value);
if (lserr != LsErr.None)
{
TextFormatterContext.ThrowExceptionFromLsError(SR.Get(SRID.RelievePenaltyResourceFailure, lserr), lserr);
}
return _penaltyResource;
}
/// <summary>
/// Client to get a Boolean flag indicating whether the line is truncated in the
/// middle of a word. This flag is set only when TextParagraphProperties.TextWrapping
/// is set to TextWrapping.Wrap and a single word is longer than the formatting
/// paragraph width. In such situation, TextFormatter truncates the line in the middle
/// of the word to honor the desired behavior specified by TextWrapping.Wrap setting.
/// </summary>
public override bool IsTruncated
{
get { return _isLineTruncated; }
}
#endregion
#region TextMetrics
/// <summary>
/// Client to get the number of text source positions of this line
/// </summary>
public override int Length
{
get { return _metrics.Length; }
}
/// <summary>
/// Client to get the number of characters following the last character
/// of the line that may trigger reformatting of the current line.
/// </summary>
public override int DependentLength
{
get { return _metrics.DependentLength; }
}
/// <summary>
/// Client to get the number of newline characters at line end
/// </summary>
public override int NewlineLength
{
get { return _metrics.NewlineLength; }
}
/// <summary>
/// Client to get distance from paragraph start to line start
/// </summary>
public override double Start
{
get { return _metrics.Start; }
}
/// <summary>
/// Client to get the total width of this line
/// </summary>
public override double Width
{
get { return _metrics.Width; }
}
/// <summary>
/// Client to get the total width of this line including width of whitespace characters at the end of the line.
/// </summary>
public override double WidthIncludingTrailingWhitespace
{
get { return _metrics.WidthIncludingTrailingWhitespace; }
}
/// <summary>
/// Client to get the height of the line
/// </summary>
public override double Height
{
get { return _metrics.Height; }
}
/// <summary>
/// Client to get the height of the text (or other content) in the line; this property may differ from the Height
/// property if the client specified the line height
/// </summary>
public override double TextHeight
{
get { return _metrics.TextHeight; }
}
/// <summary>
/// Client to get the distance from top to baseline of this text line
/// </summary>
public override double Baseline
{
get { return _metrics.Baseline; }
}
/// <summary>
/// Client to get the distance from the top of the text (or other content) to the baseline of this text line;
/// this property may differ from the Baseline property if the client specified the line height
/// </summary>
public override double TextBaseline
{
get { return _metrics.TextBaseline; }
}
/// <summary>
/// Client to get the distance from the before edge of line height
/// to the baseline of marker of the line if any.
/// </summary>
public override double MarkerBaseline
{
get { return _metrics.MarkerBaseline; }
}
/// <summary>
/// Client to get the overall height of the list items marker of the line if any.
/// </summary>
public override double MarkerHeight
{
get { return _metrics.MarkerHeight; }
}
#endregion
}
}
| 37.209476 | 219 | 0.582535 | [
"MIT"
] | 00mjk/wpf | src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/TextFormatting/FullTextBreakpoint.cs | 14,921 | C# |
#region license
// Copyright (c) HatTrick Labs, LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at https://github.com/HatTrickLabs/db-ex
#endregion
namespace HatTrick.DbEx.Sql.Expression
{
public class NullableByteArraySelectExpression : SelectExpression<byte[]>,
NullableByteArrayElement
{
public NullableByteArraySelectExpression(IExpressionElement<byte[]> expression)
: base(expression)
{
}
#region as
public NullableByteArrayElement As(string alias)
{
Alias = alias;
return this;
}
#endregion
#region order by
OrderByExpression AnyElement.Asc => throw new DbExpressionException("Select expressions cannot be used in Order By clauses.");
OrderByExpression AnyElement.Desc => throw new DbExpressionException("Select expressions cannot be used in Order By clauses.");
#endregion
}
}
| 33.911111 | 135 | 0.698558 | [
"Apache-2.0"
] | HatTrickLabs/dbExpression | src/HatTrick.DbEx.Sql/Expression/_Select/NullableByteArraySelectExpression.cs | 1,528 | C# |
/********************************************************
* *
* Copyright (C) Microsoft. All rights reserved. *
* *
*********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Partner.CSP.Api.V1.Samples.DataModels
{
public class UsageType
{
public string entitlement_id { get; set; }
public string usage_start_time { get; set; }
public string usage_end_time { get; set; }
public string object_type { get; set; }
public string meter_name { get; set; }
public string meter_category { get; set; }
public string unit { get; set; }
public string instance_data { get; set; }
public string meter_id { get; set; }
public InfoField info_fields { get; set; }
public double quantity { get; set; }
public string meter_region { get; set; }
public string meter_sub_category { get; set; }
}
}
| 36.9375 | 59 | 0.5 | [
"MIT"
] | PartnerCenterSamples/Commerce-API-DotNet | DataModels/UsageType.cs | 1,184 | C# |
/// If you're new to Strange, start with MyFirstProject.
/// If you're interested in how Signals work, return here once you understand the
/// rest of Strange. This example shows how Signals differ from the default
/// EventDispatcher.
/// All comments from MyFirstProjectContext have been removed and replaced by comments focusing
/// on the differences
using System;
using UnityEngine;
using strange.extensions.context.api;
using strange.extensions.context.impl;
using strange.extensions.dispatcher.eventdispatcher.api;
using strange.extensions.dispatcher.eventdispatcher.impl;
using strange.extensions.command.api;
using strange.extensions.command.impl;
namespace strange.examples.signals
{
public class SignalsContext : MVCSContext
{
public SignalsContext (MonoBehaviour view) : base(view)
{
}
public SignalsContext (MonoBehaviour view, ContextStartupFlags flags) : base(view, flags)
{
}
// Unbind the default EventCommandBinder and rebind the SignalCommandBinder
protected override void addCoreComponents()
{
base.addCoreComponents();
injectionBinder.Unbind<ICommandBinder>();
injectionBinder.Bind<ICommandBinder>().To<SignalCommandBinder>().ToSingleton();
}
// Override Start so that we can fire the StartSignal
override public IContext Start()
{
base.Start();
StartSignal startSignal= (StartSignal)injectionBinder.GetInstance<StartSignal>();
startSignal.Dispatch();
return this;
}
protected override void mapBindings()
{
injectionBinder.Bind<IExampleModel>().To<ExampleModel>().ToSingleton();
injectionBinder.Bind<IExampleService>().To<ExampleService>().ToSingleton();
mediationBinder.Bind<ExampleView>().To<ExampleMediator>();
commandBinder.Bind<CallWebServiceSignal>().To<CallWebServiceCommand>();
//StartSignal is now fired instead of the START event.
//Note how we've bound it "Once". This means that the mapping goes away as soon as the command fires.
commandBinder.Bind<StartSignal>().To<StartCommand>().Once ();
//In MyFirstProject, there's are SCORE_CHANGE and FULFILL_SERVICE_REQUEST Events.
//Here we change that to a Signal. The Signal isn't bound to any Command,
//so we map it as an injection so a Command can fire it, and a Mediator can receive it
injectionBinder.Bind<ScoreChangedSignal>().ToSingleton();
injectionBinder.Bind<FulfillWebServiceRequestSignal>().ToSingleton();
}
}
}
| 34.069444 | 104 | 0.749694 | [
"MIT"
] | czarzappy/BookClub | Unity/Assets/Scripts/signalsproject/SignalsContext.cs | 2,453 | C# |
//******************************************************************************************************
// AdditionalUserFieldValue.cs - Gbtc
//
// Copyright © 2021, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 06/23/2021 - Billy Ernest
// Generated original version of source code.
//
//******************************************************************************************************
using GSF.Data.Model;
using GSF.Security.Model;
using System;
namespace SystemCenter.Model
{
[UseEscapedName, ConfigFileTableNamePrefix("SecurityProvider", "TableNamePrefix"), TableName("AdditionalUserFieldValue")]
[AllowSearch]
[PatchRoles("Administrator, Transmission SME")]
[PostRoles("Administrator, Transmission SME")]
[DeleteRoles("Administrator, Transmission SME")]
[SettingsCategory("SecurityProvider")]
public class AdditionalUserFieldValue
{
[PrimaryKey(true)]
public int ID { get; set; }
[ParentKey(typeof(UserAccount))]
public Guid UserAccountID { get; set; }
[ParentKey(typeof(AdditionalUserField))]
public int AdditionalUserFieldID { get; set; }
public string Value { get; set; }
}
} | 45.195652 | 125 | 0.612795 | [
"MIT"
] | GridProtectionAlliance/openXDA | Source/Libraries/openXDA.Model/SystemCenter/UserAccount/AdditionalUserFieldValue.cs | 2,082 | C# |
using ValueOf;
namespace Rusell.Tickets.Domain;
public class TicketSeatPrice : ValueOf<decimal, TicketSeatPrice>
{
public static implicit operator decimal(TicketSeatPrice ticketSeatPrice) => ticketSeatPrice.Value;
public static implicit operator TicketSeatPrice(decimal ticketSeatPrice) => From(ticketSeatPrice);
}
| 32.5 | 102 | 0.812308 | [
"MIT"
] | cantte/Rusell.Api | src/Tickets/Domain/TicketSeatPrice.cs | 325 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the machinelearning-2014-12-12.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.MachineLearning.Model
{
/// <summary>
/// Amazon ML returns the following elements.
/// </summary>
public partial class DescribeTagsResponse : AmazonWebServiceResponse
{
private string _resourceId;
private TaggableResourceType _resourceType;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Gets and sets the property ResourceId.
/// <para>
/// The ID of the tagged ML object.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string ResourceId
{
get { return this._resourceId; }
set { this._resourceId = value; }
}
// Check to see if ResourceId property is set
internal bool IsSetResourceId()
{
return this._resourceId != null;
}
/// <summary>
/// Gets and sets the property ResourceType.
/// <para>
/// The type of the tagged ML object.
/// </para>
/// </summary>
public TaggableResourceType ResourceType
{
get { return this._resourceType; }
set { this._resourceType = value; }
}
// Check to see if ResourceType property is set
internal bool IsSetResourceType()
{
return this._resourceType != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A list of tags associated with the ML object.
/// </para>
/// </summary>
[AWSProperty(Max=100)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 28.927835 | 113 | 0.593728 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/MachineLearning/Generated/Model/DescribeTagsResponse.cs | 2,806 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityCollectionResponse.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type WorkbookRangeFormatBordersCollectionResponse.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class WorkbookRangeFormatBordersCollectionResponse
{
/// <summary>
/// Gets or sets the <see cref="IWorkbookRangeFormatBordersCollectionPage"/> value.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)]
public IWorkbookRangeFormatBordersCollectionPage Value { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
}
}
| 41.970588 | 153 | 0.626489 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookRangeFormatBordersCollectionResponse.cs | 1,427 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.ServiceBus.Bindings;
using Microsoft.Azure.ServiceBus;
using Moq;
using Xunit;
namespace Microsoft.Azure.WebJobs.ServiceBus.UnitTests.Bindings
{
public class ServiceBusAttributeBindingProviderTests
{
private readonly Mock<MessagingProvider> _mockMessagingProvider;
private readonly ServiceBusAttributeBindingProvider _provider;
public ServiceBusAttributeBindingProviderTests()
{
Mock<INameResolver> mockResolver = new Mock<INameResolver>(MockBehavior.Strict);
ServiceBusConfiguration config = new ServiceBusConfiguration();
_mockMessagingProvider = new Mock<MessagingProvider>(MockBehavior.Strict, config);
config.MessagingProvider = _mockMessagingProvider.Object;
_provider = new ServiceBusAttributeBindingProvider(mockResolver.Object, config);
}
[Fact]
public async Task TryCreateAsync_AccountOverride_OverrideIsApplied()
{
ParameterInfo parameter = GetType().GetMethod("TestJob_AccountOverride").GetParameters()[0];
BindingProviderContext context = new BindingProviderContext(parameter, new Dictionary<string, Type>(), CancellationToken.None);
IBinding binding = await _provider.TryCreateAsync(context);
Assert.NotNull(binding);
}
[Fact]
public async Task TryCreateAsync_DefaultAccount()
{
ParameterInfo parameter = GetType().GetMethod("TestJob").GetParameters()[0];
BindingProviderContext context = new BindingProviderContext(parameter, new Dictionary<string, Type>(), CancellationToken.None);
IBinding binding = await _provider.TryCreateAsync(context);
Assert.NotNull(binding);
}
public static void TestJob_AccountOverride(
[ServiceBusAttribute("test"),
ServiceBusAccount("testaccount")] out Message message)
{
message = new Message();
}
public static void TestJob(
[ServiceBusAttribute("test")] out Message message)
{
message = new Message();
}
}
}
| 35.464789 | 139 | 0.690627 | [
"MIT"
] | Azure-App-Service/azure-webjobs-sdk | test/Microsoft.Azure.WebJobs.ServiceBus.UnitTests/Bindings/ServiceBusAttributeBindingProviderTests.cs | 2,520 | C# |
// Jeebs Rapid Application Development
// Copyright (c) bfren - licensed under https://mit.bfren.dev/2013
using Jeebs.Data.Mapping;
namespace Jeebs.WordPress.Data.Tables;
/// <summary>
/// Term Taxonomy Table
/// </summary>
public sealed record class TermTaxonomyTable : Table
{
/// <summary>
/// TermTaxonomyId
/// </summary>
public string Id =>
"term_taxonomy_id";
/// <summary>
/// TermId
/// </summary>
public string TermId =>
"term_id";
/// <summary>
/// Taxonomy
/// </summary>
public string Taxonomy =>
"taxonomy";
/// <summary>
/// Description
/// </summary>
public string Description =>
"description";
/// <summary>
/// ParentId
/// </summary>
public string ParentId =>
"parent";
/// <summary>
/// Count
/// </summary>
public string Count =>
"count";
/// <summary>
/// Create object
/// </summary>
/// <param name="prefix">Table prefix</param>
public TermTaxonomyTable(string prefix) : base($"{prefix}term_taxonomy") { }
}
| 17.872727 | 77 | 0.636826 | [
"MIT"
] | bfren/jeebs | src/Jeebs.WordPress.Data.Types/Tables/TermTaxonomyTable.cs | 985 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _01TrojanInvasion
{
class Program
{
static void Main(string[] args)
{
int wavesOfWarriors = int.Parse(Console.ReadLine());
List<int> plates = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
Stack<int> stackOfWarriors = null;
bool isDestroyed = false;
for (int wave = 1; wave <= wavesOfWarriors; wave++)
{
List<int> powerOfWarriors = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
stackOfWarriors = new Stack<int>(powerOfWarriors);
if (wave % 3 == 0)
{
int extraWave = int.Parse(Console.ReadLine());
plates.Add(extraWave);
}
while (stackOfWarriors.Count > 0 && plates.Count > 0)
{
int currentWarrior = stackOfWarriors.Peek();
if (currentWarrior > plates[0])
{
currentWarrior -= plates[0];
stackOfWarriors.Pop();
stackOfWarriors.Push(currentWarrior);
plates.RemoveAt(0);
}
else if (plates[0] > currentWarrior)
{
currentWarrior = stackOfWarriors.Pop();
plates[0] -= currentWarrior;
}
else
{
stackOfWarriors.Pop();
plates.RemoveAt(0);
}
if (plates.Count == 0)
{
isDestroyed = true;
break;
}
}
if (isDestroyed)
{
break;
}
}
if (plates.Count != 0)
{
Console.WriteLine("The Spartans successfully repulsed the Trojan attack.");
Console.WriteLine($"Plates left: {string.Join(", ", plates)}");
}
else
{
Console.WriteLine("The Trojans successfully destroyed the Spartan defense.");
Console.WriteLine($"Warriors left: {string.Join(", ", stackOfWarriors)}");
}
}
}
}
| 32.414634 | 93 | 0.421369 | [
"MIT"
] | stanislavstoyanov99/SoftUni-Software-Engineering | Advanced-and-OOP-with-C#/Exams/CSharp Advanced/CharpAdvancedRetakeExam16April19/01TrojanInvasion/Program.cs | 2,660 | C# |
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class Lesson1 : ModuleRules
{
public Lesson1(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
| 33.083333 | 129 | 0.72796 | [
"MIT"
] | gank498/C-UE4 | Lesson1/Lesson1.Build.cs | 794 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace LibwebpSharp.Native
{
public static class WebPDecoder
{
/// <summary>
/// Return the decoder's version number
/// </summary>
/// <returns>Hexadecimal using 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507</returns>
[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern int WebPGetDecoderVersion();
/// <summary>
/// This function will validate the WebP image header and retrieve the image height and width. Pointers *width and *height can be passed NULL if deemed irrelevant
/// </summary>
/// <param name="data">Pointer to WebP image data</param>
/// <param name="data_size">This is the size of the memory block pointed to by data containing the image data</param>
/// <param name="width">The range is limited currently from 1 to 16383</param>
/// <param name="height">The range is limited currently from 1 to 16383</param>
/// <returns>1 if success, otherwise error code returned in the case of (a) formatting error(s).</returns>
[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern int WebPGetInfo(IntPtr data, UInt32 data_size, ref int width, ref int height);
/// <summary>
/// Decodes WEBP images pointed to by *data and returns RGB samples into a pre-allocated buffer
/// </summary>
/// <param name="data">Pointer to WebP image data</param>
/// <param name="data_size">This is the size of the memory block pointed to by data containing the image data</param>
/// <param name="output_buffer">Pointer to decoded WebP image</param>
/// <param name="output_buffer_size">Size of allocated buffer</param>
/// <param name="output_stride">Specifies the distance between scanlines</param>
/// <returns>output_buffer if function succeeds; NULL otherwise</returns>
[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern IntPtr WebPDecodeRGBInto(IntPtr data, UInt32 data_size, IntPtr output_buffer, int output_buffer_size, int output_stride);
/// <summary>
/// Decodes WEBP images pointed to by *data and returns RGBA samples into a pre-allocated buffer
/// </summary>
/// <param name="data">Pointer to WebP image data</param>
/// <param name="data_size">This is the size of the memory block pointed to by data containing the image data</param>
/// <param name="output_buffer">Pointer to decoded WebP image</param>
/// <param name="output_buffer_size">Size of allocated buffer</param>
/// <param name="output_stride">Specifies the distance between scanlines</param>
/// <returns>output_buffer if function succeeds; NULL otherwise</returns>
[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern IntPtr WebPDecodeRGBAInto(IntPtr data, UInt32 data_size, IntPtr output_buffer, int output_buffer_size, int output_stride);
/// <summary>
/// Decodes WEBP images pointed to by *data and returns BGR samples into a pre-allocated buffer
/// </summary>
/// <param name="data">Pointer to WebP image data</param>
/// <param name="data_size">This is the size of the memory block pointed to by data containing the image data</param>
/// <param name="output_buffer">Pointer to decoded WebP image</param>
/// <param name="output_buffer_size">Size of allocated buffer</param>
/// <param name="output_stride">Specifies the distance between scanlines</param>
/// <returns>output_buffer if function succeeds; NULL otherwise</returns>
[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern IntPtr WebPDecodeBGRInto(IntPtr data, UInt32 data_size, IntPtr output_buffer, int output_buffer_size, int output_stride);
/// <summary>
/// Decodes WEBP images pointed to by *data and returns BGRA samples into a pre-allocated buffer
/// </summary>
/// <param name="data">Pointer to WebP image data</param>
/// <param name="data_size">This is the size of the memory block pointed to by data containing the image data</param>
/// <param name="output_buffer">Pointer to decoded WebP image</param>
/// <param name="output_buffer_size">Size of allocated buffer</param>
/// <param name="output_stride">Specifies the distance between scanlines</param>
/// <returns>output_buffer if function succeeds; NULL otherwise</returns>
[DllImport("libwebp", CharSet = CharSet.Auto)]
public static extern IntPtr WebPDecodeBGRAInto(IntPtr data, UInt32 data_size, IntPtr output_buffer, int output_buffer_size, int output_stride);
}
} | 64.039474 | 170 | 0.683172 | [
"MIT"
] | DavidS1998/MediFiler | Native.WebPDecoder.cs | 4,867 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using DevLab.JmesPath.Functions;
using Newtonsoft.Json.Linq;
namespace Microsoft.Health.Expressions
{
public class AddFunction : JmesPathFunction
{
public AddFunction()
: base("add", 2)
{
}
public override void Validate(params JmesPathFunctionArgument[] args)
{
base.Validate();
this.ValidatePositionalArgumentIsNumber(args, 0);
this.ValidatePositionalArgumentIsNumber(args, 1);
this.ValidateExpectedArgumentCount(MinArgumentCount, args.Length);
}
public override JToken Execute(params JmesPathFunctionArgument[] args)
{
if (args[0].Token.Type == JTokenType.Float || args[1].Token.Type == JTokenType.Float)
{
return new JValue(args[0].Token.Value<double>() + args[1].Token.Value<double>());
}
else
{
return new JValue(args[0].Token.Value<long>() + args[1].Token.Value<long>());
}
}
}
}
| 35.794872 | 100 | 0.516476 | [
"MIT"
] | MustAl-Du/IoMT | src/lib/Microsoft.Health.Expressions/AddFunction.cs | 1,396 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Memcache.V1Beta2.Snippets
{
using Google.Cloud.Memcache.V1Beta2;
using Google.LongRunning;
using System.Collections.Generic;
public sealed partial class GeneratedCloudMemcacheClientStandaloneSnippets
{
/// <summary>Snippet for ApplyParameters</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ApplyParametersResourceNames()
{
// Create client
CloudMemcacheClient cloudMemcacheClient = CloudMemcacheClient.Create();
// Initialize request argument(s)
InstanceName name = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]");
IEnumerable<string> nodeIds = new string[] { "", };
bool applyAll = false;
// Make the request
Operation<Instance, OperationMetadata> response = cloudMemcacheClient.ApplyParameters(name, nodeIds, applyAll);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = cloudMemcacheClient.PollOnceApplyParameters(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
}
}
}
| 44.508475 | 130 | 0.678218 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/memcache/v1beta2/google-cloud-memcache-v1beta2-csharp/Google.Cloud.Memcache.V1Beta2.StandaloneSnippets/CloudMemcacheClient.ApplyParametersResourceNamesSnippet.g.cs | 2,626 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_AdditionByte()
{
var test = new VectorBinaryOpTest__op_AdditionByte();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__op_AdditionByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Byte> _fld1;
public Vector256<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionByte testClass)
{
var result = _fld1 + _fld2;
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__op_AdditionByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
}
public VectorBinaryOpTest__op_AdditionByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<Byte>).GetMethod("op_Addition", new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 + _clsVar2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = op1 + op2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__op_AdditionByte();
var result = test._fld1 + test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 + _fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 + test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (byte)(left[0] + right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (byte)(left[i] + right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Addition<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 44.360248 | 184 | 0.600952 | [
"MIT"
] | 333fred/runtime | src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Addition.Byte.cs | 14,284 | C# |
// <copyright file="ROT13ViewModelTests.cs" company="APH Software">
// Copyright (c) Andrew Hawkins. All rights reserved.
// </copyright>
namespace Useful.Security.Cryptography.Tests
{
using Useful.Security.Cryptography.UI.ViewModels;
using Xunit;
public class ROT13ViewModelTests
{
[Theory]
[InlineData("Hello", "URYYB")]
public void Encrypt(string plaintext, string ciphertext)
{
Rot13ViewModel viewmodel = new();
viewmodel.Plaintext = plaintext;
viewmodel.Encrypt();
Assert.Equal(ciphertext, viewmodel.Ciphertext);
}
[Theory]
[InlineData("URYYB", "Hello")]
public void Decrypt(string plaintext, string ciphertext)
{
Rot13ViewModel viewmodel = new();
viewmodel.Ciphertext = ciphertext;
viewmodel.Decrypt();
Assert.Equal(plaintext, viewmodel.Plaintext);
}
[Fact]
public void CipherName()
{
Rot13ViewModel viewmodel = new();
Assert.Equal("ROT13", viewmodel.CipherName);
}
}
} | 29 | 67 | 0.596817 | [
"MIT"
] | aphawkins/useful-dotnet | test/Useful.Security.Cryptography.UI.Tests/ViewModels/ROT13ViewModelTests.cs | 1,131 | C# |
using FluentValidation.Results;
using System;
namespace Features.Core
{
public abstract class Entity
{
public Guid Id { get; protected set; }
public ValidationResult ValidationResult { get; protected set; }
public virtual bool EhValido()
{
throw new NotImplementedException();
}
public override bool Equals(object obj)
{
var compareTo = obj as Entity;
if (ReferenceEquals(this, compareTo)) return true;
if (ReferenceEquals(null, compareTo)) return false;
return Id.Equals(compareTo.Id);
}
public static bool operator ==(Entity a, Entity b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
return true;
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;
return a.Equals(b);
}
public static bool operator !=(Entity a, Entity b) =>
!(a == b);
public override int GetHashCode() =>
(GetType().GetHashCode() * 907) + Id.GetHashCode();
public override string ToString() =>
$"{GetType().Name} [Id={Id}]";
}
} | 26.782609 | 72 | 0.556006 | [
"Apache-2.0"
] | ferjesusjs8/TestsDevIo | TesteDeSoftwareDevIo/Features/Core/Entity.cs | 1,234 | 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/d2d1svg.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="ID2D1SvgPointCollection" /> struct.</summary>
public static unsafe class ID2D1SvgPointCollectionTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ID2D1SvgPointCollection" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ID2D1SvgPointCollection).GUID, Is.EqualTo(IID_ID2D1SvgPointCollection));
}
/// <summary>Validates that the <see cref="ID2D1SvgPointCollection" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ID2D1SvgPointCollection>(), Is.EqualTo(sizeof(ID2D1SvgPointCollection)));
}
/// <summary>Validates that the <see cref="ID2D1SvgPointCollection" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ID2D1SvgPointCollection).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ID2D1SvgPointCollection" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ID2D1SvgPointCollection), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ID2D1SvgPointCollection), Is.EqualTo(4));
}
}
}
}
| 38.596154 | 145 | 0.651719 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/d2d1svg/ID2D1SvgPointCollectionTests.cs | 2,009 | C# |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace PddOpenSdk.Models.Response.Goods
{
public partial class QueryGoodsMaterialResponseModel : PddResponseModel
{
/// <summary>
///
/// </summary>
[JsonProperty("material_list")]
public List<MaterialListResponseModel> MaterialList { get; set; }
public partial class MaterialListResponseModel : PddResponseModel
{
/// <summary>
/// 申诉审核信息
/// </summary>
[JsonProperty("appeal_check_comment")]
public string AppealCheckComment { get; set; }
/// <summary>
/// 审核信息
/// </summary>
[JsonProperty("check_comment")]
public string CheckComment { get; set; }
/// <summary>
/// 审核状态(1:待审核;2:通过;3:驳回;101:申诉待审核;102:申诉通过;103:申诉驳回)
/// </summary>
[JsonProperty("check_status")]
public int? CheckStatus { get; set; }
/// <summary>
/// 素材内容
/// </summary>
[JsonProperty("content")]
public string Content { get; set; }
/// <summary>
/// 商品id
/// </summary>
[JsonProperty("goods_id")]
public long? GoodsId { get; set; }
/// <summary>
/// 素材id
/// </summary>
[JsonProperty("material_id")]
public long? MaterialId { get; set; }
/// <summary>
/// 线上素材
/// </summary>
[JsonProperty("online_material")]
public string OnlineMaterial { get; set; }
/// <summary>
/// 素材类型(1:白底图;3:长图)
/// </summary>
[JsonProperty("type")]
public int? Type { get; set; }
}
}
}
| 30.916667 | 75 | 0.479784 | [
"Apache-2.0"
] | niltor/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Models/Response/Goods/QueryGoodsMaterialResponseModel.cs | 2,001 | C# |
using System;
using System.Runtime.CompilerServices;
using Glacie.Data.Arz;
using Glacie.Infrastructure;
namespace Glacie
{
// Record should have stable identity.
// To achieve this, they may be done as reference types, or
// as struct with access record by id.
public readonly struct Record // : IRecordApi<Field, Field?, Field>
{
private readonly Database _database;
private readonly gx_record_id _id;
internal Record(Database database, gx_record_id id)
{
_database = database;
_id = id;
}
public readonly Database Database => _database;
public readonly Context Context => _database.Context;
// TODO: Implement read-only checks in ArzDatabase.
// So at least it will help with detection of API misuse. Check should we cheap,
// because record can have own "ReadOnly" flag, which will be flowed from database/context.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ArzRecord GetUnderlyingRecord() => RecordForReading;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArzRecord GetUnderlyingRecord(bool writing)
{
if (writing) return RecordForWriting;
else return RecordForReading;
}
private readonly ArzRecord RecordForReading
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _database.GetRecordForReading(_id);
}
private ArzRecord RecordForWriting
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _database.GetRecordForWriting(_id);
}
// TODO: (Gx) Record Name Normalization: This might behave incorrectly, because
// record name in ARZ database might be not normalized. We want report
// both Name (in Context.Database) from record slot, and Path.
// They might be used later for "record name" restoring (a original casing).
public readonly string Name => RecordForReading.Name;
public readonly Path Path => new Path(Name);
public string Class
{
readonly get => RecordForReading.Class;
set => RecordForWriting.Class = value;
}
public int Version => RecordForReading.Version;
public Variant this[string fieldName]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => RecordForReading[fieldName];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => RecordForWriting[fieldName] = value;
}
}
}
| 34.894737 | 99 | 0.650075 | [
"MIT"
] | Lixiss/Glacie | src/Glacie.Context/Record.cs | 2,654 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Filter_Scripts
{
[CreateAssetMenu(menuName = "Flock/Filter/Physics Layer")]
public class PhysicsLayerFilter : ContextFilter
{
public LayerMask mask;
public override List<Transform> Filter(FlockAgent agent, List<Transform> original)
{
List<Transform> filtered = new List<Transform>();
foreach (var transform in original)
{
if (mask == (mask | 1 << transform.gameObject.layer))
{
filtered.Add(transform);
}
}
return filtered;
}
}
}
| 26.076923 | 90 | 0.558997 | [
"MIT"
] | m4rok97/Leukocyte | Assets/Scripts/Filter Scripts/PhysicsLayerFilter.cs | 680 | C# |
#region copyright
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
#endregion
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Inventory.Data.Services
{
abstract public partial class DataServiceBase : IDataService, IDisposable
{
private IDataSource _dataSource = null;
public DataServiceBase(IDataSource dataSource)
{
_dataSource = dataSource;
}
public async Task<IList<Category>> GetCategoriesAsync()
{
return await _dataSource.Categories.ToListAsync();
}
public async Task<IList<CountryCode>> GetCountryCodesAsync()
{
return await _dataSource.CountryCodes.ToListAsync();
}
public async Task<IList<OrderStatus>> GetOrderStatusAsync()
{
return await _dataSource.OrderStatus.ToListAsync();
}
public async Task<IList<PaymentType>> GetPaymentTypesAsync()
{
return await _dataSource.PaymentTypes.ToListAsync();
}
public async Task<IList<Shipper>> GetShippersAsync()
{
return await _dataSource.Shippers.ToListAsync();
}
public async Task<IList<TaxType>> GetTaxTypesAsync()
{
return await _dataSource.TaxTypes.ToListAsync();
}
#region Dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_dataSource != null)
{
_dataSource.Dispose();
}
}
}
#endregion
}
}
| 29.987805 | 82 | 0.588857 | [
"MIT"
] | AgneLukoseviciute/react-native-windows-samples | samples/TodosFeed/InventorySample/Inventory.Data/DataServices/Base/DataServiceBase.cs | 2,461 | C# |
using System.Diagnostics.CodeAnalysis;
namespace Howatworks.SubEtha.Journal.StationServices
{
[ExcludeFromCodeCoverage]
public class MissionFailed : JournalEntryBase
{
// TODO: localised?
public string Name { get; set; }
[SuppressMessage("ReSharper", "InconsistentNaming")]
public long MissionID { get; set; }
public long? Fine { get; set; }
}
}
| 25.3125 | 60 | 0.659259 | [
"MIT"
] | johnnysaucepn/SubEtha | src/Journal/Howatworks.SubEtha.Journal/StationServices/MissionFailed.cs | 407 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Homework_5
{
public class Lion : AnimalBase<int>
{
public void Play()
{
Console.WriteLine($"{Name}, play!");
}
public void Say()
{
Console.WriteLine($"{Name}, RRRRR!");
}
}
} | 18.722222 | 49 | 0.52819 | [
"MIT"
] | Alesiniya/TMS-DotNet-Ermolaeva | src/Homework5/lion.cs | 339 | C# |
//-----------------------------------------------------------------------------
// <copyright file="DaemonConfig.cs" company="Amazon.com">
// Copyright 2016 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.
// </copyright>
//-----------------------------------------------------------------------------
using Amazon.Runtime.Internal.Util;
using System;
using System.Net;
namespace Amazon.XRay.Recorder.Core.Internal.Utils
{
/// <summary>
/// DaemonConfig stores X-Ray daemon configuration about the ip address and port for UDP and TCP port. It gets the address
/// string from "AWS_TRACING_DAEMON_ADDRESS" and then from recorder's configuration for "daemon_address".
/// A notation of '127.0.0.1:2000' or 'tcp:127.0.0.1:2000 udp:127.0.0.2:2001' or 'udp:127.0.0.1:2000 tcp:127.0.0.2:2001'
/// are both acceptable. The first one means UDP and TCP are running at the same address.
/// By default it assumes a X-Ray daemon running at 127.0.0.1:2000 listening to both UDP and TCP traffic.
/// </summary>
public class DaemonConfig
{
private static readonly Logger _logger = Logger.GetLogger(typeof(DaemonConfig));
/// <summary>
/// The environment variable for daemon address.
/// </summary>
public const string EnvironmentVariableDaemonAddress = "AWS_XRAY_DAEMON_ADDRESS";
/// <summary>
/// Default address for daemon.
/// </summary>
public const string DefaultAddress = "127.0.0.1:2000";
private static readonly int _defaultDaemonPort = 2000;
private static readonly IPAddress _defaultDaemonAddress = IPAddress.Loopback;
/// <summary>
/// Default UDP and TCP endpoint.
/// </summary>
public static readonly IPEndPoint DefaultEndpoint = new IPEndPoint(_defaultDaemonAddress, _defaultDaemonPort);
/// <summary>
/// Gets or sets UDP endpoint.
/// </summary>
internal EndPoint _udpEndpoint;
/// <summary>
/// Gets or sets TCP endpoint.
/// </summary>
internal EndPoint _tcpEndpoint;
/// <summary>
/// Gets IP for UDP endpoint.
/// </summary>
public IPEndPoint UDPEndpoint {
get => _udpEndpoint.GetIPEndPoint();
set => _udpEndpoint = EndPoint.Of(value);
}
/// <summary>
/// Gets IP for TCP endpoint.
/// </summary>
public IPEndPoint TCPEndpoint
{
get => _tcpEndpoint.GetIPEndPoint();
set => _tcpEndpoint = EndPoint.Of(value);
}
public DaemonConfig()
{
_udpEndpoint = EndPoint.Of(DefaultEndpoint);
_tcpEndpoint = EndPoint.Of(DefaultEndpoint);
}
internal static DaemonConfig ParsEndpoint(string daemonAddress)
{
DaemonConfig daemonEndPoint;
if (!IPEndPointExtension.TryParse(daemonAddress, out daemonEndPoint))
{
daemonEndPoint = new DaemonConfig();
_logger.InfoFormat("The given daemonAddress ({0}) is invalid, using default daemon UDP and TCP address {1}:{2}.", daemonAddress, daemonEndPoint.UDPEndpoint.Address.ToString(), daemonEndPoint.UDPEndpoint.Port);
}
return daemonEndPoint;
}
/// <summary>
/// Parses daemonAddress and sets enpoint. If <see cref="EnvironmentVariableDaemonAddress"/> is set, this call is ignored.
/// </summary>
/// <param name="daemonAddress"> Dameon address to be parsed and set to <see cref="DaemonConfig"/> instance.</param>
/// <returns></returns>
public static DaemonConfig GetEndPoint(string daemonAddress = null)
{
if(Environment.GetEnvironmentVariable(EnvironmentVariableDaemonAddress) != null)
{
if (!string.IsNullOrEmpty(daemonAddress))
{
_logger.InfoFormat("Ignoring call to GetEndPoint as " + EnvironmentVariableDaemonAddress + " is set.");
}
return ParsEndpoint(Environment.GetEnvironmentVariable(EnvironmentVariableDaemonAddress));
}
else
{
return ParsEndpoint(daemonAddress);
}
}
}
}
| 41.504274 | 225 | 0.60173 | [
"Apache-2.0"
] | FinanzaPro/aws-xray-sdk-dotnet | sdk/src/Core/Internal/Utils/DaemonConfig.cs | 4,858 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Stride.Core.Annotations;
using Stride.Core.Presentation.Internal;
namespace Stride.Core.Presentation.Controls
{
public class ExpandableItemsControl : HeaderedItemsControl
{
/// <summary>
/// Identifies the <see cref="IsExpanded"/> dependency property.
/// </summary>
public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register(nameof(IsExpanded), typeof(bool), typeof(ExpandableItemsControl), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, OnIsExpandedChanged));
/// <summary>
/// Identifies the <see cref="Expanded"/> routed event.
/// </summary>
public static readonly RoutedEvent ExpandedEvent = EventManager.RegisterRoutedEvent(nameof(Expanded), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ExpandableItemsControl));
/// <summary>
/// Identifies the <see cref="Collapsed"/> routed event.
/// </summary>
public static readonly RoutedEvent CollapsedEvent = EventManager.RegisterRoutedEvent(nameof(Collapsed), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ExpandableItemsControl));
/// <summary>
/// Gets or sets whether this control is expanded.
/// </summary>
public bool IsExpanded { get { return (bool)GetValue(IsExpandedProperty); } set { SetValue(IsExpandedProperty, value.Box()); } }
protected bool CanExpand => HasItems;
/// <summary>
/// Raised when this <see cref="ExpandableItemsControl"/> is expanded.
/// </summary>
public event RoutedEventHandler Expanded { add { AddHandler(ExpandedEvent, value); } remove { RemoveHandler(ExpandedEvent, value); } }
/// <summary>
/// Raised when this <see cref="ExpandableItemsControl"/> is collapsed.
/// </summary>
public event RoutedEventHandler Collapsed { add { AddHandler(CollapsedEvent, value); } remove { RemoveHandler(CollapsedEvent, value); } }
/// <summary>
/// Invoked when this <see cref="ExpandableItemsControl"/> is expanded. Raises the <see cref="Expanded"/> event.
/// </summary>
/// <param name="e">The routed event arguments.</param>
protected virtual void OnExpanded([NotNull] RoutedEventArgs e)
{
RaiseEvent(e);
}
/// <summary>
/// Invoked when this <see cref="ExpandableItemsControl"/> is collapsed. Raises the <see cref="Collapsed"/> event.
/// </summary>
/// <param name="e">The routed event arguments.</param>
protected virtual void OnCollapsed([NotNull] RoutedEventArgs e)
{
RaiseEvent(e);
}
/// <inheritdoc/>
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!e.Handled && IsEnabled && e.ClickCount % 2 == 0)
{
SetCurrentValue(IsExpandedProperty, !IsExpanded);
e.Handled = true;
}
base.OnMouseLeftButtonDown(e);
}
private static void OnIsExpandedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var item = (ExpandableItemsControl)d;
var isExpanded = (bool)e.NewValue;
if (isExpanded)
item.OnExpanded(new RoutedEventArgs(ExpandedEvent, item));
else
item.OnCollapsed(new RoutedEventArgs(CollapsedEvent, item));
}
}
}
| 44.546512 | 240 | 0.651527 | [
"MIT"
] | Alan-love/xenko | sources/presentation/Stride.Core.Presentation/Controls/ExpandableItemsControl.cs | 3,831 | C# |
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Common.Models
{
public class PackagerReport : AbstractOperationReport
{
[XmlArray("Objects")]
[XmlArrayItem("Object")]
public List<PackagerObjectReport> ObjectReports { get; set; }
}
}
| 23 | 69 | 0.692308 | [
"Apache-2.0"
] | BrianMcGough/IUMediaHelperApps | Common/Models/PackagerReport.cs | 301 | C# |
/*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JustLogic nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Rect/Set X")]
[UnitFriendlyName("Rect.Set X")]
[UnitUsage(typeof(Rect))]
public class JLRectSetX : JLExpression
{
[Parameter(ExpressionType = typeof(Rect))]
public JLExpression OperandValue;
[Parameter(ExpressionType = typeof(System.Single))]
public JLExpression Value;
public override object GetAnyResult(IExecutionContext context)
{
Rect opValue = OperandValue.GetResult<Rect>(context);
opValue.x = Value.GetResult<System.Single>(context);
return opValue;
}
}
| 38.87931 | 79 | 0.769401 | [
"BSD-3-Clause"
] | AqlaSolutions/JustLogic | Assets/JustLogicUnits/Generated/Rect/JLRectSetX.cs | 2,255 | C# |
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine;
public class ScriptTools : MonoBehaviour
{
/// <summary>
/// path = Application.dataPath + @"GameDesigner\Skill\StateAction"
/// </summary>
static public void CreateScript(string path, string scriptName, string textContents)
{
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
File.AppendAllText(path + "/" + scriptName + ".cs", textContents);
AssetDatabase.Refresh();
}
/// <summary>
/// path = Application.dataPath + @"GameDesigner\Skill\StateAction"
/// </summary>
static public void CreateScript(string path, string scriptName, string[] scriptText)
{
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
foreach (var str in scriptText)
{
File.AppendAllText(path + "/" + scriptName + ".cs", str + "\n");
}
AssetDatabase.Refresh();
}
}
#endif | 28.742857 | 88 | 0.622266 | [
"MIT"
] | RedAWM/GDNet | GameDesigner/Editor/ScriptTools.cs | 1,008 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.