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 |
|---|---|---|---|---|---|---|---|---|
// Original code dervied from:
// https://github.com/thelinuxlich/artemis_CSharp/blob/master/Artemis_XNA_INDEPENDENT/System/EntitySystem.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntitySystem.cs" company="GAMADU.COM">
// Copyright © 2013 GAMADU.COM. Contains rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY GAMADU.COM '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 GAMADU.COM OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of GAMADU.COM.
// </copyright>
// <summary>
// Base of all Entity Systems. Provide basic functionalities.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended.Entities
{
public abstract class ProcessingSystem
{
private TimeSpan _timer;
internal EntityComponentSystem EntityComponentSystem;
public bool IsEnabled { get; set; }
public Game Game => EntityComponentSystem.Game;
public GraphicsDevice GraphicsDevice => EntityComponentSystem.GraphicsDevice;
public EntityManager EntityManager => EntityComponentSystem.EntityManager;
public TimeSpan ProcessingDelay { get; set; }
protected ProcessingSystem()
{
IsEnabled = true;
_timer = TimeSpan.Zero;
}
public virtual void Initialize()
{
}
public virtual void LoadContent()
{
}
public virtual void UnloadContent()
{
}
internal void ProcessInternal(GameTime gameTime)
{
if (!CheckProcessing(gameTime))
return;
Begin(gameTime);
Process(gameTime);
End(gameTime);
}
public void Toggle()
{
IsEnabled = !IsEnabled;
}
protected virtual void Begin(GameTime gameTime)
{
}
protected virtual bool CheckProcessing(GameTime gameTime)
{
// ReSharper disable once InvertIf
if (ProcessingDelay != TimeSpan.Zero)
{
_timer += gameTime.ElapsedGameTime;
if (_timer <= ProcessingDelay)
return false;
_timer -= ProcessingDelay;
}
return IsEnabled;
}
protected virtual void Process(GameTime gameTime)
{
}
protected virtual void End(GameTime gameTime)
{
}
}
} | 36.294643 | 119 | 0.611316 | [
"MIT"
] | damian-666/MonoGame.Extended | Source/MonoGame.Extended.Entities/ProcessingSystem.cs | 4,068 | C# |
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using System;
namespace CarSystemApplication
{
class Controller
{
// Imports
private readonly EngineInterface engineinterface;
private readonly BrakeInterface brakeinterface;
private readonly Dashboard dashboard;
// Sees
private readonly Ignition ignition;
private readonly OilMonitor oilmonitor;
private readonly Pedals pedals;
private readonly PetrolMonitor petrolmonitor;
// Local Controller State variables
private IgnitionState ignition_state = IgnitionState.withdrawn_key;
private PedalState accelerator_state = PedalState.pedal_released;
private PedalState brake_pedal_state = PedalState.pedal_released;
private PetrolState petrol_state = PetrolState.petrol_high;
private OilPressureState oil_pressure_state = OilPressureState.oil_pressure_low;
private OilTemperatureState oil_temperature_state = OilTemperatureState.oil_temperature_low;
// The constructor that the car system calls, It passes on the maximum speed value to the engine interface which passes it on to the SpeedMonitor
public Controller(Ignition ignition, OilMonitor oilmonitor, Pedals pedals, PetrolMonitor petrolmonitor, int maximum_speed)
{
// sees -> insure the parameters are not null
Contract.Requires(ignition != null);
Contract.Requires(oilmonitor != null);
Contract.Requires(pedals != null);
Contract.Requires(petrolmonitor != null);
this.ignition = ignition;
this.oilmonitor = oilmonitor;
this.pedals = pedals;
this.petrolmonitor = petrolmonitor;
// Imports
brakeinterface = new BrakeInterface();
engineinterface = new EngineInterface(maximum_speed);
dashboard = new Dashboard();
}
// Invariant
[ContractInvariantMethod]
private void Invariant()
{
// Make sure every import and sees is initialized
Contract.Invariant(ignition != null);
Contract.Invariant(oilmonitor != null);
Contract.Invariant(pedals != null);
Contract.Invariant(petrolmonitor != null);
Contract.Invariant(brakeinterface != null);
Contract.Invariant(engineinterface != null);
Contract.Invariant(dashboard != null);
// a => b is equivalent to (not a) or b
// When the key is not in the ignition the engine should be off
Contract.Invariant(!(ignition_state == IgnitionState.withdrawn_key) || engineinterface.engine_state == EngineState.engine_off);
// The engine can only be on when the key is inserted.
Contract.Invariant(!(engineinterface.engine_state == EngineState.engine_on) || ignition_state == IgnitionState.inserted_key);
// If the engine has failed and the brakes havn't failed -> the brakes should be applied
Contract.Invariant(!(engineinterface.engine_good == false && brakeinterface.brakes_good == true) || brakeinterface.brake_status == BrakeState.brakes_applied);
// When the brakes have failed the engine should be turned off
Contract.Invariant(!(brakeinterface.brakes_good == false) || engineinterface.engine_state == EngineState.engine_off);
// When the petrol is low the dashboard petrol light should be turned on
Contract.Invariant(!(petrol_state == PetrolState.petrol_low) || dashboard.petrol_light == DashboardState.on);
// When the oil temperature is high the dashboard oil temperature light should be turned on
Contract.Invariant(!(oil_temperature_state == OilTemperatureState.oil_temperature_high) || dashboard.oil_temperature_light == DashboardState.on);
// When the oil pressure is high the dashboard oil pressure light warning must be on
Contract.Invariant(!(oil_pressure_state == OilPressureState.oil_pressure_high) || dashboard.oil_pressure_light == DashboardState.on);
}
// The operation method which simulates the car system.
public void operate()
{
ignition_state = ignition.get_key_status();
if (ignition_state == IgnitionState.withdrawn_key)
{
engineinterface.engine_turn_off();
}
else
{
// Get the current levels of the petrol and oil sensors.
petrol_state = petrolmonitor.get_petrol_level();
oil_pressure_state = oilmonitor.get_pressure_level();
oil_temperature_state = oilmonitor.get_temperature_level();
if (petrol_state == PetrolState.petrol_low)
{
dashboard.petrol_light_on();
}
// Explicit to let CC know???
else
{
dashboard.petrol_light_off();
}
// Check Oil Pressure State
if (oil_pressure_state == OilPressureState.oil_pressure_high)
{
dashboard.oil_pressure_light_on();
}
else
{
dashboard.oil_pressure_light_off();
}
// Check Oil Temperature State
if (oil_temperature_state == OilTemperatureState.oil_temperature_high)
{
dashboard.oil_temperature_light_on();
}
else
{
dashboard.oil_temperature_light_off();
}
// Turn on engine if it is off
engineinterface.check_engine_state();
if (engineinterface.engine_state == EngineState.engine_off && engineinterface.engine_good)
{
engineinterface.engine_turn_on();
}
// Check the state of the engine, brakes and the two set of pedals.
engineinterface.check_engine_state();
brakeinterface.check_brake_state();
accelerator_state = pedals.get_accelerator_status();
brake_pedal_state = pedals.get_brake_pedal_status();
// If the engine has failed or the brake pedals have been pressed -> apply the brakes aslong has they haven't failed
if ((engineinterface.engine_good == false || brake_pedal_state == PedalState.pedal_pressed) && brakeinterface.brakes_good)
{
brakeinterface.apply_brakes();
Console.WriteLine("Decreasing speed");
engineinterface.decrease_speed(1);
}
// If the brakes have failed
if (brakeinterface.brakes_good == false)
{
engineinterface.engine_turn_off();
Contract.Assert(engineinterface.engine_state == EngineState.engine_off && brakeinterface.brakes_good == false);
}
else // Brakes are good, engine might still have failed though -> check whether to increase or decrease the speed
{
// Only release the brakes if the engine hasen't failed
if (brake_pedal_state == PedalState.pedal_released && engineinterface.engine_good)
{
brakeinterface.release_brakes();
}
if (accelerator_state == PedalState.pedal_released)
{
engineinterface.decrease_speed(1);
}
// Increase speed if the accelerator is pressed and the engine is on
if (accelerator_state == PedalState.pedal_pressed && engineinterface.engine_state == EngineState.engine_on)
{
engineinterface.increase_speed(1);
}
}
}
}
/* Test Methods */
// Some of these methods by design brake the invariant on the controller -> hence the ContractVerification(false) -> don't try and prove them
// Also those that don't aren't being called while the operate loop is being called -> dont account for them
// Test whether the engine can be turned on while the key had been withdrawn
[ContractVerification(false)]
public void key_withdrawn_test()
{
ignition_state = IgnitionState.withdrawn_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
}
// expected to be good
[ContractVerification(false)]
public void key_with_key_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
}
// Expected to fail
[ContractVerification(false)]
public void engine_failure_brakes_good_not_applied_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
brakeinterface.set_brake_good();
engineinterface.set_engine_bad();
brakeinterface.release_brakes();
}
// expected to be good
[ContractVerification(false)]
public void engine_failure_brakes_good_applied_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
brakeinterface.set_brake_good();
engineinterface.set_engine_bad();
brakeinterface.apply_brakes();
}
// Expected to fail
[ContractVerification(false)]
public void brakes_failed_engine_running_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
brakeinterface.set_brake_bad();
}
// expected to be good
[ContractVerification(false)]
public void brakes_failed_engine_off_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
brakeinterface.set_brake_bad();
engineinterface.engine_turn_off();
}
// Expected to fail
[ContractVerification(false)]
public int failed_to_go_above_maximum_speed_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
engineinterface.engine_turn_on();
brakeinterface.set_brake_good();
engineinterface.speedmonitor.set_newspeed(0);
int i = 0;
// go 1 above the maximum speed
while (i <= engineinterface.speedmonitor.maximum_speed)
{
engineinterface.increase_speed(1);
i++;
}
return engineinterface.speedmonitor.get_current_speed();
}
// Expected to be good
// Expected to return a value of 0 == the end speed after the test
[ContractVerification(false)]
public int go_to_maximum_speed_and_to_zero_test()
{
ignition_state = IgnitionState.inserted_key;
engineinterface.set_engine_good();
brakeinterface.set_brake_good();
engineinterface.engine_turn_on();
engineinterface.speedmonitor.set_newspeed(0);
int i = 0;
// go to the maximum speed
while (i < engineinterface.speedmonitor.maximum_speed)
{
engineinterface.increase_speed(1);
i++;
}
// go down to 0 again
while (i > 0)
{
engineinterface.decrease_speed(1);
i--;
}
return engineinterface.speedmonitor.get_current_speed();
}
// Expected to fail
[ContractVerification(false)]
public void petrol_low_fail_dashboard_light_test()
{
petrol_state = PetrolState.petrol_low;
dashboard.petrol_light_off();
}
// Expected to be good
[ContractVerification(false)]
public void petrol_low_dashboard_light()
{
petrol_state = PetrolState.petrol_low;
dashboard.petrol_light_on();
}
// Expected to fail
[ContractVerification(false)]
public void oil_temp_high_fail_dashboard_light_test()
{
oil_temperature_state = OilTemperatureState.oil_temperature_high;
dashboard.oil_temperature_light_off();
}
// Expected to be good
[ContractVerification(false)]
public void oil_temp_high_dashboard_light_test()
{
oil_temperature_state = OilTemperatureState.oil_temperature_high;
dashboard.oil_temperature_light_on();
}
// Expected to fail
[ContractVerification(false)]
public void oil_pressure_high_fail_dashboard_light_test()
{
oil_pressure_state = OilPressureState.oil_pressure_high;
dashboard.oil_pressure_light_off();
}
// Expected to be good
[ContractVerification(false)]
public void oil_pressure_high_dashboard_light_test()
{
oil_pressure_state = OilPressureState.oil_pressure_high;
dashboard.oil_pressure_light_on();
}
}
}
| 40.565598 | 170 | 0.601121 | [
"MIT"
] | rasmunk/set11515 | cw/src/CarSystem/CarSystemApplication/Controller.cs | 13,916 | 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.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using static Interop;
namespace System.Drawing.Design
{
public partial class ContentAlignmentEditor
{
/// <summary>
/// Control we use to provide the content alignment UI.
/// </summary>
private class ContentUI : Control
{
private IWindowsFormsEditorService _edSvc;
private double _pixelFactor;
private bool _allowExit = true;
private readonly RadioButton _topLeft = new RadioButton();
private readonly RadioButton _topCenter = new RadioButton();
private readonly RadioButton _topRight = new RadioButton();
private readonly RadioButton _middleLeft = new RadioButton();
private readonly RadioButton _middleCenter = new RadioButton();
private readonly RadioButton _middleRight = new RadioButton();
private readonly RadioButton _bottomLeft = new RadioButton();
private readonly RadioButton _bottomCenter = new RadioButton();
private readonly RadioButton _bottomRight = new RadioButton();
public ContentUI()
{
_pixelFactor = DpiHelper.LogicalToDeviceUnits(1);
InitComponent();
}
private ContentAlignment Align
{
get
{
if (_topLeft.Checked)
{
return ContentAlignment.TopLeft;
}
else if (_topCenter.Checked)
{
return ContentAlignment.TopCenter;
}
else if (_topRight.Checked)
{
return ContentAlignment.TopRight;
}
else if (_middleLeft.Checked)
{
return ContentAlignment.MiddleLeft;
}
else if (_middleCenter.Checked)
{
return ContentAlignment.MiddleCenter;
}
else if (_middleRight.Checked)
{
return ContentAlignment.MiddleRight;
}
else if (_bottomLeft.Checked)
{
return ContentAlignment.BottomLeft;
}
else if (_bottomCenter.Checked)
{
return ContentAlignment.BottomCenter;
}
else
{
return ContentAlignment.BottomRight;
}
}
set
{
switch (value)
{
case ContentAlignment.TopLeft:
CheckedControl = _topLeft;
break;
case ContentAlignment.TopCenter:
CheckedControl = _topCenter;
break;
case ContentAlignment.TopRight:
CheckedControl = _topRight;
break;
case ContentAlignment.MiddleLeft:
CheckedControl = _middleLeft;
break;
case ContentAlignment.MiddleCenter:
CheckedControl = _middleCenter;
break;
case ContentAlignment.MiddleRight:
CheckedControl = _middleRight;
break;
case ContentAlignment.BottomLeft:
CheckedControl = _bottomLeft;
break;
case ContentAlignment.BottomCenter:
CheckedControl = _bottomCenter;
break;
case ContentAlignment.BottomRight:
CheckedControl = _bottomRight;
break;
}
}
}
protected override bool ShowFocusCues
{
get => true;
}
public object Value { get; private set; }
public void End()
{
_edSvc = null;
Value = null;
}
private void ResetAnchorStyle(bool toNone = false)
{
const AnchorStyles DefaultCenterAnchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
const AnchorStyles DefaultRightAnchor = AnchorStyles.Top | AnchorStyles.Right;
if (toNone)
{
_topCenter.Anchor = AnchorStyles.None;
_topRight.Anchor = AnchorStyles.None;
_middleCenter.Anchor = AnchorStyles.None;
_middleRight.Anchor = AnchorStyles.None;
_bottomCenter.Anchor = AnchorStyles.None;
_bottomRight.Anchor = AnchorStyles.None;
}
else
{
_topCenter.Anchor = DefaultCenterAnchor;
_topRight.Anchor = DefaultRightAnchor;
_middleCenter.Anchor = DefaultCenterAnchor;
_middleRight.Anchor = DefaultRightAnchor;
_bottomCenter.Anchor = DefaultCenterAnchor;
_bottomRight.Anchor = DefaultRightAnchor;
}
}
private void SetDimensions()
{
SuspendLayout();
try
{
// This is to invoke parent changed message that help rescaling the controls based on parent font (when it changed)
Controls.Clear();
//local cache.
var pixel_24 = DpiHelper.ConvertToGivenDpiPixel(24, _pixelFactor);
var pixel_25 = DpiHelper.ConvertToGivenDpiPixel(25, _pixelFactor);
var pixel_32 = DpiHelper.ConvertToGivenDpiPixel(32, _pixelFactor);
var pixel_59 = DpiHelper.ConvertToGivenDpiPixel(59, _pixelFactor);
var pixel_64 = DpiHelper.ConvertToGivenDpiPixel(64, _pixelFactor);
var pixel_89 = DpiHelper.ConvertToGivenDpiPixel(89, _pixelFactor);
var pixel_99 = DpiHelper.ConvertToGivenDpiPixel(99, _pixelFactor);
var pixel_125 = DpiHelper.ConvertToGivenDpiPixel(125, _pixelFactor);
Size = new Size(pixel_125, pixel_89);
_topLeft.Size = new Size(pixel_24, pixel_25);
_topCenter.Location = new Point(pixel_32, 0);
_topCenter.Size = new Size(pixel_59, pixel_25);
_topRight.Location = new Point(pixel_99, 0);
_topRight.Size = new Size(pixel_24, pixel_25);
_middleLeft.Location = new Point(0, pixel_32);
_middleLeft.Size = new Size(pixel_24, pixel_25);
_middleCenter.Location = new Point(pixel_32, pixel_32);
_middleCenter.Size = new Size(pixel_59, pixel_25);
_middleRight.Location = new Point(pixel_99, pixel_32);
_middleRight.Size = new Size(pixel_24, pixel_25);
_bottomLeft.Location = new Point(0, pixel_64);
_bottomLeft.Size = new Size(pixel_24, pixel_25);
_bottomCenter.Location = new Point(pixel_32, pixel_64);
_bottomCenter.Size = new Size(pixel_59, pixel_25);
_bottomRight.Location = new Point(pixel_99, pixel_64);
_bottomRight.Size = new Size(pixel_24, pixel_25);
ResetAnchorStyle();
Controls.AddRange(new Control[]
{
_bottomRight,
_bottomCenter,
_bottomLeft,
_middleRight,
_middleCenter,
_middleLeft,
_topRight,
_topCenter,
_topLeft
});
}
finally
{
ResumeLayout();
}
}
private void InitComponent()
{
BackColor = SystemColors.Control;
ForeColor = SystemColors.ControlText;
AccessibleName = SR.ContentAlignmentEditorAccName;
_topLeft.TabIndex = 8;
_topLeft.Text = string.Empty;
_topLeft.Appearance = Appearance.Button;
_topLeft.Click += new EventHandler(OptionClick);
_topLeft.AccessibleName = SR.ContentAlignmentEditorTopLeftAccName;
_topCenter.TabIndex = 0;
_topCenter.Text = string.Empty;
_topCenter.Appearance = Appearance.Button;
_topCenter.Click += new EventHandler(OptionClick);
_topCenter.AccessibleName = SR.ContentAlignmentEditorTopCenterAccName;
_topRight.TabIndex = 1;
_topRight.Text = string.Empty;
_topRight.Appearance = Appearance.Button;
_topRight.Click += new EventHandler(OptionClick);
_topRight.AccessibleName = SR.ContentAlignmentEditorTopRightAccName;
_middleLeft.TabIndex = 2;
_middleLeft.Text = string.Empty;
_middleLeft.Appearance = Appearance.Button;
_middleLeft.Click += new EventHandler(OptionClick);
_middleLeft.AccessibleName = SR.ContentAlignmentEditorMiddleLeftAccName;
_middleCenter.TabIndex = 3;
_middleCenter.Text = string.Empty;
_middleCenter.Appearance = Appearance.Button;
_middleCenter.Click += new EventHandler(OptionClick);
_middleCenter.AccessibleName = SR.ContentAlignmentEditorMiddleCenterAccName;
_middleRight.TabIndex = 4;
_middleRight.Text = string.Empty;
_middleRight.Appearance = Appearance.Button;
_middleRight.Click += new EventHandler(OptionClick);
_middleRight.AccessibleName = SR.ContentAlignmentEditorMiddleRightAccName;
_bottomLeft.TabIndex = 5;
_bottomLeft.Text = string.Empty;
_bottomLeft.Appearance = Appearance.Button;
_bottomLeft.Click += new EventHandler(OptionClick);
_bottomLeft.AccessibleName = SR.ContentAlignmentEditorBottomLeftAccName;
_bottomCenter.TabIndex = 6;
_bottomCenter.Text = string.Empty;
_bottomCenter.Appearance = Appearance.Button;
_bottomCenter.Click += new EventHandler(OptionClick);
_bottomCenter.AccessibleName = SR.ContentAlignmentEditorBottomCenterAccName;
_bottomRight.TabIndex = 7;
_bottomRight.Text = string.Empty;
_bottomRight.Appearance = Appearance.Button;
_bottomRight.Click += new EventHandler(OptionClick);
_bottomRight.AccessibleName = SR.ContentAlignmentEditorBottomRightAccName;
SetDimensions();
}
protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew)
{
var factor = (double)deviceDpiNew / deviceDpiOld;
_pixelFactor *= factor;
ResetAnchorStyle(toNone: true);
SetDimensions();
}
protected override bool IsInputKey(Keys keyData)
=> keyData switch
{
// here, we will return false, because we want the arrow keys
// to get picked up by the process key method below
Keys.Left => false,
Keys.Right => false,
Keys.Up => false,
Keys.Down => false,
_ => base.IsInputKey(keyData),
};
private void OptionClick(object sender, EventArgs e)
{
// We allow dialog exit if allowExit is set to true
// and don't want the unintended Click event to close the dialog
if (_allowExit)
{
Value = Align;
_edSvc.CloseDropDown();
}
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
// Refresh current selection - this moves the focus to selected control, on editor launch
Align = Align;
}
public void Start(IWindowsFormsEditorService edSvc, object value)
{
_edSvc = edSvc;
Value = value;
Align = (value is null) ? ContentAlignment.MiddleLeft : (ContentAlignment)value;
}
/// <summary>
/// Here, we handle the return, tab, and escape keys appropriately
/// </summary>
protected override bool ProcessDialogKey(Keys keyData)
{
var checkedControl = CheckedControl;
switch (keyData & Keys.KeyCode)
{
case Keys.Left:
ProcessLeftKey(checkedControl);
return true;
case Keys.Right:
ProcessRightKey(checkedControl);
return true;
case Keys.Up:
ProcessUpKey(checkedControl);
return true;
case Keys.Down:
ProcessDownKey(checkedControl);
return true;
case Keys.Space:
OptionClick(this, EventArgs.Empty);
return true;
case Keys.Return:
if ((keyData & (Keys.Alt | Keys.Control)) == 0)
{
OptionClick(this, EventArgs.Empty);
return true;
}
goto default;
case Keys.Escape:
if ((keyData & (Keys.Alt | Keys.Control)) == 0)
{
_edSvc.CloseDropDown();
return true;
}
goto default;
case Keys.Tab:
if ((keyData & (Keys.Alt | Keys.Control)) == 0)
{
int nextTabIndex = CheckedControl.TabIndex + ((keyData & Keys.Shift) == 0 ? 1 : -1);
if (nextTabIndex < 0)
{
nextTabIndex = Controls.Count - 1;
}
else if (nextTabIndex >= Controls.Count)
{
nextTabIndex = 0;
}
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is RadioButton && Controls[i].TabIndex == nextTabIndex)
{
CheckedControl = (RadioButton)Controls[i];
return true;
}
}
return true;
}
goto default;
default:
return base.ProcessDialogKey(keyData);
}
}
/// <summary>
/// Imagine the grid to choose alignment:
/// [TL] [TC] [TR]
/// [ML] [MC] [MR]
/// [BL] [BC] [BR]
/// Pressing Down on any of these will lead to the same column but
/// a lower row; and pressing Down on the bottom row is meaningless
/// </summary>
/// <param name="checkedControl"></param>
private void ProcessDownKey(RadioButton checkedControl)
{
if (checkedControl == _topRight)
{
CheckedControl = _middleRight;
}
else if (checkedControl == _middleRight)
{
CheckedControl = _bottomRight;
}
else if (checkedControl == _topCenter)
{
CheckedControl = _middleCenter;
}
else if (checkedControl == _middleCenter)
{
CheckedControl = _bottomCenter;
}
else if (checkedControl == _topLeft)
{
CheckedControl = _middleLeft;
}
else if (checkedControl == _middleLeft)
{
CheckedControl = _bottomLeft;
}
}
/// <summary>
/// Imagine the grid to choose alignment:
/// [TL] [TC] [TR]
/// [ML] [MC] [MR]
/// [BL] [BC] [BR]
/// Pressing Up on any of these will lead to the same column but
/// a higher row; and pressing Up on the top row is meaningless
/// </summary>
/// <param name="checkedControl"></param>
private void ProcessUpKey(RadioButton checkedControl)
{
if (checkedControl == _bottomRight)
{
CheckedControl = _middleRight;
}
else if (checkedControl == _middleRight)
{
CheckedControl = _topRight;
}
else if (checkedControl == _bottomCenter)
{
CheckedControl = _middleCenter;
}
else if (checkedControl == _middleCenter)
{
CheckedControl = _topCenter;
}
else if (checkedControl == _bottomLeft)
{
CheckedControl = _middleLeft;
}
else if (checkedControl == _middleLeft)
{
CheckedControl = _topLeft;
}
}
/// <summary>
/// Imagine the grid to choose alignment:
/// [TL] [TC] [TR]
/// [ML] [MC] [MR]
/// [BL] [BC] [BR]
/// Pressing Right on any of these will lead to the same row but
/// a farther Right column; and pressing right on the right-most column is meaningless
/// </summary>
/// <param name="checkedControl"></param>
private void ProcessRightKey(RadioButton checkedControl)
{
if (checkedControl == _bottomLeft)
{
CheckedControl = _bottomCenter;
}
else if (checkedControl == _middleLeft)
{
CheckedControl = _middleCenter;
}
else if (checkedControl == _topLeft)
{
CheckedControl = _topCenter;
}
else if (checkedControl == _bottomCenter)
{
CheckedControl = _bottomRight;
}
else if (checkedControl == _middleCenter)
{
CheckedControl = _middleRight;
}
else if (checkedControl == _topCenter)
{
CheckedControl = _topRight;
}
}
/// <summary>
/// Imagine the grid to choose alignment:
/// [TL] [TC] [TR]
/// [ML] [MC] [MR]
/// [BL] [BC] [BR]
/// Pressing Left on any of these will lead to the same row but
/// a farther left column; and pressing Left on the left-most column is meaningless
/// </summary>
/// <param name="checkedControl"></param>
private void ProcessLeftKey(RadioButton checkedControl)
{
if (checkedControl == _bottomRight)
{
CheckedControl = _bottomCenter;
}
else if (checkedControl == _middleRight)
{
CheckedControl = _middleCenter;
}
else if (checkedControl == _topRight)
{
CheckedControl = _topCenter;
}
else if (checkedControl == _bottomCenter)
{
CheckedControl = _bottomLeft;
}
else if (checkedControl == _middleCenter)
{
CheckedControl = _middleLeft;
}
else if (checkedControl == _topCenter)
{
CheckedControl = _topLeft;
}
}
/// <summary>
/// Gets/Sets the checked control value of our editor
/// </summary>
private RadioButton CheckedControl
{
get
{
foreach (var control in Controls)
{
if (control is RadioButton radioButton && radioButton.Checked)
{
return radioButton;
}
}
return _middleLeft;
}
set
{
CheckedControl.Checked = false;
value.Checked = true;
// To actually move focus to a radio button, we need to call Focus() method.
// However, that would raise OnClick event, which would close the editor.
// We set allowExit to false, to block editor exit, on radio button selection change.
_allowExit = false;
value.Focus();
_allowExit = true;
// RadioButton::Checked will tell Accessibility that State and Name changed.
// Tell Accessibility that focus changed as well.
if (value.IsHandleCreated)
{
User32.NotifyWinEvent((int)AccessibleEvents.Focus, new HandleRef(value, value.Handle), User32.OBJID.CLIENT, 0);
}
}
}
}
}
}
| 39.766497 | 135 | 0.464812 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms.Design/src/System/Drawing/Design/ContentAlignmentEditor.ContentUI.cs | 23,504 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ServiceFabric.Mocks.Tests.Services;
namespace ServiceFabric.Mocks.Tests.ServiceProxyTests
{
[TestClass]
public class MockServiceProxyTests
{
[TestMethod]
public void TestNetFxFullCompatibility()
{
var proxy = new MockServiceProxy<MyStatelessService>();
Assert.IsNotNull(proxy);
Assert.IsNotNull(proxy.GetType().GetProperty("ServicePartitionClient"));
Assert.IsNotNull(proxy.GetType().GetProperty("ServicePartitionClient2"));
}
}
}
| 30.894737 | 85 | 0.688245 | [
"MIT"
] | Jasper136/ServiceFabric.Mocks | test/ServiceFabric.Mocks.Tests/ServiceProxyTests/MockServiceProxyTests.cs | 589 | C# |
using Cosmos.Business.Extensions.Holiday.Core;
using Cosmos.I18N.Countries;
namespace Cosmos.Business.Extensions.Holiday.Definitions.SouthAmerica.Guyana.Public
{
/// <summary>
/// Emancipation Day
/// </summary>
public class EmancipationDay : BaseFixedHolidayFunc
{
/// <inheritdoc />
public override Country Country { get; } = Country.Guyana;
/// <inheritdoc />
public override Country BelongsToCountry { get; } = Country.Guyana;
/// <inheritdoc />
public override string Name { get; } = "Emancipation Day";
/// <inheritdoc />
public override HolidayType HolidayType { get; set; } = HolidayType.Public;
/// <inheritdoc />
public override int Month { get; set; } = 8;
/// <inheritdoc />
public override int Day { get; set; } = 1;
/// <inheritdoc />
public override string I18NIdentityCode { get; } = "i18n_holiday_gy_emancipation";
}
} | 30.5625 | 90 | 0.618609 | [
"Apache-2.0"
] | cosmos-open/Holiday | src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/SouthAmerica/Guyana/Public/EmancipationDay.cs | 978 | C# |
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Data;
using System.IO;
using System.Linq;
using EDictionary.Core.Utilities;
using EDictionary.Core.Models;
using EDictionary.Core.Extensions;
namespace EDictionary.Core.Data
{
public partial class DataAccess : SqliteAccess
{
public DataAccess(DatabaseInfo dbInfo) : base(dbInfo)
{
}
public override Result CreateTable()
{
try
{
using (SQLiteCommand command = new SQLiteCommand(createTableQuery, dbConnection))
{
OpenConnection();
command.ExecuteNonQuery();
return new Result(message:"", innerMessage:"", status:Status.Success);
}
}
catch (Exception exception)
{
return new Result(message:exception.Message, status:Status.Error, exception:exception);
}
finally
{
CloseConnection();
}
}
public Result Insert(string wordJsonStr)
{
try
{
using (SQLiteCommand command = new SQLiteCommand(insertQuery, dbConnection))
{
OpenConnection();
Word word = JsonHelper.Deserialize(wordJsonStr);
string wordNumber = word.ID.MatchRegex("[0-9]");
string wordName = word.Name;
if (wordNumber != null)
wordName += " " + wordNumber;
command.Parameters.AddWithValue("@id", word.ID);
command.Parameters.AddWithValue("@name", wordName); // TODO: Test
command.Parameters.AddWithValue("@definition", wordJsonStr);
command.ExecuteNonQuery();
return new Result(message:"", innerMessage:"", status:Status.Success);
}
}
catch (Exception exception)
{
LogWriter.Instance.WriteLine($"Error occured at Insert in DataAccess:\n{exception.Message}");
return new Result(message:exception.Message, status:Status.Error, exception:exception);
}
finally
{
CloseConnection();
}
}
public Result<string> SelectDefinitionFrom(string wordID)
{
Watcher watch = new Watcher();
try
{
using (SQLiteCommand command = new SQLiteCommand(selectDefinitionFromQuery, dbConnection))
{
OpenConnection();
command.Parameters.Add(new SQLiteParameter() { ParameterName = "@id", Value = wordID});
using (SQLiteCommand fmd = dbConnection.CreateCommand())
{
command.CommandType = CommandType.Text;
SQLiteDataReader reader = command.ExecuteReader();
reader.Read();
string definitionStr = Convert.ToString(reader["Definition"]);
return new Result<string>(data:definitionStr, message:"", status:Status.Success);
}
}
}
catch (Exception exception)
{
LogWriter.Instance.WriteLine($"Error occured at SelectDefinitionFrom in DataAccess:\n{exception.Message}");
return new Result<string>(
message:exception.Message,
innerMessage:"",
status:Status.Error,
exception:exception
);
}
finally
{
CloseConnection();
}
}
public Result<List<string>> SelectID()
{
try
{
List<string> results = new List<string>();
using (SQLiteCommand command = new SQLiteCommand(selectIDQuery, dbConnection))
{
OpenConnection();
using (SQLiteCommand fmd = dbConnection.CreateCommand())
{
command.CommandType = CommandType.Text;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add(Convert.ToString(reader["ID"]));
}
return new Result<List<string>>(data:results, message:"", status:Status.Success);
}
}
}
catch (Exception exception)
{
LogWriter.Instance.WriteLine($"Error occured at SelectID in DataAccess:\n{exception.Message}");
return new Result<List<string>>(
message:exception.Message,
innerMessage:"",
status:Status.Error,
exception:exception
);
}
finally
{
CloseConnection();
}
}
public Result<List<string>> SelectName()
{
try
{
List<string> results = new List<string>();
using (SQLiteCommand command = new SQLiteCommand(selectNameQuery, dbConnection))
{
OpenConnection();
using (SQLiteCommand fmd = dbConnection.CreateCommand())
{
command.CommandType = CommandType.Text;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add(Convert.ToString(reader["Name"]));
}
return new Result<List<string>>(data: results, message: "", status: Status.Success);
}
}
}
catch (Exception exception)
{
LogWriter.Instance.WriteLine($"Error occured at SelectName in DataAccess:\n{exception.Message}");
return new Result<List<string>>(
message: exception.Message,
innerMessage: "",
status: Status.Error,
exception: exception
);
}
finally
{
CloseConnection();
}
}
public Result<Dictionary<string, string>> SelectIDAndName()
{
try
{
Dictionary<string, string> results = new Dictionary<string, string>();
using (SQLiteCommand command = new SQLiteCommand(selectIDAndNameQuery, dbConnection))
{
OpenConnection();
using (SQLiteCommand fmd = dbConnection.CreateCommand())
{
command.CommandType = CommandType.Text;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add(
Convert.ToString(reader["ID"]),
Convert.ToString(reader["Name"]));
}
return new Result<Dictionary<string, string>>(data: results, message: "", status: Status.Success);
}
}
}
catch (Exception exception)
{
LogWriter.Instance.WriteLine($"Error occured at SelectIDAndName in DataAccess:\n{exception.Message}");
return new Result<Dictionary<string, string>>(
message: exception.Message,
innerMessage: "",
status: Status.Error,
exception: exception
);
}
finally
{
CloseConnection();
}
}
}
}
| 24.830508 | 111 | 0.656826 | [
"BSD-3-Clause"
] | nguyendinhchinh/EDictionary | src/EDictionary.Core/Data/DataAccess.cs | 5,860 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using Azure.Core;
using Azure.ResourceManager.AppService.Models;
using Azure.ResourceManager.Models;
namespace Azure.ResourceManager.AppService
{
/// <summary> A class representing the VnetGateway data model. </summary>
public partial class VnetGatewayData : ProxyOnlyResource
{
/// <summary> Initializes a new instance of VnetGatewayData. </summary>
public VnetGatewayData()
{
}
/// <summary> Initializes a new instance of VnetGatewayData. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="resourceType"> The resourceType. </param>
/// <param name="systemData"> The systemData. </param>
/// <param name="kind"> Kind of resource. </param>
/// <param name="vnetName"> The Virtual Network name. </param>
/// <param name="vpnPackageUri"> The URI where the VPN package can be downloaded. </param>
internal VnetGatewayData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, string kind, string vnetName, Uri vpnPackageUri) : base(id, name, resourceType, systemData, kind)
{
VnetName = vnetName;
VpnPackageUri = vpnPackageUri;
}
/// <summary> The Virtual Network name. </summary>
public string VnetName { get; set; }
/// <summary> The URI where the VPN package can be downloaded. </summary>
public Uri VpnPackageUri { get; set; }
}
}
| 38.837209 | 216 | 0.654491 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/VnetGatewayData.cs | 1,670 | C# |
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
using System;
namespace Puerts
{
internal class StaticCallbacks
{
[MonoPInvokeCallback(typeof(V8FunctionCallback))]
internal static string ModuleResolverWrap(string identifer, int jsEnvIdx)
{
return JsEnv.jsEnvs[jsEnvIdx].ResolveModuleContent(identifer);
}
[MonoPInvokeCallback(typeof(V8FunctionCallback))]
internal static void JsEnvCallbackWrap(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
int jsEnvIdx, callbackIdx;
Utils.LongToTwoInt(data, out jsEnvIdx, out callbackIdx);
JsEnv.jsEnvs[jsEnvIdx].InvokeCallback(isolate, callbackIdx, info, self, paramLen);
}
catch (Exception e)
{
PuertsDLL.ThrowException(isolate, "JsEnvCallbackWrap c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[MonoPInvokeCallback(typeof(V8DestructorCallback))]
internal static void GeneralDestructor(IntPtr self, long data)
{
try
{
int jsEnvIdx, callbackIdx;
Utils.LongToTwoInt(data, out jsEnvIdx, out callbackIdx);
JsEnv.jsEnvs[jsEnvIdx].JsReleaseObject(self.ToInt32());
}
catch {}
}
[MonoPInvokeCallback(typeof(V8ConstructorCallback))]
internal static IntPtr ConstructorWrap(IntPtr isolate, IntPtr info, int paramLen, long data)
{
try
{
int jsEnvIdx, callbackIdx;
Utils.LongToTwoInt(data, out jsEnvIdx, out callbackIdx);
var ret = JsEnv.jsEnvs[jsEnvIdx].InvokeConstructor(isolate, callbackIdx, info, paramLen);
return ret;
}
catch (Exception e)
{
PuertsDLL.ThrowException(isolate, "ConstructorWrap c# exception:" + e.Message + ",stack:" + e.StackTrace);
return IntPtr.Zero;
}
}
[MonoPInvokeCallback(typeof(V8FunctionCallback))]
internal static void ReturnTrue(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
PuertsDLL.ReturnBoolean(isolate, info, true);
}
}
} | 39.614286 | 179 | 0.616661 | [
"BSD-3-Clause"
] | FishOrBear/puerts | unity/Assets/Puerts/Src/StaticCallbacks.cs | 2,775 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Ess.Transform;
using Aliyun.Acs.Ess.Transform.V20140828;
using System.Collections.Generic;
namespace Aliyun.Acs.Ess.Model.V20140828
{
public class AttachDBInstancesRequest : RpcAcsRequest<AttachDBInstancesResponse>
{
public AttachDBInstancesRequest()
: base("Ess", "2014-08-28", "AttachDBInstances")
{
}
private string resourceOwnerAccount;
private string scalingGroupId;
private string action;
private bool? forceAttach;
private List<string> dBInstances;
private long? ownerId;
private string accessKeyId;
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string ScalingGroupId
{
get
{
return scalingGroupId;
}
set
{
scalingGroupId = value;
DictionaryUtil.Add(QueryParameters, "ScalingGroupId", value);
}
}
public string Action
{
get
{
return action;
}
set
{
action = value;
DictionaryUtil.Add(QueryParameters, "Action", value);
}
}
public bool? ForceAttach
{
get
{
return forceAttach;
}
set
{
forceAttach = value;
DictionaryUtil.Add(QueryParameters, "ForceAttach", value.ToString());
}
}
public List<string> DBInstances
{
get
{
return dBInstances;
}
set
{
dBInstances = value;
for (int i = 0; i < dBInstances.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"DBInstance." + (i + 1) , dBInstances[i]);
}
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string AccessKeyId
{
get
{
return accessKeyId;
}
set
{
accessKeyId = value;
DictionaryUtil.Add(QueryParameters, "AccessKeyId", value);
}
}
public override AttachDBInstancesResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext)
{
return AttachDBInstancesResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 21.76 | 117 | 0.653493 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-ess/Ess/Model/V20140828/AttachDBInstancesRequest.cs | 3,264 | C# |
// Author: Daniele Giardini - http://www.demigiant.com
// Created: 2014/07/19 14:11
//
// License Copyright (c) Daniele Giardini.
// This work is subject to the terms at http://dotween.demigiant.com/license.php
//
// =============================================================
// Contains Daniele Giardini's C# port of the easing equations created by Robert Penner
// (all easing equations except for Flash, InFlash, OutFlash, InOutFlash,
// which use some parts of Robert Penner's equations but were created by Daniele Giardini)
// http://robertpenner.com/easing, see license below:
// =============================================================
//
// TERMS OF USE - EASING EQUATIONS
//
// Open source under the BSD License.
//
// Copyright © 2001 Robert Penner
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name of the author nor the names of contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
// - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using UnityEngine;
using XMLib.Easing;
#pragma warning disable 1591
namespace XMLib
{
/// <summary>
/// Used for custom and animationCurve-based ease functions. Must return a value between 0 and 1.
/// </summary>
public delegate float EaseFunction(float time, float duration, float overshootOrAmplitude, float period);
/// <summary>
/// EaseUtility
/// </summary>
public static class EaseUtility
{
private const float _PiOver2 = Mathf.PI * 0.5f;
private const float _TwoPi = Mathf.PI * 2;
/// <summary>
/// Returns a value between 0 and 1 (inclusive) based on the elapsed time and ease selected
/// </summary>
public static float Evaluate(Ease easeType, float time, float duration, float overshootOrAmplitude = 0, float period = 0)
{
switch (easeType)
{
case Ease.Linear:
return time / duration;
case Ease.InSine:
return -(float)Math.Cos(time / duration * _PiOver2) + 1;
case Ease.OutSine:
return (float)Math.Sin(time / duration * _PiOver2);
case Ease.InOutSine:
return -0.5f * ((float)Math.Cos(Mathf.PI * time / duration) - 1);
case Ease.InQuad:
return (time /= duration) * time;
case Ease.OutQuad:
return -(time /= duration) * (time - 2);
case Ease.InOutQuad:
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time;
return -0.5f * ((--time) * (time - 2) - 1);
case Ease.InCubic:
return (time /= duration) * time * time;
case Ease.OutCubic:
return ((time = time / duration - 1) * time * time + 1);
case Ease.InOutCubic:
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time;
return 0.5f * ((time -= 2) * time * time + 2);
case Ease.InQuart:
return (time /= duration) * time * time * time;
case Ease.OutQuart:
return -((time = time / duration - 1) * time * time * time - 1);
case Ease.InOutQuart:
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time;
return -0.5f * ((time -= 2) * time * time * time - 2);
case Ease.InQuint:
return (time /= duration) * time * time * time * time;
case Ease.OutQuint:
return ((time = time / duration - 1) * time * time * time * time + 1);
case Ease.InOutQuint:
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time * time;
return 0.5f * ((time -= 2) * time * time * time * time + 2);
case Ease.InExpo:
return (time == 0) ? 0 : (float)Math.Pow(2, 10 * (time / duration - 1));
case Ease.OutExpo:
if (time == duration) return 1;
return (-(float)Math.Pow(2, -10 * time / duration) + 1);
case Ease.InOutExpo:
if (time == 0) return 0;
if (time == duration) return 1;
if ((time /= duration * 0.5f) < 1) return 0.5f * (float)Math.Pow(2, 10 * (time - 1));
return 0.5f * (-(float)Math.Pow(2, -10 * --time) + 2);
case Ease.InCirc:
return -((float)Math.Sqrt(1 - (time /= duration) * time) - 1);
case Ease.OutCirc:
return (float)Math.Sqrt(1 - (time = time / duration - 1) * time);
case Ease.InOutCirc:
if ((time /= duration * 0.5f) < 1) return -0.5f * ((float)Math.Sqrt(1 - time * time) - 1);
return 0.5f * ((float)Math.Sqrt(1 - (time -= 2) * time) + 1);
case Ease.InElastic:
float s0;
if (time == 0) return 0;
if ((time /= duration) == 1) return 1;
if (period == 0) period = duration * 0.3f;
if (overshootOrAmplitude < 1)
{
overshootOrAmplitude = 1;
s0 = period / 4;
}
else s0 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude);
return -(overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s0) * _TwoPi / period));
case Ease.OutElastic:
float s1;
if (time == 0) return 0;
if ((time /= duration) == 1) return 1;
if (period == 0) period = duration * 0.3f;
if (overshootOrAmplitude < 1)
{
overshootOrAmplitude = 1;
s1 = period / 4;
}
else s1 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude);
return (overshootOrAmplitude * (float)Math.Pow(2, -10 * time) * (float)Math.Sin((time * duration - s1) * _TwoPi / period) + 1);
case Ease.InOutElastic:
float s;
if (time == 0) return 0;
if ((time /= duration * 0.5f) == 2) return 1;
if (period == 0) period = duration * (0.3f * 1.5f);
if (overshootOrAmplitude < 1)
{
overshootOrAmplitude = 1;
s = period / 4;
}
else s = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude);
if (time < 1) return -0.5f * (overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period));
return overshootOrAmplitude * (float)Math.Pow(2, -10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period) * 0.5f + 1;
case Ease.InBack:
return (time /= duration) * time * ((overshootOrAmplitude + 1) * time - overshootOrAmplitude);
case Ease.OutBack:
return ((time = time / duration - 1) * time * ((overshootOrAmplitude + 1) * time + overshootOrAmplitude) + 1);
case Ease.InOutBack:
if ((time /= duration * 0.5f) < 1) return 0.5f * (time * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time - overshootOrAmplitude));
return 0.5f * ((time -= 2) * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time + overshootOrAmplitude) + 2);
case Ease.InBounce:
return Bounce.EaseIn(time, duration, overshootOrAmplitude, period);
case Ease.OutBounce:
return Bounce.EaseOut(time, duration, overshootOrAmplitude, period);
case Ease.InOutBounce:
return Bounce.EaseInOut(time, duration, overshootOrAmplitude, period);
// Extra custom eases ////////////////////////////////////////////////////
case Ease.Flash:
return Flash.Ease(time, duration, overshootOrAmplitude, period);
case Ease.InFlash:
return Flash.EaseIn(time, duration, overshootOrAmplitude, period);
case Ease.OutFlash:
return Flash.EaseOut(time, duration, overshootOrAmplitude, period);
case Ease.InOutFlash:
return Flash.EaseInOut(time, duration, overshootOrAmplitude, period);
// Default
default:
// OutQuad
return -(time /= duration) * (time - 2);
}
}
public static EaseFunction ToEaseFunction(Ease ease)
{
switch (ease)
{
case Ease.Linear:
return (float time, float duration, float overshootOrAmplitude, float period) =>
time / duration;
case Ease.InSine:
return (float time, float duration, float overshootOrAmplitude, float period) =>
-(float)Math.Cos(time / duration * _PiOver2) + 1;
case Ease.OutSine:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(float)Math.Sin(time / duration * _PiOver2);
case Ease.InOutSine:
return (float time, float duration, float overshootOrAmplitude, float period) =>
-0.5f * ((float)Math.Cos(Mathf.PI * time / duration) - 1);
case Ease.InQuad:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(time /= duration) * time;
case Ease.OutQuad:
return (float time, float duration, float overshootOrAmplitude, float period) =>
-(time /= duration) * (time - 2);
case Ease.InOutQuad:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time;
return -0.5f * ((--time) * (time - 2) - 1);
};
case Ease.InCubic:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(time /= duration) * time * time;
case Ease.OutCubic:
return (float time, float duration, float overshootOrAmplitude, float period) =>
((time = time / duration - 1) * time * time + 1);
case Ease.InOutCubic:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time;
return 0.5f * ((time -= 2) * time * time + 2);
};
case Ease.InQuart:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(time /= duration) * time * time * time;
case Ease.OutQuart:
return (float time, float duration, float overshootOrAmplitude, float period) =>
-((time = time / duration - 1) * time * time * time - 1);
case Ease.InOutQuart:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time;
return -0.5f * ((time -= 2) * time * time * time - 2);
};
case Ease.InQuint:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(time /= duration) * time * time * time * time;
case Ease.OutQuint:
return (float time, float duration, float overshootOrAmplitude, float period) =>
((time = time / duration - 1) * time * time * time * time + 1);
case Ease.InOutQuint:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time * time;
return 0.5f * ((time -= 2) * time * time * time * time + 2);
};
case Ease.InExpo:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(time == 0) ? 0 : (float)Math.Pow(2, 10 * (time / duration - 1));
case Ease.OutExpo:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if (time == duration) return 1;
return (-(float)Math.Pow(2, -10 * time / duration) + 1);
};
case Ease.InOutExpo:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if (time == 0) return 0;
if (time == duration) return 1;
if ((time /= duration * 0.5f) < 1) return 0.5f * (float)Math.Pow(2, 10 * (time - 1));
return 0.5f * (-(float)Math.Pow(2, -10 * --time) + 2);
};
case Ease.InCirc:
return (float time, float duration, float overshootOrAmplitude, float period) =>
-((float)Math.Sqrt(1 - (time /= duration) * time) - 1);
case Ease.OutCirc:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(float)Math.Sqrt(1 - (time = time / duration - 1) * time);
case Ease.InOutCirc:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if ((time /= duration * 0.5f) < 1) return -0.5f * ((float)Math.Sqrt(1 - time * time) - 1);
return 0.5f * ((float)Math.Sqrt(1 - (time -= 2) * time) + 1);
};
case Ease.InElastic:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
float s0;
if (time == 0) return 0;
if ((time /= duration) == 1) return 1;
if (period == 0) period = duration * 0.3f;
if (overshootOrAmplitude < 1)
{
overshootOrAmplitude = 1;
s0 = period / 4;
}
else s0 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude);
return -(overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s0) * _TwoPi / period));
};
case Ease.OutElastic:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
float s1;
if (time == 0) return 0;
if ((time /= duration) == 1) return 1;
if (period == 0) period = duration * 0.3f;
if (overshootOrAmplitude < 1)
{
overshootOrAmplitude = 1;
s1 = period / 4;
}
else s1 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude);
return (overshootOrAmplitude * (float)Math.Pow(2, -10 * time) * (float)Math.Sin((time * duration - s1) * _TwoPi / period) + 1);
};
case Ease.InOutElastic:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
float s;
if (time == 0) return 0;
if ((time /= duration * 0.5f) == 2) return 1;
if (period == 0) period = duration * (0.3f * 1.5f);
if (overshootOrAmplitude < 1)
{
overshootOrAmplitude = 1;
s = period / 4;
}
else s = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude);
if (time < 1) return -0.5f * (overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period));
return overshootOrAmplitude * (float)Math.Pow(2, -10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period) * 0.5f + 1;
};
case Ease.InBack:
return (float time, float duration, float overshootOrAmplitude, float period) =>
(time /= duration) * time * ((overshootOrAmplitude + 1) * time - overshootOrAmplitude);
case Ease.OutBack:
return (float time, float duration, float overshootOrAmplitude, float period) =>
((time = time / duration - 1) * time * ((overshootOrAmplitude + 1) * time + overshootOrAmplitude) + 1);
case Ease.InOutBack:
return (float time, float duration, float overshootOrAmplitude, float period) =>
{
if ((time /= duration * 0.5f) < 1) return 0.5f * (time * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time - overshootOrAmplitude));
return 0.5f * ((time -= 2) * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time + overshootOrAmplitude) + 2);
};
case Ease.InBounce:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Bounce.EaseIn(time, duration, overshootOrAmplitude, period);
case Ease.OutBounce:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Bounce.EaseOut(time, duration, overshootOrAmplitude, period);
case Ease.InOutBounce:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Bounce.EaseInOut(time, duration, overshootOrAmplitude, period);
// Extra custom eases ////////////////////////////////////////////////////
case Ease.Flash:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Flash.Ease(time, duration, overshootOrAmplitude, period);
case Ease.InFlash:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Flash.EaseIn(time, duration, overshootOrAmplitude, period);
case Ease.OutFlash:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Flash.EaseOut(time, duration, overshootOrAmplitude, period);
case Ease.InOutFlash:
return (float time, float duration, float overshootOrAmplitude, float period) =>
Flash.EaseInOut(time, duration, overshootOrAmplitude, period);
// Default
default:
// OutQuad
return (float time, float duration, float overshootOrAmplitude, float period) => -(time /= duration) * (time - 2);
}
}
internal static bool IsFlashEase(Ease ease)
{
switch (ease)
{
case Ease.Flash:
case Ease.InFlash:
case Ease.OutFlash:
case Ease.InOutFlash:
return true;
}
return false;
}
}
public enum Ease
{
Unset, // Used to let TweenParams know that the ease was not set and apply it differently if used on Tweeners or Sequences
Linear,
InSine,
OutSine,
InOutSine,
InQuad,
OutQuad,
InOutQuad,
InCubic,
OutCubic,
InOutCubic,
InQuart,
OutQuart,
InOutQuart,
InQuint,
OutQuint,
InOutQuint,
InExpo,
OutExpo,
InOutExpo,
InCirc,
OutCirc,
InOutCirc,
InElastic,
OutElastic,
InOutElastic,
InBack,
OutBack,
InOutBack,
InBounce,
OutBounce,
InOutBounce,
// Extra custom eases
Flash, InFlash, OutFlash, InOutFlash,
}
namespace Easing
{
/// <summary>
/// This class contains a C# port of the easing equations created by Robert Penner (http://robertpenner.com/easing).
/// </summary>
public static class Bounce
{
/// <summary>
/// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity.
/// </summary>
/// <param name="time">
/// Current time (in frames or seconds).
/// </param>
/// <param name="duration">
/// Expected easing duration (in frames or seconds).
/// </param>
/// <param name="unusedOvershootOrAmplitude">Unused: here to keep same delegate for all ease types.</param>
/// <param name="unusedPeriod">Unused: here to keep same delegate for all ease types.</param>
/// <returns>
/// The eased value.
/// </returns>
public static float EaseIn(float time, float duration, float unusedOvershootOrAmplitude, float unusedPeriod)
{
return 1 - EaseOut(duration - time, duration, -1, -1);
}
/// <summary>
/// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity.
/// </summary>
/// <param name="time">
/// Current time (in frames or seconds).
/// </param>
/// <param name="duration">
/// Expected easing duration (in frames or seconds).
/// </param>
/// <param name="unusedOvershootOrAmplitude">Unused: here to keep same delegate for all ease types.</param>
/// <param name="unusedPeriod">Unused: here to keep same delegate for all ease types.</param>
/// <returns>
/// The eased value.
/// </returns>
public static float EaseOut(float time, float duration, float unusedOvershootOrAmplitude, float unusedPeriod)
{
if ((time /= duration) < (1 / 2.75f))
{
return (7.5625f * time * time);
}
if (time < (2 / 2.75f))
{
return (7.5625f * (time -= (1.5f / 2.75f)) * time + 0.75f);
}
if (time < (2.5f / 2.75f))
{
return (7.5625f * (time -= (2.25f / 2.75f)) * time + 0.9375f);
}
return (7.5625f * (time -= (2.625f / 2.75f)) * time + 0.984375f);
}
/// <summary>
/// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration.
/// </summary>
/// <param name="time">
/// Current time (in frames or seconds).
/// </param>
/// <param name="duration">
/// Expected easing duration (in frames or seconds).
/// </param>
/// <param name="unusedOvershootOrAmplitude">Unused: here to keep same delegate for all ease types.</param>
/// <param name="unusedPeriod">Unused: here to keep same delegate for all ease types.</param>
/// <returns>
/// The eased value.
/// </returns>
public static float EaseInOut(float time, float duration, float unusedOvershootOrAmplitude, float unusedPeriod)
{
if (time < duration * 0.5f)
{
return EaseIn(time * 2, duration, -1, -1) * 0.5f;
}
return EaseOut(time * 2 - duration, duration, -1, -1) * 0.5f + 0.5f;
}
}
public static class Flash
{
public static float Ease(float time, float duration, float overshootOrAmplitude, float period)
{
int stepIndex = Mathf.CeilToInt((time / duration) * overshootOrAmplitude); // 1 to overshootOrAmplitude
float stepDuration = duration / overshootOrAmplitude;
time -= stepDuration * (stepIndex - 1);
float dir = (stepIndex % 2 != 0) ? 1 : -1;
if (dir < 0) time -= stepDuration;
float res = (time * dir) / stepDuration;
return WeightedEase(overshootOrAmplitude, period, stepIndex, stepDuration, dir, res);
}
public static float EaseIn(float time, float duration, float overshootOrAmplitude, float period)
{
int stepIndex = Mathf.CeilToInt((time / duration) * overshootOrAmplitude); // 1 to overshootOrAmplitude
float stepDuration = duration / overshootOrAmplitude;
time -= stepDuration * (stepIndex - 1);
float dir = (stepIndex % 2 != 0) ? 1 : -1;
if (dir < 0) time -= stepDuration;
time = time * dir;
float res = (time /= stepDuration) * time;
return WeightedEase(overshootOrAmplitude, period, stepIndex, stepDuration, dir, res);
}
public static float EaseOut(float time, float duration, float overshootOrAmplitude, float period)
{
int stepIndex = Mathf.CeilToInt((time / duration) * overshootOrAmplitude); // 1 to overshootOrAmplitude
float stepDuration = duration / overshootOrAmplitude;
time -= stepDuration * (stepIndex - 1);
float dir = (stepIndex % 2 != 0) ? 1 : -1;
if (dir < 0) time -= stepDuration;
time = time * dir;
float res = -(time /= stepDuration) * (time - 2);
return WeightedEase(overshootOrAmplitude, period, stepIndex, stepDuration, dir, res);
}
public static float EaseInOut(float time, float duration, float overshootOrAmplitude, float period)
{
int stepIndex = Mathf.CeilToInt((time / duration) * overshootOrAmplitude); // 1 to overshootOrAmplitude
float stepDuration = duration / overshootOrAmplitude;
time -= stepDuration * (stepIndex - 1);
float dir = (stepIndex % 2 != 0) ? 1 : -1;
if (dir < 0) time -= stepDuration;
time = time * dir;
float res = (time /= stepDuration * 0.5f) < 1
? 0.5f * time * time
: -0.5f * ((--time) * (time - 2) - 1);
return WeightedEase(overshootOrAmplitude, period, stepIndex, stepDuration, dir, res);
}
private static float WeightedEase(float overshootOrAmplitude, float period, int stepIndex, float stepDuration, float dir, float res)
{
float easedRes = 0;
float finalDecimals = 0;
// Use previous stepIndex in case of odd ones, so that back ease is not clamped
if (dir > 0 && (int)overshootOrAmplitude % 2 == 0) stepIndex++;
else if (dir < 0 && (int)overshootOrAmplitude % 2 != 0) stepIndex++;
if (period > 0)
{
float finalTruncated = (float)Math.Truncate(overshootOrAmplitude);
finalDecimals = overshootOrAmplitude - finalTruncated;
if (finalTruncated % 2 > 0) finalDecimals = 1 - finalDecimals;
finalDecimals = (finalDecimals * stepIndex) / overshootOrAmplitude;
easedRes = (res * (overshootOrAmplitude - stepIndex)) / overshootOrAmplitude;
}
else if (period < 0)
{
period = -period;
easedRes = (res * stepIndex) / overshootOrAmplitude;
}
float diff = easedRes - res;
res += (diff * period) + finalDecimals;
if (res > 1) res = 1;
return res;
}
}
}
} | 48.573668 | 174 | 0.502033 | [
"MIT"
] | PxGame/XMLib.AM.Example | Assets/XMLib/XMLib.Common/Runtime/Utility/EaseUtility.cs | 30,991 | C# |
// [[[[INFO>
// Copyright 2015 Epicycle (http://epicycle.org, https://github.com/open-epicycle)
//
// 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.
//
// For more information check https://github.com/open-epicycle/Epicycle.Graphics-cs
// ]]]]
using System;
namespace Epicycle.Graphics.Color
{
// [### ColorINT.cs.TEMPLATE> type = int12, channels = rgb
public struct ColorRGB12 : IEquatable<ColorRGB12>
{
#region consts
public const ushort MinChannelValue = 0;
public const ushort MaxChannelValue = ((ushort) 0xfff);
#endregion
#region Named colors
#endregion
#region Members
private readonly ulong _rgb;
#endregion
#region Construction and conversion
public ColorRGB12(ulong rgb)
{
_rgb = rgb & ((ulong) 0xfffffffff);
}
public ColorRGB12(ushort r, ushort g, ushort b)
{
_rgb = ((ulong) r << 24) | ((ulong) g << 12) | ((ulong) b << 0);
}
#endregion
#region Properties
public ushort R
{
get { return (ushort) ((_rgb >> 24) & MaxChannelValue); }
}
public ushort G
{
get { return (ushort) ((_rgb >> 12) & MaxChannelValue); }
}
public ushort B
{
get { return (ushort) ((_rgb >> 0) & MaxChannelValue); }
}
#endregion
#region Mutation
#endregion
#region Equality & HashCode
public bool Equals(ColorRGB12 c)
{
return _rgb == c._rgb;
}
public override bool Equals(object obj)
{
var c = obj as ColorRGB12?;
if(!c.HasValue)
{
return false;
}
return Equals(c.Value);
}
public override int GetHashCode()
{
return _rgb.GetHashCode();
}
public static bool operator ==(ColorRGB12 v, ColorRGB12 w)
{
return v.Equals(w);
}
public static bool operator !=(ColorRGB12 v, ColorRGB12 w)
{
return !v.Equals(w);
}
#endregion
#region ToString
public override string ToString()
{
return string.Format("ColorRGB12(R={0}, G={1}, B={2})", R, G, B);
}
#endregion
}
// ###]
}
| 21.9 | 83 | 0.52381 | [
"Apache-2.0"
] | open-epicycle/Epicycle.Graphics-cs | projects/Epicycle.Graphics_cs/Color/ColorRGB12.cs | 3,068 | C# |
using Blazored.LocalStorage;
using CnGalWebSite.DataModel.Helper;
using CnGalWebSite.DataModel.Model;
using CnGalWebSite.Shared.Provider;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
namespace CnGalWebSite.Shared.Service
{
public class AuthService : IAuthService
{
private readonly HttpClient _httpClient;
private readonly AuthenticationStateProvider _authenticationStateProvider;
private readonly ILocalStorageService _localStorage;
public AuthService(HttpClient httpClient,
AuthenticationStateProvider authenticationStateProvider,
ILocalStorageService localStorage)
{
_httpClient = httpClient;
_authenticationStateProvider = authenticationStateProvider;
_localStorage = localStorage;
}
/// <summary>
/// 提交registerModel给accounts controller并返回RegisterResult给调用者
/// </summary>
/// <param name="registerModel"></param>
/// <returns></returns>
public async Task<Result> Register(RegisterModel registerModel)
{
try
{
var result = await _httpClient.PostAsJsonAsync<RegisterModel>(ToolHelper.WebApiPath + "api/account/register", registerModel);
var jsonContent = result.Content.ReadAsStringAsync().Result;
var obj = JsonSerializer.Deserialize<Result>(jsonContent, ToolHelper.options);
return obj;
}
catch (Exception exc)
{
return new Result { Successful = false, Error = exc.Message };
}
}
/// <summary>
/// 类似于Register 方法,它将LoginModel 发送给login controller
/// 但是,当返回一个成功的结果时
/// 它将返回一个授权令牌并持久化到local storge
/// </summary>
/// <param name="loginModel"></param>
/// <returns></returns>
public async Task<LoginResult> Login(LoginModel loginModel)
{
try
{
var result = await _httpClient.PostAsJsonAsync<LoginModel>(ToolHelper.WebApiPath + "api/account/Login", loginModel);
var jsonContent = result.Content.ReadAsStringAsync().Result;
var obj = JsonSerializer.Deserialize<LoginResult>(jsonContent, ToolHelper.options);
if (obj.Code == LoginResultCode.OK)
{
//记住 则保存令牌到本地
if (loginModel.RememberMe)
{
await _localStorage.SetItemAsync("authToken", obj.Token);
}
((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(obj.Token);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", obj.Token);
return obj;
}
return obj;
}
catch (Exception exc)
{
return new LoginResult { Code = LoginResultCode.WrongUserNameOrPassword, ErrorDescribe = exc.Message };
}
}
/// <summary>
/// 类似于Register 方法,它将LoginModel 发送给login controller
/// 但是,当返回一个成功的结果时
/// 它将返回一个授权令牌并持久化到local storge
/// </summary>
/// <param name="loginModel"></param>
/// <returns></returns>
public async Task<bool> Login(string JwtToken)
{
if (string.IsNullOrWhiteSpace(JwtToken))
{
return false;
}
try
{
await _localStorage.SetItemAsync("authToken", JwtToken);
((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(JwtToken);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JwtToken);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 类似于 Login 方法
/// 但是,当返回一个成功的结果时
/// 它将返回一个授权令牌并持久化到local storge
/// </summary>
/// <returns></returns>
public async Task<LoginResult> Refresh()
{
//是否记住用户
var isRemerber = false;
try
{
//判断是否登入
var userState = await _authenticationStateProvider.GetAuthenticationStateAsync();
if (userState.User.Identity.IsAuthenticated == false)
{
return null;
}
//读取本地令牌到Http请求头
var savedToken = await _localStorage.GetItemAsync<string>("authToken");
if (string.IsNullOrWhiteSpace(savedToken) == false)
{
isRemerber = true;
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", savedToken);
}
}
catch
{
return null;
}
try
{
//调用刷新接口
var result = await _httpClient.PostAsJsonAsync<LoginModel>(ToolHelper.WebApiPath + "api/account/RefreshJWToken", new LoginModel());
var jsonContent = result.Content.ReadAsStringAsync().Result;
var obj = JsonSerializer.Deserialize<LoginResult>(jsonContent, ToolHelper.options);
if (obj.Code == LoginResultCode.OK&&string.IsNullOrWhiteSpace(obj.Token)==false)
{
if (isRemerber)
{
await _localStorage.SetItemAsync("authToken", obj.Token);
}
((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(obj.Token);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", obj.Token);
return obj;
}
else
{
//失败后清空登入
await _localStorage.RemoveItemAsync("authToken");
((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut();
_httpClient.DefaultRequestHeaders.Authorization = null;
return obj;
}
}
catch
{
await _localStorage.RemoveItemAsync("authToken");
((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut();
_httpClient.DefaultRequestHeaders.Authorization = null;
return new LoginResult { Code = LoginResultCode.WrongUserNameOrPassword, ErrorDescribe = "登入已过期" };
}
}
/// <summary>
/// 执行与Login 方法相反的操作。
/// </summary>
/// <returns></returns>
public async Task Logout()
{
await _localStorage.RemoveItemAsync("authToken");
((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut();
_httpClient.DefaultRequestHeaders.Authorization = null;
}
/// <summary>
/// 注册用户时验证电子邮箱
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<ConfirmEmailRegisterResult> ConfirmEmailRegister(ConfirmEmailRegisterModel model)
{
var result = await _httpClient.PostAsJsonAsync<ConfirmEmailRegisterModel>(ToolHelper.WebApiPath + "api/account/ConfirmEmailRegister", model);
var jsonContent = result.Content.ReadAsStringAsync().Result;
var obj = JsonSerializer.Deserialize<ConfirmEmailRegisterResult>(jsonContent, ToolHelper.options);
return obj;
}
/// <summary>
/// 检查是否已经登入
/// </summary>
/// <returns></returns>
public async Task<bool> IsLogin()
{
var userState = await _authenticationStateProvider.GetAuthenticationStateAsync();
if (userState.User.Identity.IsAuthenticated == false)
{
return false;
}
else
{
return true;
}
}
}
}
| 38.036036 | 153 | 0.568688 | [
"MIT"
] | LittleFish-233/CnGalWebSite | CnGalWebSite/CnGalWebSite.Shared/Service/AuthService.cs | 8,854 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the inspector-2016-02-16.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Inspector.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Inspector.Model.Internal.MarshallTransformations
{
/// <summary>
/// Tag Marshaller
/// </summary>
public class TagMarshaller : IRequestMarshaller<Tag, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(Tag requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetKey())
{
context.Writer.WritePropertyName("key");
context.Writer.Write(requestObject.Key);
}
if(requestObject.IsSetValue())
{
context.Writer.WritePropertyName("value");
context.Writer.Write(requestObject.Value);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static TagMarshaller Instance = new TagMarshaller();
}
} | 32.485294 | 108 | 0.636487 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Inspector/Generated/Model/Internal/MarshallTransformations/TagMarshaller.cs | 2,209 | C# |
namespace TDE_3
{
partial class Form1
{
/// <summary>
/// Variável de designer necessária.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpar os recursos que estão sendo usados.
/// </summary>
/// <param name="disposing">true se for necessário descartar os recursos gerenciados; caso contrário, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código gerado pelo Windows Form Designer
/// <summary>
/// Método necessário para suporte ao Designer - não modifique
/// o conteúdo deste método com o editor de código.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.guna2PictureBox1 = new Guna.UI2.WinForms.Guna2PictureBox();
this.label2 = new System.Windows.Forms.Label();
this.guna2PictureBox2 = new Guna.UI2.WinForms.Guna2PictureBox();
this.label3 = new System.Windows.Forms.Label();
this.txtEmail = new Guna.UI2.WinForms.Guna2TextBox();
this.guna2PictureBox3 = new Guna.UI2.WinForms.Guna2PictureBox();
this.guna2PictureBox4 = new Guna.UI2.WinForms.Guna2PictureBox();
this.guna2Button1 = new Guna.UI2.WinForms.Guna2Button();
this.txtSenha = new Guna.UI2.WinForms.Guna2TextBox();
this.Close = new Guna.UI2.WinForms.Guna2Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox4)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(-20, -9);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(450, 463);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(140)))), ((int)(((byte)(82)))), ((int)(((byte)(255)))));
this.label1.Font = new System.Drawing.Font("Century Gothic", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(125, 119);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(112, 39);
this.label1.TabIndex = 1;
this.label1.Text = "Log In";
//
// guna2PictureBox1
//
this.guna2PictureBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(140)))), ((int)(((byte)(82)))), ((int)(((byte)(255)))));
this.guna2PictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("guna2PictureBox1.Image")));
this.guna2PictureBox1.Location = new System.Drawing.Point(43, 112);
this.guna2PictureBox1.Name = "guna2PictureBox1";
this.guna2PictureBox1.ShadowDecoration.Parent = this.guna2PictureBox1;
this.guna2PictureBox1.Size = new System.Drawing.Size(76, 52);
this.guna2PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.guna2PictureBox1.TabIndex = 2;
this.guna2PictureBox1.TabStop = false;
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(140)))), ((int)(((byte)(82)))), ((int)(((byte)(255)))));
this.label2.Font = new System.Drawing.Font("Century Gothic", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(128, 175);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(219, 44);
this.label2.TabIndex = 3;
this.label2.Text = "We Create, We Design,\r\n We Develop";
//
// guna2PictureBox2
//
this.guna2PictureBox2.BackColor = System.Drawing.Color.White;
this.guna2PictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("guna2PictureBox2.Image")));
this.guna2PictureBox2.Location = new System.Drawing.Point(492, 28);
this.guna2PictureBox2.Name = "guna2PictureBox2";
this.guna2PictureBox2.ShadowDecoration.Parent = this.guna2PictureBox2;
this.guna2PictureBox2.Size = new System.Drawing.Size(121, 107);
this.guna2PictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.guna2PictureBox2.TabIndex = 4;
this.guna2PictureBox2.TabStop = false;
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Century Gothic", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(159)))), ((int)(((byte)(111)))), ((int)(((byte)(255)))));
this.label3.Location = new System.Drawing.Point(454, 138);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(200, 22);
this.label3.TabIndex = 5;
this.label3.Text = "Faça seu Login Aqui!";
//
// txtEmail
//
this.txtEmail.BorderRadius = 20;
this.txtEmail.BorderThickness = 0;
this.txtEmail.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtEmail.DefaultText = "";
this.txtEmail.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208)))));
this.txtEmail.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226)))));
this.txtEmail.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138)))));
this.txtEmail.DisabledState.Parent = this.txtEmail;
this.txtEmail.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138)))));
this.txtEmail.FillColor = System.Drawing.SystemColors.Control;
this.txtEmail.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.txtEmail.FocusedState.Parent = this.txtEmail;
this.txtEmail.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtEmail.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(159)))), ((int)(((byte)(111)))), ((int)(((byte)(255)))));
this.txtEmail.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.txtEmail.HoverState.Parent = this.txtEmail;
this.txtEmail.Location = new System.Drawing.Point(438, 183);
this.txtEmail.Margin = new System.Windows.Forms.Padding(5);
this.txtEmail.Name = "txtEmail";
this.txtEmail.PasswordChar = '\0';
this.txtEmail.PlaceholderText = "";
this.txtEmail.SelectedText = "";
this.txtEmail.ShadowDecoration.Parent = this.txtEmail;
this.txtEmail.Size = new System.Drawing.Size(238, 46);
this.txtEmail.TabIndex = 6;
this.txtEmail.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtEmail.Click += new System.EventHandler(this.txtEmail_Click);
//
// guna2PictureBox3
//
this.guna2PictureBox3.BackColor = System.Drawing.SystemColors.Control;
this.guna2PictureBox3.Image = ((System.Drawing.Image)(resources.GetObject("guna2PictureBox3.Image")));
this.guna2PictureBox3.Location = new System.Drawing.Point(447, 191);
this.guna2PictureBox3.Name = "guna2PictureBox3";
this.guna2PictureBox3.ShadowDecoration.Parent = this.guna2PictureBox3;
this.guna2PictureBox3.Size = new System.Drawing.Size(34, 28);
this.guna2PictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.guna2PictureBox3.TabIndex = 7;
this.guna2PictureBox3.TabStop = false;
//
// guna2PictureBox4
//
this.guna2PictureBox4.BackColor = System.Drawing.SystemColors.Control;
this.guna2PictureBox4.Image = ((System.Drawing.Image)(resources.GetObject("guna2PictureBox4.Image")));
this.guna2PictureBox4.Location = new System.Drawing.Point(447, 275);
this.guna2PictureBox4.Name = "guna2PictureBox4";
this.guna2PictureBox4.ShadowDecoration.Parent = this.guna2PictureBox4;
this.guna2PictureBox4.Size = new System.Drawing.Size(34, 28);
this.guna2PictureBox4.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.guna2PictureBox4.TabIndex = 9;
this.guna2PictureBox4.TabStop = false;
//
// guna2Button1
//
this.guna2Button1.BorderRadius = 24;
this.guna2Button1.CheckedState.Parent = this.guna2Button1;
this.guna2Button1.Cursor = System.Windows.Forms.Cursors.Hand;
this.guna2Button1.CustomImages.Parent = this.guna2Button1;
this.guna2Button1.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(140)))), ((int)(((byte)(82)))), ((int)(((byte)(255)))));
this.guna2Button1.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.guna2Button1.ForeColor = System.Drawing.Color.White;
this.guna2Button1.HoverState.Parent = this.guna2Button1;
this.guna2Button1.Location = new System.Drawing.Point(469, 352);
this.guna2Button1.Name = "guna2Button1";
this.guna2Button1.ShadowDecoration.Parent = this.guna2Button1;
this.guna2Button1.Size = new System.Drawing.Size(180, 45);
this.guna2Button1.TabIndex = 10;
this.guna2Button1.Text = "Login";
this.guna2Button1.Click += new System.EventHandler(this.guna2Button1_Click);
//
// txtSenha
//
this.txtSenha.BorderRadius = 20;
this.txtSenha.BorderThickness = 0;
this.txtSenha.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSenha.DefaultText = "";
this.txtSenha.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208)))));
this.txtSenha.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226)))));
this.txtSenha.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138)))));
this.txtSenha.DisabledState.Parent = this.txtSenha;
this.txtSenha.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138)))));
this.txtSenha.FillColor = System.Drawing.SystemColors.Control;
this.txtSenha.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.txtSenha.FocusedState.Parent = this.txtSenha;
this.txtSenha.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtSenha.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(159)))), ((int)(((byte)(111)))), ((int)(((byte)(255)))));
this.txtSenha.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.txtSenha.HoverState.Parent = this.txtSenha;
this.txtSenha.Location = new System.Drawing.Point(438, 265);
this.txtSenha.Margin = new System.Windows.Forms.Padding(5);
this.txtSenha.Name = "txtSenha";
this.txtSenha.PasswordChar = '*';
this.txtSenha.PlaceholderText = "";
this.txtSenha.SelectedText = "";
this.txtSenha.ShadowDecoration.Parent = this.txtSenha;
this.txtSenha.Size = new System.Drawing.Size(238, 46);
this.txtSenha.TabIndex = 11;
this.txtSenha.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtSenha.Click += new System.EventHandler(this.txtSenha_Click);
//
// Close
//
this.Close.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(140)))), ((int)(((byte)(82)))), ((int)(((byte)(255)))));
this.Close.BorderRadius = 20;
this.Close.CheckedState.Parent = this.Close;
this.Close.CustomImages.Parent = this.Close;
this.Close.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(140)))), ((int)(((byte)(82)))), ((int)(((byte)(255)))));
this.Close.Font = new System.Drawing.Font("Century Gothic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Close.ForeColor = System.Drawing.Color.White;
this.Close.HoverState.Parent = this.Close;
this.Close.Image = ((System.Drawing.Image)(resources.GetObject("Close.Image")));
this.Close.ImageAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.Close.Location = new System.Drawing.Point(27, 385);
this.Close.Name = "Close";
this.Close.ShadowDecoration.Parent = this.Close;
this.Close.Size = new System.Drawing.Size(103, 39);
this.Close.TabIndex = 12;
this.Close.Text = "Desligar";
this.Close.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.Close.Click += new System.EventHandler(this.Close_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(700, 447);
this.Controls.Add(this.Close);
this.Controls.Add(this.guna2Button1);
this.Controls.Add(this.guna2PictureBox4);
this.Controls.Add(this.guna2PictureBox3);
this.Controls.Add(this.txtEmail);
this.Controls.Add(this.label3);
this.Controls.Add(this.guna2PictureBox2);
this.Controls.Add(this.label2);
this.Controls.Add(this.guna2PictureBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtSenha);
this.Controls.Add(this.pictureBox1);
this.Font = new System.Drawing.Font("Century Gothic", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Margin = new System.Windows.Forms.Padding(5);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.guna2PictureBox4)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label1;
private Guna.UI2.WinForms.Guna2PictureBox guna2PictureBox1;
private System.Windows.Forms.Label label2;
private Guna.UI2.WinForms.Guna2PictureBox guna2PictureBox2;
private System.Windows.Forms.Label label3;
private Guna.UI2.WinForms.Guna2TextBox txtEmail;
private Guna.UI2.WinForms.Guna2PictureBox guna2PictureBox3;
private Guna.UI2.WinForms.Guna2PictureBox guna2PictureBox4;
private Guna.UI2.WinForms.Guna2Button guna2Button1;
private Guna.UI2.WinForms.Guna2TextBox txtSenha;
private Guna.UI2.WinForms.Guna2Button Close;
}
}
| 62.145763 | 165 | 0.620193 | [
"MIT"
] | Henriqueiru/Validacao-DataGridViewTDE | TDE 3/TDE 3/Form1.Designer.cs | 18,348 | C# |
/*****************************************************************************
*
* ReoGrid - .NET Spreadsheet Control
*
* https://reogrid.net/
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* ReoGrid and ReoGridEditor is released under MIT license.
*
* Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com>
* Copyright (c) 2012-2016 unvell.com, all rights reserved.
*
****************************************************************************/
using System;
using System.Windows.Forms;
using unvell.ReoGrid.PropertyPages;
using unvell.ReoGrid.Actions;
using unvell.ReoGrid.Editor.LangRes;
namespace unvell.ReoGrid.Editor.PropertyPages
{
public partial class AlignmentPage : UserControl, IPropertyPage
{
public AlignmentPage()
{
InitializeComponent();
cmbHorAlign.Items.AddRange(new string[]
{
//"General", "Left", "Center", "Right", "Distributed (Indent)"
LangResource.Horizontal_Alignment_General,
LangResource.Horizontal_Alignment_Left,
LangResource.Horizontal_Alignment_Right,
LangResource.Horizontal_Alignment_Distributed,
});
cmbVerAlign.Items.AddRange(new string[]
{
//"General", "Top", "Middle", "Bottom"
LangResource.Vertical_Alignment_General,
LangResource.Vertical_Alignment_Top,
LangResource.Vertical_Alignment_Middle,
LangResource.Vertical_Alignment_Bottom,
});
textRotateControl.AngleChanged += (s, e) =>
{
if (numRotationAngle.Value != textRotateControl.Angle)
{
numRotationAngle.Value = textRotateControl.Angle;
}
};
numRotationAngle.ValueChanged += (s, e) =>
{
if (textRotateControl.Angle != numRotationAngle.Value)
{
textRotateControl.Angle = (int)numRotationAngle.Value;
}
};
}
#region IPropertyPage Members
private ReoGridControl grid;
public ReoGridControl Grid
{
get { return grid; }
set { this.grid = value; }
}
public void SetupUILanguage()
{
this.formLineTextAlignment.Text = LangResource.AlignmentPage_Text_Alignment;
this.labelHorizontal.Text = LangResource.AlignmentPage_Horizontal;
this.labelVertical.Text = LangResource.AlignmentPage_Vertical;
this.labelIndent.Text = LangResource.AlignmentPage_Indent;
this.formLineTextControl.Text = LangResource.AlignmentPage_Text_Control;
this.chkWrapText.Text = LangResource.AlignmentPage_Wrap_Text;
this.grpOrientation.Text = LangResource.AlignmentPage_Orientation;
this.labelDegrees.Text = LangResource.AlignmentPage_Degrees;
}
private CheckState backupTextWrapState;
private ReoGridHorAlign backupHorAlign;
private ReoGridVerAlign backupVerAlign;
private ushort backupIndent = 0;
private float backupRotateAngle = 0;
public void LoadPage()
{
var sheet = grid.CurrentWorksheet;
WorksheetRangeStyle style = sheet.GetRangeStyles(sheet.SelectionRange);
if (style.TextWrapMode == TextWrapMode.WordBreak
|| style.TextWrapMode == TextWrapMode.BreakAll)
{
backupTextWrapState = CheckState.Checked;
}
else
{
backupTextWrapState = CheckState.Unchecked;
}
backupHorAlign = style.HAlign;
backupVerAlign = style.VAlign;
switch (style.HAlign)
{
case ReoGridHorAlign.General:
cmbHorAlign.SelectedIndex = 0; break;
case ReoGridHorAlign.Left:
cmbHorAlign.SelectedIndex = 1; break;
case ReoGridHorAlign.Center:
cmbHorAlign.SelectedIndex = 2; break;
case ReoGridHorAlign.Right:
cmbHorAlign.SelectedIndex = 3; break;
case ReoGridHorAlign.DistributedIndent:
cmbHorAlign.SelectedIndex = 4; break;
}
switch (style.VAlign)
{
case ReoGridVerAlign.General:
cmbVerAlign.SelectedIndex = 0; break;
case ReoGridVerAlign.Top:
cmbVerAlign.SelectedIndex = 1; break;
case ReoGridVerAlign.Middle:
cmbVerAlign.SelectedIndex = 2; break;
case ReoGridVerAlign.Bottom:
cmbVerAlign.SelectedIndex = 3; break;
}
chkWrapText.CheckState = backupTextWrapState;
backupIndent = style.Indent;
numIndent.Value = backupIndent;
// cell text rotate
var angle = style.RotationAngle;
if (angle < -90) angle = -90;
if (angle > 90) angle = 90;
backupRotateAngle = angle;
textRotateControl.Angle = (int)angle;
numRotationAngle.Value = (int)angle;
}
public WorksheetReusableAction CreateUpdateAction()
{
var style = new WorksheetRangeStyle();
ReoGridHorAlign halign = ReoGridHorAlign.General;
ReoGridVerAlign valign = ReoGridVerAlign.Middle;
switch (cmbHorAlign.SelectedIndex)
{
default:
case 0: halign = ReoGridHorAlign.General; break;
case 1: halign = ReoGridHorAlign.Left; break;
case 2: halign = ReoGridHorAlign.Center; break;
case 3: halign = ReoGridHorAlign.Right; break;
case 4: halign = ReoGridHorAlign.DistributedIndent; break;
}
switch (cmbVerAlign.SelectedIndex)
{
default:
case 0: valign = ReoGridVerAlign.General; break;
case 1: valign = ReoGridVerAlign.Top; break;
case 2: valign = ReoGridVerAlign.Middle; break;
case 3: valign = ReoGridVerAlign.Bottom; break;
}
if (backupHorAlign != halign)
{
style.Flag |= PlainStyleFlag.HorizontalAlign;
style.HAlign = halign;
}
if (backupVerAlign != valign)
{
style.Flag |= PlainStyleFlag.VerticalAlign;
style.VAlign = valign;
}
if (backupTextWrapState != chkWrapText.CheckState)
{
style.Flag |= PlainStyleFlag.TextWrap;
if (chkWrapText.Checked)
{
style.TextWrapMode = TextWrapMode.WordBreak;
}
else
{
style.TextWrapMode = TextWrapMode.NoWrap;
}
}
if (backupIndent != numIndent.Value)
{
style.Flag |= PlainStyleFlag.Indent;
style.Indent = (ushort)numIndent.Value;
}
if (backupRotateAngle != textRotateControl.Angle)
{
style.RotationAngle = textRotateControl.Angle;
style.Flag |= PlainStyleFlag.RotationAngle;
}
return style.Flag == PlainStyleFlag.None ? null : new SetRangeStyleAction(grid.CurrentWorksheet.SelectionRange, style);
}
#pragma warning disable 67 // variable is never used
/// <summary>
/// Setting dialog will be closed when this event rasied
/// </summary>
public event EventHandler Done;
#pragma warning restore 67 // variable is never used
#endregion // IPropertyPage Members
}
}
| 27.226891 | 122 | 0.69892 | [
"MIT"
] | burstray/ReoGrid | !ReoGrid-3.0.0/Editor/PropertyPages/AlignmentPage.cs | 6,482 | C# |
using System;
using UltimaOnline.Items;
namespace UltimaOnline.Items
{
public class DarkglowScimitar : RadiantScimitar
{
public override int LabelNumber{ get{ return 1073542; } } // darkglow scimitar
[Constructable]
public DarkglowScimitar()
{
WeaponAttributes.HitDispel = 10;
}
public DarkglowScimitar( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
}
| 19.571429 | 81 | 0.671533 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline.Data/Items/Weapons/Swords/DarkglowScimitar.cs | 685 | C# |
using System;
using System.CodeDom.Compiler;
using System.Xml.Serialization;
namespace Workday.HumanResources
{
[GeneratedCode("System.Xml", "4.6.1590.0"), XmlType(Namespace = "urn:com.workday/bsvc", IncludeInSchema = false)]
[Serializable]
public enum ItemChoiceType2
{
Auto_Complete,
Skip
}
}
| 20.333333 | 114 | 0.754098 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.HumanResources/ItemChoiceType2.cs | 305 | C# |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.36.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Dialogflow API Version v2beta1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/dialogflow-enterprise/'>Dialogflow API</a>
* <tr><th>API Version<td>v2beta1
* <tr><th>API Rev<td>20181215 (1444)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/dialogflow-enterprise/'>
* https://cloud.google.com/dialogflow-enterprise/</a>
* <tr><th>Discovery Name<td>dialogflow
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Dialogflow API can be found at
* <a href='https://cloud.google.com/dialogflow-enterprise/'>https://cloud.google.com/dialogflow-enterprise/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Dialogflow.v2beta1
{
/// <summary>The Dialogflow Service.</summary>
public class DialogflowService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v2beta1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public DialogflowService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public DialogflowService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "dialogflow"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://dialogflow.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://dialogflow.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Dialogflow API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>View, manage and query your Dialogflow agents</summary>
public static string Dialogflow = "https://www.googleapis.com/auth/dialogflow";
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
}
///<summary>A base abstract class for Dialogflow requests.</summary>
public abstract class DialogflowBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new DialogflowBaseServiceRequest instance.</summary>
protected DialogflowBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Dialogflow parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
agent = new AgentResource(service);
knowledgeBases = new KnowledgeBasesResource(service);
operations = new OperationsResource(service);
}
private readonly AgentResource agent;
/// <summary>Gets the Agent resource.</summary>
public virtual AgentResource Agent
{
get { return agent; }
}
/// <summary>The "agent" collection of methods.</summary>
public class AgentResource
{
private const string Resource = "agent";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AgentResource(Google.Apis.Services.IClientService service)
{
this.service = service;
entityTypes = new EntityTypesResource(service);
environments = new EnvironmentsResource(service);
intents = new IntentsResource(service);
knowledgeBases = new KnowledgeBasesResource(service);
sessions = new SessionsResource(service);
}
private readonly EntityTypesResource entityTypes;
/// <summary>Gets the EntityTypes resource.</summary>
public virtual EntityTypesResource EntityTypes
{
get { return entityTypes; }
}
/// <summary>The "entityTypes" collection of methods.</summary>
public class EntityTypesResource
{
private const string Resource = "entityTypes";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EntityTypesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
entities = new EntitiesResource(service);
}
private readonly EntitiesResource entities;
/// <summary>Gets the Entities resource.</summary>
public virtual EntitiesResource Entities
{
get { return entities; }
}
/// <summary>The "entities" collection of methods.</summary>
public class EntitiesResource
{
private const string Resource = "entities";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EntitiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates multiple new entities in the specified entity type.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the entity type to create entities in. Format:
/// `projects//agent/entityTypes/`.</param>
public virtual BatchCreateRequest BatchCreate(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchCreateEntitiesRequest body, string parent)
{
return new BatchCreateRequest(service, body, parent);
}
/// <summary>Creates multiple new entities in the specified entity type.
///
/// Operation </summary>
public class BatchCreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchCreate request.</summary>
public BatchCreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchCreateEntitiesRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the entity type to create entities in. Format:
/// `projects//agent/entityTypes/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchCreateEntitiesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchCreate"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entities:batchCreate"; }
}
/// <summary>Initializes BatchCreate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/entityTypes/[^/]+$",
});
}
}
/// <summary>Deletes entities in the specified entity type.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the entity type to delete entries for. Format:
/// `projects//agent/entityTypes/`.</param>
public virtual BatchDeleteRequest BatchDelete(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteEntitiesRequest body, string parent)
{
return new BatchDeleteRequest(service, body, parent);
}
/// <summary>Deletes entities in the specified entity type.
///
/// Operation </summary>
public class BatchDeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchDelete request.</summary>
public BatchDeleteRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteEntitiesRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the entity type to delete entries for. Format:
/// `projects//agent/entityTypes/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteEntitiesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchDelete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entities:batchDelete"; }
}
/// <summary>Initializes BatchDelete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/entityTypes/[^/]+$",
});
}
}
/// <summary>Updates or creates multiple entities in the specified entity type. This method does not
/// affect entities in the entity type that aren't explicitly specified in the request.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the entity type to update or create entities in. Format:
/// `projects//agent/entityTypes/`.</param>
public virtual BatchUpdateRequest BatchUpdate(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateEntitiesRequest body, string parent)
{
return new BatchUpdateRequest(service, body, parent);
}
/// <summary>Updates or creates multiple entities in the specified entity type. This method does not
/// affect entities in the entity type that aren't explicitly specified in the request.
///
/// Operation </summary>
public class BatchUpdateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchUpdate request.</summary>
public BatchUpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateEntitiesRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the entity type to update or create entities in. Format:
/// `projects//agent/entityTypes/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateEntitiesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchUpdate"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entities:batchUpdate"; }
}
/// <summary>Initializes BatchUpdate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/entityTypes/[^/]+$",
});
}
}
}
/// <summary>Deletes entity types in the specified agent.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the agent to delete all entities types for. Format:
/// `projects//agent`.</param>
public virtual BatchDeleteRequest BatchDelete(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteEntityTypesRequest body, string parent)
{
return new BatchDeleteRequest(service, body, parent);
}
/// <summary>Deletes entity types in the specified agent.
///
/// Operation </summary>
public class BatchDeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchDelete request.</summary>
public BatchDeleteRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteEntityTypesRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the agent to delete all entities types for. Format:
/// `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteEntityTypesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchDelete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes:batchDelete"; }
}
/// <summary>Initializes BatchDelete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
}
}
/// <summary>Updates/Creates multiple entity types in the specified agent.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the agent to update or create entity types in. Format:
/// `projects//agent`.</param>
public virtual BatchUpdateRequest BatchUpdate(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesRequest body, string parent)
{
return new BatchUpdateRequest(service, body, parent);
}
/// <summary>Updates/Creates multiple entity types in the specified agent.
///
/// Operation </summary>
public class BatchUpdateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchUpdate request.</summary>
public BatchUpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the agent to update or create entity types in. Format:
/// `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchUpdate"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes:batchUpdate"; }
}
/// <summary>Initializes BatchUpdate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
}
}
/// <summary>Creates an entity type in the specified agent.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The agent to create a entity type for. Format: `projects//agent`.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates an entity type in the specified agent.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The agent to create a entity type for. Format: `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The language of entity synonyms defined in `entity_type`. If not specified,
/// the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes the specified entity type.</summary>
/// <param name="name">Required. The name of the entity type to delete. Format:
/// `projects//agent/entityTypes/`.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified entity type.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the entity type to delete. Format:
/// `projects//agent/entityTypes/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/entityTypes/[^/]+$",
});
}
}
/// <summary>Retrieves the specified entity type.</summary>
/// <param name="name">Required. The name of the entity type. Format: `projects//agent/entityTypes/`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified entity type.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the entity type. Format:
/// `projects//agent/entityTypes/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The language to retrieve entity synonyms for. If not specified, the agent's
/// default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/entityTypes/[^/]+$",
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Returns the list of all entity types in the specified agent.</summary>
/// <param name="parent">Required. The agent to list all entity types from. Format: `projects//agent`.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all entity types in the specified agent.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListEntityTypesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The agent to list all entity types from. Format: `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The language to list entity synonyms for. If not specified, the agent's
/// default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The next_page_token value returned from a previous list request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 100 and at
/// most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified entity type.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required for all methods except `create` (`create` populates the name automatically. The unique
/// identifier of the entity type. Format: `projects//agent/entityTypes/`.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified entity type.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required for all methods except `create` (`create` populates the name automatically.
/// The unique identifier of the entity type. Format: `projects//agent/entityTypes/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The language of entity synonyms defined in `entity_type`. If not specified,
/// the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1EntityType Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/entityTypes/[^/]+$",
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly EnvironmentsResource environments;
/// <summary>Gets the Environments resource.</summary>
public virtual EnvironmentsResource Environments
{
get { return environments; }
}
/// <summary>The "environments" collection of methods.</summary>
public class EnvironmentsResource
{
private const string Resource = "environments";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EnvironmentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
users = new UsersResource(service);
}
private readonly UsersResource users;
/// <summary>Gets the Users resource.</summary>
public virtual UsersResource Users
{
get { return users; }
}
/// <summary>The "users" collection of methods.</summary>
public class UsersResource
{
private const string Resource = "users";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public UsersResource(Google.Apis.Services.IClientService service)
{
this.service = service;
sessions = new SessionsResource(service);
}
private readonly SessionsResource sessions;
/// <summary>Gets the Sessions resource.</summary>
public virtual SessionsResource Sessions
{
get { return sessions; }
}
/// <summary>The "sessions" collection of methods.</summary>
public class SessionsResource
{
private const string Resource = "sessions";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SessionsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
contexts = new ContextsResource(service);
entityTypes = new EntityTypesResource(service);
}
private readonly ContextsResource contexts;
/// <summary>Gets the Contexts resource.</summary>
public virtual ContextsResource Contexts
{
get { return contexts; }
}
/// <summary>The "contexts" collection of methods.</summary>
public class ContextsResource
{
private const string Resource = "contexts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ContextsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a context.
///
/// If the specified context already exists, overrides the context.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The session to create a context for. Format: `projects//agent/sessions/` or
/// `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified, we assume default 'draft'
/// environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a context.
///
/// If the specified context already exists, overrides the context.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The session to create a context for. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User
/// ID` is not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/contexts"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+$",
});
}
}
/// <summary>Deletes the specified context.</summary>
/// <param name="name">Required. The name of the context to delete. Format: `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is not specified, we assume default
/// 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified context.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the context to delete. Format:
/// `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is
/// not specified, we assume default 'draft' environment. If `User ID` is not specified,
/// we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+/contexts/[^/]+$",
});
}
}
/// <summary>Retrieves the specified context.</summary>
/// <param name="name">Required. The name of the context. Format: `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is not specified, we assume default
/// 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified context.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the context. Format:
/// `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is
/// not specified, we assume default 'draft' environment. If `User ID` is not specified,
/// we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+/contexts/[^/]+$",
});
}
}
/// <summary>Returns the list of all contexts in the specified session.</summary>
/// <param name="parent">Required. The session to list all contexts from. Format: `projects//agent/sessions/` or
/// `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified, we assume default 'draft'
/// environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all contexts in the specified session.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListContextsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The session to list all contexts from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User
/// ID` is not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The maximum number of items to return in a single page. By
/// default 100 and at most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional. The next_page_token value returned from a previous list
/// request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/contexts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+$",
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified context.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required. The unique identifier of the context. Format: `projects//agent/sessions//contexts/`, or
/// `projects//agent/environments//users//sessions//contexts/`.
///
/// The `Context ID` is always converted to lowercase, may only contain characters in a-zA-Z0-9_-% and may be at most
/// 250 bytes long.
///
/// If `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not specified, we
/// assume default '-' user.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified context.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required. The unique identifier of the context. Format:
/// `projects//agent/sessions//contexts/`, or
/// `projects//agent/environments//users//sessions//contexts/`.
///
/// The `Context ID` is always converted to lowercase, may only contain characters in
/// a-zA-Z0-9_-% and may be at most 250 bytes long.
///
/// If `Environment ID` is not specified, we assume default 'draft' environment. If
/// `User ID` is not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+/contexts/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly EntityTypesResource entityTypes;
/// <summary>Gets the EntityTypes resource.</summary>
public virtual EntityTypesResource EntityTypes
{
get { return entityTypes; }
}
/// <summary>The "entityTypes" collection of methods.</summary>
public class EntityTypesResource
{
private const string Resource = "entityTypes";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EntityTypesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a session entity type.
///
/// If the specified session entity type already exists, overrides the session entity
/// type.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The session to create a session entity type for. Format: `projects//agent/sessions/`
/// or `projects//agent/environments//users// sessions/`. If `Environment ID` is not specified, we assume default
/// 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a session entity type.
///
/// If the specified session entity type already exists, overrides the session entity
/// type.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The session to create a session entity type for. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users// sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User
/// ID` is not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+$",
});
}
}
/// <summary>Deletes the specified session entity type.</summary>
/// <param name="name">Required. The name of the entity type to delete. Format: `projects//agent/sessions//entityTypes/`
/// or `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not specified, we assume
/// default 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified session entity type.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the entity type to delete. Format:
/// `projects//agent/sessions//entityTypes/` or
/// `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID`
/// is not specified, we assume default 'draft' environment. If `User ID` is not
/// specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+/entityTypes/[^/]+$",
});
}
}
/// <summary>Retrieves the specified session entity type.</summary>
/// <param name="name">Required. The name of the session entity type. Format: `projects//agent/sessions//entityTypes/`
/// or `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not specified, we assume
/// default 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified session entity type.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the session entity type. Format:
/// `projects//agent/sessions//entityTypes/` or
/// `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID`
/// is not specified, we assume default 'draft' environment. If `User ID` is not
/// specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+/entityTypes/[^/]+$",
});
}
}
/// <summary>Returns the list of all session entity types in the specified
/// session.</summary>
/// <param name="parent">Required. The session to list all session entity types from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users// sessions/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume default '-'
/// user.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all session entity types in the specified
/// session.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListSessionEntityTypesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The session to list all session entity types from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users// sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User
/// ID` is not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list
/// request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By
/// default 100 and at most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified session entity type.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required. The unique identifier of this session entity type. Format:
/// `projects//agent/sessions//entityTypes/`, or `projects//agent/environments//users//sessions//entityTypes/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.
///
/// `` must be the display name of an existing entity type in the same agent that will be overridden or
/// supplemented.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified session entity type.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required. The unique identifier of this session entity type. Format:
/// `projects//agent/sessions//entityTypes/`, or
/// `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID`
/// is not specified, we assume default 'draft' environment. If `User ID` is not
/// specified, we assume default '-' user.
///
/// `` must be the display name of an existing entity type in the same agent that will
/// be overridden or supplemented.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+/entityTypes/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Deletes all active contexts in the specified session.</summary>
/// <param name="parent">Required. The name of the session to delete all contexts from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If `Environment ID` is not
/// specified we assume default 'draft' environment. If `User ID` is not specified, we assume default '-'
/// user.</param>
public virtual DeleteContextsRequest DeleteContexts(string parent)
{
return new DeleteContextsRequest(service, parent);
}
/// <summary>Deletes all active contexts in the specified session.</summary>
public class DeleteContextsRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new DeleteContexts request.</summary>
public DeleteContextsRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The name of the session to delete all contexts from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If
/// `Environment ID` is not specified we assume default 'draft' environment. If `User ID` is
/// not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "deleteContexts"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/contexts"; }
}
/// <summary>Initializes DeleteContexts parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+$",
});
}
}
/// <summary>Processes a natural language query and returns structured, actionable data as a
/// result. This method is not idempotent, because it may cause contexts and session entity
/// types to be updated, which in turn might affect results of future queries.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="session">Required. The name of the session this query is sent to. Format: `projects//agent/sessions/`,
/// or `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified, we assume default 'draft'
/// environment. If `User ID` is not specified, we are using "-". It’s up to the API caller to choose an appropriate
/// `Session ID` and `User Id`. They can be a random numbers or some type of user and session identifiers (preferably
/// hashed). The length of the `Session ID` and `User ID` must not exceed 36 characters.</param>
public virtual DetectIntentRequest DetectIntent(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentRequest body, string session)
{
return new DetectIntentRequest(service, body, session);
}
/// <summary>Processes a natural language query and returns structured, actionable data as a
/// result. This method is not idempotent, because it may cause contexts and session entity
/// types to be updated, which in turn might affect results of future queries.</summary>
public class DetectIntentRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentResponse>
{
/// <summary>Constructs a new DetectIntent request.</summary>
public DetectIntentRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentRequest body, string session)
: base(service)
{
Session = session;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the session this query is sent to. Format:
/// `projects//agent/sessions/`, or `projects//agent/environments//users//sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID`
/// is not specified, we are using "-". It’s up to the API caller to choose an appropriate
/// `Session ID` and `User Id`. They can be a random numbers or some type of user and
/// session identifiers (preferably hashed). The length of the `Session ID` and `User ID`
/// must not exceed 36 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("session", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Session { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "detectIntent"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+session}:detectIntent"; }
}
/// <summary>Initializes DetectIntent parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"session", new Google.Apis.Discovery.Parameter
{
Name = "session",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/environments/[^/]+/users/[^/]+/sessions/[^/]+$",
});
}
}
}
}
}
private readonly IntentsResource intents;
/// <summary>Gets the Intents resource.</summary>
public virtual IntentsResource Intents
{
get { return intents; }
}
/// <summary>The "intents" collection of methods.</summary>
public class IntentsResource
{
private const string Resource = "intents";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public IntentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Deletes intents in the specified agent.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the agent to delete all entities types for. Format:
/// `projects//agent`.</param>
public virtual BatchDeleteRequest BatchDelete(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteIntentsRequest body, string parent)
{
return new BatchDeleteRequest(service, body, parent);
}
/// <summary>Deletes intents in the specified agent.
///
/// Operation </summary>
public class BatchDeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchDelete request.</summary>
public BatchDeleteRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteIntentsRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the agent to delete all entities types for. Format:
/// `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchDeleteIntentsRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchDelete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/intents:batchDelete"; }
}
/// <summary>Initializes BatchDelete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
}
}
/// <summary>Updates/Creates multiple intents in the specified agent.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The name of the agent to update or create intents in. Format:
/// `projects//agent`.</param>
public virtual BatchUpdateRequest BatchUpdate(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateIntentsRequest body, string parent)
{
return new BatchUpdateRequest(service, body, parent);
}
/// <summary>Updates/Creates multiple intents in the specified agent.
///
/// Operation </summary>
public class BatchUpdateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new BatchUpdate request.</summary>
public BatchUpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateIntentsRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the agent to update or create intents in. Format:
/// `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1BatchUpdateIntentsRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchUpdate"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/intents:batchUpdate"; }
}
/// <summary>Initializes BatchUpdate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
}
}
/// <summary>Creates an intent in the specified agent.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The agent to create a intent for. Format: `projects//agent`.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates an intent in the specified agent.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The agent to create a intent for. Format: `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The language of training phrases, parameters and rich messages defined in
/// `intent`. If not specified, the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
[Google.Apis.Util.RequestParameterAttribute("intentView", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<IntentViewEnum> IntentView { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
public enum IntentViewEnum
{
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_UNSPECIFIED")]
INTENTVIEWUNSPECIFIED,
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_FULL")]
INTENTVIEWFULL,
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/intents"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"intentView", new Google.Apis.Discovery.Parameter
{
Name = "intentView",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes the specified intent and its direct or indirect followup intents.</summary>
/// <param name="name">Required. The name of the intent to delete. If this intent has direct or indirect followup
/// intents, we also delete them.
///
/// Format: `projects//agent/intents/`.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified intent and its direct or indirect followup intents.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the intent to delete. If this intent has direct or indirect
/// followup intents, we also delete them.
///
/// Format: `projects//agent/intents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/intents/[^/]+$",
});
}
}
/// <summary>Retrieves the specified intent.</summary>
/// <param name="name">Required. The name of the intent. Format: `projects//agent/intents/`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified intent.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the intent. Format: `projects//agent/intents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
[Google.Apis.Util.RequestParameterAttribute("intentView", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<IntentViewEnum> IntentView { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
public enum IntentViewEnum
{
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_UNSPECIFIED")]
INTENTVIEWUNSPECIFIED,
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_FULL")]
INTENTVIEWFULL,
}
/// <summary>Optional. The language to retrieve training phrases, parameters and rich messages for.
/// If not specified, the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/intents/[^/]+$",
});
RequestParameters.Add(
"intentView", new Google.Apis.Discovery.Parameter
{
Name = "intentView",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Returns the list of all intents in the specified agent.</summary>
/// <param name="parent">Required. The agent to list all intents from. Format: `projects//agent`.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all intents in the specified agent.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListIntentsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The agent to list all intents from. Format: `projects//agent`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 100 and at
/// most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
[Google.Apis.Util.RequestParameterAttribute("intentView", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<IntentViewEnum> IntentView { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
public enum IntentViewEnum
{
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_UNSPECIFIED")]
INTENTVIEWUNSPECIFIED,
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_FULL")]
INTENTVIEWFULL,
}
/// <summary>Optional. The language to list training phrases, parameters and rich messages for. If
/// not specified, the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/intents"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"intentView", new Google.Apis.Discovery.Parameter
{
Name = "intentView",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified intent.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required for all methods except `create` (`create` populates the name automatically. The unique
/// identifier of this intent. Format: `projects//agent/intents/`.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified intent.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required for all methods except `create` (`create` populates the name automatically.
/// The unique identifier of this intent. Format: `projects//agent/intents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
[Google.Apis.Util.RequestParameterAttribute("intentView", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<IntentViewEnum> IntentView { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
public enum IntentViewEnum
{
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_UNSPECIFIED")]
INTENTVIEWUNSPECIFIED,
[Google.Apis.Util.StringValueAttribute("INTENT_VIEW_FULL")]
INTENTVIEWFULL,
}
/// <summary>Optional. The language of training phrases, parameters and rich messages defined in
/// `intent`. If not specified, the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must
/// be enabled in the agent, before they can be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Intent Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/intents/[^/]+$",
});
RequestParameters.Add(
"intentView", new Google.Apis.Discovery.Parameter
{
Name = "intentView",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"languageCode", new Google.Apis.Discovery.Parameter
{
Name = "languageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly KnowledgeBasesResource knowledgeBases;
/// <summary>Gets the KnowledgeBases resource.</summary>
public virtual KnowledgeBasesResource KnowledgeBases
{
get { return knowledgeBases; }
}
/// <summary>The "knowledgeBases" collection of methods.</summary>
public class KnowledgeBasesResource
{
private const string Resource = "knowledgeBases";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public KnowledgeBasesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
documents = new DocumentsResource(service);
}
private readonly DocumentsResource documents;
/// <summary>Gets the Documents resource.</summary>
public virtual DocumentsResource Documents
{
get { return documents; }
}
/// <summary>The "documents" collection of methods.</summary>
public class DocumentsResource
{
private const string Resource = "documents";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DocumentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a new document.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The knoweldge base to create a document for. Format:
/// `projects//knowledgeBases/`.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a new document.
///
/// Operation </summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The knoweldge base to create a document for. Format:
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/documents"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+$",
});
}
}
/// <summary>Deletes the specified document.
///
/// Operation </summary>
/// <param name="name">The name of the document to delete. Format: `projects//knowledgeBases//documents/`.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified document.
///
/// Operation </summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the document to delete. Format:
/// `projects//knowledgeBases//documents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+/documents/[^/]+$",
});
}
}
/// <summary>Retrieves the specified document.</summary>
/// <param name="name">Required. The name of the document to retrieve. Format
/// `projects//knowledgeBases//documents/`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified document.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the document to retrieve. Format
/// `projects//knowledgeBases//documents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+/documents/[^/]+$",
});
}
}
/// <summary>Returns the list of all documents of the knowledge base.</summary>
/// <param name="parent">Required. The knowledge base to list all documents for. Format:
/// `projects//knowledgeBases/`.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all documents of the knowledge base.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListDocumentsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The knowledge base to list all documents for. Format:
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list
/// request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 10 and
/// at most 100.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/documents"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified document. Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The document resource name. The name must be empty when creating a document. Format:
/// `projects//knowledgeBases//documents/`.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified document. Operation </summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The document resource name. The name must be empty when creating a document.
/// Format: `projects//knowledgeBases//documents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. Not specified means `update all`. Currently, only `display_name` can be
/// updated, an InvalidArgument will be returned for attempting to update other
/// fields.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+/documents/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Reloads the specified document from its specified source, content_uri or content. The
/// previously loaded content of the document will be deleted. Note: Even when the content of the
/// document has not changed, there still may be side effects because of internal implementation
/// changes. Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the document to reload. Format: `projects//knowledgeBases//documents/`</param>
public virtual ReloadRequest Reload(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ReloadDocumentRequest body, string name)
{
return new ReloadRequest(service, body, name);
}
/// <summary>Reloads the specified document from its specified source, content_uri or content. The
/// previously loaded content of the document will be deleted. Note: Even when the content of the
/// document has not changed, there still may be side effects because of internal implementation
/// changes. Operation </summary>
public class ReloadRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Reload request.</summary>
public ReloadRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ReloadDocumentRequest body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the document to reload. Format:
/// `projects//knowledgeBases//documents/`</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ReloadDocumentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "reload"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}:reload"; }
}
/// <summary>Initializes Reload parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+/documents/[^/]+$",
});
}
}
}
/// <summary>Creates a knowledge base.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project to create a knowledge base for. Format: `projects/`.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a knowledge base.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project to create a knowledge base for. Format: `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/knowledgeBases"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
}
}
/// <summary>Deletes the specified knowledge base.</summary>
/// <param name="name">Required. The name of the knowledge base to delete. Format:
/// `projects//knowledgeBases/`.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified knowledge base.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the knowledge base to delete. Format:
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. Force deletes the knowledge base. When set to true, any documents in the
/// knowledge base are also deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("force", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Force { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+$",
});
RequestParameters.Add(
"force", new Google.Apis.Discovery.Parameter
{
Name = "force",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves the specified knowledge base.</summary>
/// <param name="name">Required. The name of the knowledge base to retrieve. Format
/// `projects//knowledgeBases/`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified knowledge base.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the knowledge base to retrieve. Format
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+$",
});
}
}
/// <summary>Returns the list of all knowledge bases of the specified agent.</summary>
/// <param name="parent">Required. The project to list of knowledge bases for. Format: `projects/`.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all knowledge bases of the specified agent.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListKnowledgeBasesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The project to list of knowledge bases for. Format: `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 10 and at
/// most 100.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional. The next_page_token value returned from a previous list request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/knowledgeBases"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent$",
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified knowledge base.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The knowledge base resource name. The name must be empty when creating a knowledge base. Format:
/// `projects//knowledgeBases/`.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified knowledge base.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The knowledge base resource name. The name must be empty when creating a knowledge
/// base. Format: `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. Not specified means `update all`. Currently, only `display_name` can be
/// updated, an InvalidArgument will be returned for attempting to update other fields.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/knowledgeBases/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly SessionsResource sessions;
/// <summary>Gets the Sessions resource.</summary>
public virtual SessionsResource Sessions
{
get { return sessions; }
}
/// <summary>The "sessions" collection of methods.</summary>
public class SessionsResource
{
private const string Resource = "sessions";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SessionsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
contexts = new ContextsResource(service);
entityTypes = new EntityTypesResource(service);
}
private readonly ContextsResource contexts;
/// <summary>Gets the Contexts resource.</summary>
public virtual ContextsResource Contexts
{
get { return contexts; }
}
/// <summary>The "contexts" collection of methods.</summary>
public class ContextsResource
{
private const string Resource = "contexts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ContextsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a context.
///
/// If the specified context already exists, overrides the context.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The session to create a context for. Format: `projects//agent/sessions/` or
/// `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified, we assume default 'draft'
/// environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a context.
///
/// If the specified context already exists, overrides the context.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The session to create a context for. Format: `projects//agent/sessions/`
/// or `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified,
/// we assume default 'draft' environment. If `User ID` is not specified, we assume default '-'
/// user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/contexts"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+$",
});
}
}
/// <summary>Deletes the specified context.</summary>
/// <param name="name">Required. The name of the context to delete. Format: `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is not specified, we assume default
/// 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified context.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the context to delete. Format:
/// `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+/contexts/[^/]+$",
});
}
}
/// <summary>Retrieves the specified context.</summary>
/// <param name="name">Required. The name of the context. Format: `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is not specified, we assume default
/// 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified context.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the context. Format: `projects//agent/sessions//contexts/` or
/// `projects//agent/environments//users//sessions//contexts/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+/contexts/[^/]+$",
});
}
}
/// <summary>Returns the list of all contexts in the specified session.</summary>
/// <param name="parent">Required. The session to list all contexts from. Format: `projects//agent/sessions/` or
/// `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified, we assume default 'draft'
/// environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all contexts in the specified session.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListContextsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The session to list all contexts from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is
/// not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list
/// request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 100
/// and at most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/contexts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified context.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required. The unique identifier of the context. Format: `projects//agent/sessions//contexts/`, or
/// `projects//agent/environments//users//sessions//contexts/`.
///
/// The `Context ID` is always converted to lowercase, may only contain characters in a-zA-Z0-9_-% and may be at most
/// 250 bytes long.
///
/// If `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not specified, we
/// assume default '-' user.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified context.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required. The unique identifier of the context. Format:
/// `projects//agent/sessions//contexts/`, or
/// `projects//agent/environments//users//sessions//contexts/`.
///
/// The `Context ID` is always converted to lowercase, may only contain characters in
/// a-zA-Z0-9_-% and may be at most 250 bytes long.
///
/// If `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is
/// not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Context Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+/contexts/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly EntityTypesResource entityTypes;
/// <summary>Gets the EntityTypes resource.</summary>
public virtual EntityTypesResource EntityTypes
{
get { return entityTypes; }
}
/// <summary>The "entityTypes" collection of methods.</summary>
public class EntityTypesResource
{
private const string Resource = "entityTypes";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EntityTypesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a session entity type.
///
/// If the specified session entity type already exists, overrides the session entity
/// type.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The session to create a session entity type for. Format: `projects//agent/sessions/`
/// or `projects//agent/environments//users// sessions/`. If `Environment ID` is not specified, we assume default
/// 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a session entity type.
///
/// If the specified session entity type already exists, overrides the session entity
/// type.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The session to create a session entity type for. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users// sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is
/// not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+$",
});
}
}
/// <summary>Deletes the specified session entity type.</summary>
/// <param name="name">Required. The name of the entity type to delete. Format: `projects//agent/sessions//entityTypes/`
/// or `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not specified, we assume
/// default 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified session entity type.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the entity type to delete. Format:
/// `projects//agent/sessions//entityTypes/` or
/// `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+/entityTypes/[^/]+$",
});
}
}
/// <summary>Retrieves the specified session entity type.</summary>
/// <param name="name">Required. The name of the session entity type. Format: `projects//agent/sessions//entityTypes/`
/// or `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not specified, we assume
/// default 'draft' environment. If `User ID` is not specified, we assume default '-' user.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified session entity type.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the session entity type. Format:
/// `projects//agent/sessions//entityTypes/` or
/// `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+/entityTypes/[^/]+$",
});
}
}
/// <summary>Returns the list of all session entity types in the specified session.</summary>
/// <param name="parent">Required. The session to list all session entity types from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users// sessions/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume default '-'
/// user.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all session entity types in the specified session.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListSessionEntityTypesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The session to list all session entity types from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users// sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is
/// not specified, we assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list
/// request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 100
/// and at most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/entityTypes"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified session entity type.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required. The unique identifier of this session entity type. Format:
/// `projects//agent/sessions//entityTypes/`, or `projects//agent/environments//users//sessions//entityTypes/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.
///
/// `` must be the display name of an existing entity type in the same agent that will be overridden or
/// supplemented.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified session entity type.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required. The unique identifier of this session entity type. Format:
/// `projects//agent/sessions//entityTypes/`, or
/// `projects//agent/environments//users//sessions//entityTypes/`. If `Environment ID` is not
/// specified, we assume default 'draft' environment. If `User ID` is not specified, we assume
/// default '-' user.
///
/// `` must be the display name of an existing entity type in the same agent that will be
/// overridden or supplemented.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SessionEntityType Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+/entityTypes/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Deletes all active contexts in the specified session.</summary>
/// <param name="parent">Required. The name of the session to delete all contexts from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If `Environment ID` is not
/// specified we assume default 'draft' environment. If `User ID` is not specified, we assume default '-'
/// user.</param>
public virtual DeleteContextsRequest DeleteContexts(string parent)
{
return new DeleteContextsRequest(service, parent);
}
/// <summary>Deletes all active contexts in the specified session.</summary>
public class DeleteContextsRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new DeleteContexts request.</summary>
public DeleteContextsRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The name of the session to delete all contexts from. Format:
/// `projects//agent/sessions/` or `projects//agent/environments//users//sessions/`. If `Environment
/// ID` is not specified we assume default 'draft' environment. If `User ID` is not specified, we
/// assume default '-' user.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "deleteContexts"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/contexts"; }
}
/// <summary>Initializes DeleteContexts parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+$",
});
}
}
/// <summary>Processes a natural language query and returns structured, actionable data as a result.
/// This method is not idempotent, because it may cause contexts and session entity types to be updated,
/// which in turn might affect results of future queries.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="session">Required. The name of the session this query is sent to. Format: `projects//agent/sessions/`,
/// or `projects//agent/environments//users//sessions/`. If `Environment ID` is not specified, we assume default 'draft'
/// environment. If `User ID` is not specified, we are using "-". It’s up to the API caller to choose an appropriate
/// `Session ID` and `User Id`. They can be a random numbers or some type of user and session identifiers (preferably
/// hashed). The length of the `Session ID` and `User ID` must not exceed 36 characters.</param>
public virtual DetectIntentRequest DetectIntent(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentRequest body, string session)
{
return new DetectIntentRequest(service, body, session);
}
/// <summary>Processes a natural language query and returns structured, actionable data as a result.
/// This method is not idempotent, because it may cause contexts and session entity types to be updated,
/// which in turn might affect results of future queries.</summary>
public class DetectIntentRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentResponse>
{
/// <summary>Constructs a new DetectIntent request.</summary>
public DetectIntentRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentRequest body, string session)
: base(service)
{
Session = session;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the session this query is sent to. Format:
/// `projects//agent/sessions/`, or `projects//agent/environments//users//sessions/`. If
/// `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not
/// specified, we are using "-". It’s up to the API caller to choose an appropriate `Session ID` and
/// `User Id`. They can be a random numbers or some type of user and session identifiers (preferably
/// hashed). The length of the `Session ID` and `User ID` must not exceed 36 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("session", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Session { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1DetectIntentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "detectIntent"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+session}:detectIntent"; }
}
/// <summary>Initializes DetectIntent parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"session", new Google.Apis.Discovery.Parameter
{
Name = "session",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/agent/sessions/[^/]+$",
});
}
}
}
/// <summary>Exports the specified agent to a ZIP file.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project that the agent to export is associated with. Format:
/// `projects/`.</param>
public virtual ExportRequest Export(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ExportAgentRequest body, string parent)
{
return new ExportRequest(service, body, parent);
}
/// <summary>Exports the specified agent to a ZIP file.
///
/// Operation </summary>
public class ExportRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Export request.</summary>
public ExportRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ExportAgentRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project that the agent to export is associated with. Format:
/// `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ExportAgentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "export"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/agent:export"; }
}
/// <summary>Initializes Export parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>Imports the specified agent from a ZIP file.
///
/// Uploads new intents and entity types without deleting the existing ones. Intents and entity types with
/// the same name are replaced with the new versions from ImportAgentRequest.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project that the agent to import is associated with. Format:
/// `projects/`.</param>
public virtual ImportRequest Import(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ImportAgentRequest body, string parent)
{
return new ImportRequest(service, body, parent);
}
/// <summary>Imports the specified agent from a ZIP file.
///
/// Uploads new intents and entity types without deleting the existing ones. Intents and entity types with
/// the same name are replaced with the new versions from ImportAgentRequest.
///
/// Operation </summary>
public class ImportRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Import request.</summary>
public ImportRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ImportAgentRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project that the agent to import is associated with. Format:
/// `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ImportAgentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "import"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/agent:import"; }
}
/// <summary>Initializes Import parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>Restores the specified agent from a ZIP file.
///
/// Replaces the current agent version with a new one. All the intents and entity types in the older version
/// are deleted.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project that the agent to restore is associated with. Format:
/// `projects/`.</param>
public virtual RestoreRequest Restore(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1RestoreAgentRequest body, string parent)
{
return new RestoreRequest(service, body, parent);
}
/// <summary>Restores the specified agent from a ZIP file.
///
/// Replaces the current agent version with a new one. All the intents and entity types in the older version
/// are deleted.
///
/// Operation </summary>
public class RestoreRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Restore request.</summary>
public RestoreRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1RestoreAgentRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project that the agent to restore is associated with. Format:
/// `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1RestoreAgentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "restore"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/agent:restore"; }
}
/// <summary>Initializes Restore parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>Returns the list of agents.
///
/// Since there is at most one conversational agent per project, this method is useful primarily for listing
/// all agents across projects the caller has access to. One can achieve that with a wildcard project
/// collection id "-". Refer to [List Sub-Collections](https://cloud.google.com/apis/design/design_patterns
/// #list_sub-collections).</summary>
/// <param name="parent">Required. The project to list agents from. Format: `projects/`.</param>
public virtual SearchRequest Search(string parent)
{
return new SearchRequest(service, parent);
}
/// <summary>Returns the list of agents.
///
/// Since there is at most one conversational agent per project, this method is useful primarily for listing
/// all agents across projects the caller has access to. One can achieve that with a wildcard project
/// collection id "-". Refer to [List Sub-Collections](https://cloud.google.com/apis/design/design_patterns
/// #list_sub-collections).</summary>
public class SearchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1SearchAgentsResponse>
{
/// <summary>Constructs a new Search request.</summary>
public SearchRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The project to list agents from. Format: `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 100 and at
/// most 1000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional. The next_page_token value returned from a previous list request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "search"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/agent:search"; }
}
/// <summary>Initializes Search parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Trains the specified agent.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project that the agent to train is associated with. Format:
/// `projects/`.</param>
public virtual TrainRequest Train(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1TrainAgentRequest body, string parent)
{
return new TrainRequest(service, body, parent);
}
/// <summary>Trains the specified agent.
///
/// Operation </summary>
public class TrainRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Train request.</summary>
public TrainRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1TrainAgentRequest body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project that the agent to train is associated with. Format:
/// `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1TrainAgentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "train"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/agent:train"; }
}
/// <summary>Initializes Train parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
}
private readonly KnowledgeBasesResource knowledgeBases;
/// <summary>Gets the KnowledgeBases resource.</summary>
public virtual KnowledgeBasesResource KnowledgeBases
{
get { return knowledgeBases; }
}
/// <summary>The "knowledgeBases" collection of methods.</summary>
public class KnowledgeBasesResource
{
private const string Resource = "knowledgeBases";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public KnowledgeBasesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
documents = new DocumentsResource(service);
}
private readonly DocumentsResource documents;
/// <summary>Gets the Documents resource.</summary>
public virtual DocumentsResource Documents
{
get { return documents; }
}
/// <summary>The "documents" collection of methods.</summary>
public class DocumentsResource
{
private const string Resource = "documents";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DocumentsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a new document.
///
/// Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The knoweldge base to create a document for. Format:
/// `projects//knowledgeBases/`.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a new document.
///
/// Operation </summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The knoweldge base to create a document for. Format:
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/documents"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+$",
});
}
}
/// <summary>Deletes the specified document.
///
/// Operation </summary>
/// <param name="name">The name of the document to delete. Format: `projects//knowledgeBases//documents/`.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified document.
///
/// Operation </summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the document to delete. Format:
/// `projects//knowledgeBases//documents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+/documents/[^/]+$",
});
}
}
/// <summary>Retrieves the specified document.</summary>
/// <param name="name">Required. The name of the document to retrieve. Format
/// `projects//knowledgeBases//documents/`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified document.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the document to retrieve. Format
/// `projects//knowledgeBases//documents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+/documents/[^/]+$",
});
}
}
/// <summary>Returns the list of all documents of the knowledge base.</summary>
/// <param name="parent">Required. The knowledge base to list all documents for. Format:
/// `projects//knowledgeBases/`.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all documents of the knowledge base.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListDocumentsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The knowledge base to list all documents for. Format:
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 10 and at
/// most 100.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/documents"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified document. Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The document resource name. The name must be empty when creating a document. Format:
/// `projects//knowledgeBases//documents/`.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified document. Operation </summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The document resource name. The name must be empty when creating a document. Format:
/// `projects//knowledgeBases//documents/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. Not specified means `update all`. Currently, only `display_name` can be
/// updated, an InvalidArgument will be returned for attempting to update other fields.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Document Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+/documents/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Reloads the specified document from its specified source, content_uri or content. The
/// previously loaded content of the document will be deleted. Note: Even when the content of the
/// document has not changed, there still may be side effects because of internal implementation
/// changes. Operation </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the document to reload. Format: `projects//knowledgeBases//documents/`</param>
public virtual ReloadRequest Reload(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ReloadDocumentRequest body, string name)
{
return new ReloadRequest(service, body, name);
}
/// <summary>Reloads the specified document from its specified source, content_uri or content. The
/// previously loaded content of the document will be deleted. Note: Even when the content of the
/// document has not changed, there still may be side effects because of internal implementation
/// changes. Operation </summary>
public class ReloadRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Reload request.</summary>
public ReloadRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ReloadDocumentRequest body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the document to reload. Format:
/// `projects//knowledgeBases//documents/`</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ReloadDocumentRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "reload"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}:reload"; }
}
/// <summary>Initializes Reload parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+/documents/[^/]+$",
});
}
}
}
/// <summary>Creates a knowledge base.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project to create a knowledge base for. Format: `projects/`.</param>
public virtual CreateRequest Create(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a knowledge base.</summary>
public class CreateRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string parent)
: base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project to create a knowledge base for. Format: `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/knowledgeBases"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>Deletes the specified knowledge base.</summary>
/// <param name="name">Required. The name of the knowledge base to delete. Format:
/// `projects//knowledgeBases/`.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes the specified knowledge base.</summary>
public class DeleteRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleProtobufEmpty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the knowledge base to delete. Format:
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. Force deletes the knowledge base. When set to true, any documents in the
/// knowledge base are also deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("force", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Force { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+$",
});
RequestParameters.Add(
"force", new Google.Apis.Discovery.Parameter
{
Name = "force",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves the specified knowledge base.</summary>
/// <param name="name">Required. The name of the knowledge base to retrieve. Format
/// `projects//knowledgeBases/`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Retrieves the specified knowledge base.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the knowledge base to retrieve. Format
/// `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+$",
});
}
}
/// <summary>Returns the list of all knowledge bases of the specified agent.</summary>
/// <param name="parent">Required. The project to list of knowledge bases for. Format: `projects/`.</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Returns the list of all knowledge bases of the specified agent.</summary>
public class ListRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1ListKnowledgeBasesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The project to list of knowledge bases for. Format: `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. The next_page_token value returned from a previous list request.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional. The maximum number of items to return in a single page. By default 10 and at most
/// 100.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/knowledgeBases"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the specified knowledge base.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The knowledge base resource name. The name must be empty when creating a knowledge base. Format:
/// `projects//knowledgeBases/`.</param>
public virtual PatchRequest Patch(Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the specified knowledge base.</summary>
public class PatchRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The knowledge base resource name. The name must be empty when creating a knowledge base.
/// Format: `projects//knowledgeBases/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. Not specified means `update all`. Currently, only `display_name` can be updated,
/// an InvalidArgument will be returned for attempting to update other fields.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1KnowledgeBase Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/knowledgeBases/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
private readonly OperationsResource operations;
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations
{
get { return operations; }
}
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.</summary>
public class GetRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleLongrunningOperation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/operations/[^/]+$",
});
}
}
}
/// <summary>Retrieves the specified agent.</summary>
/// <param name="parent">Required. The project that the agent to fetch is associated with. Format:
/// `projects/`.</param>
public virtual GetAgentRequest GetAgent(string parent)
{
return new GetAgentRequest(service, parent);
}
/// <summary>Retrieves the specified agent.</summary>
public class GetAgentRequest : DialogflowBaseServiceRequest<Google.Apis.Dialogflow.v2beta1.Data.GoogleCloudDialogflowV2beta1Agent>
{
/// <summary>Constructs a new GetAgent request.</summary>
public GetAgentRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The project that the agent to fetch is associated with. Format:
/// `projects/`.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getAgent"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2beta1/{+parent}/agent"; }
}
/// <summary>Initializes GetAgent parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
}
}
namespace Google.Apis.Dialogflow.v2beta1.Data
{
/// <summary>The response message for EntityTypes.BatchUpdateEntityTypes.</summary>
public class GoogleCloudDialogflowV2BatchUpdateEntityTypesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The collection of updated or created entity types.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypes")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2EntityType> EntityTypes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Intents.BatchUpdateIntents.</summary>
public class GoogleCloudDialogflowV2BatchUpdateIntentsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The collection of updated or created intents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2Intent> Intents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a context.</summary>
public class GoogleCloudDialogflowV2Context : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The number of conversational query requests after which the context expires. If set to
/// `0` (the default) the context expires immediately. Contexts expire automatically after 20 minutes even if
/// there are no matching queries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lifespanCount")]
public virtual System.Nullable<int> LifespanCount { get; set; }
/// <summary>Required. The unique identifier of the context. Format: `projects//agent/sessions//contexts/`.
///
/// The `Context ID` is always converted to lowercase, may only contain characters in [a-zA-Z0-9_-%] and may be
/// at most 250 bytes long.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of parameters associated with this context. Refer to [this
/// doc](https://dialogflow.com/docs/actions-and-parameters) for syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IDictionary<string,object> Parameters { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an entity type. Entity types serve as a tool for extracting parameter values from natural
/// language queries.</summary>
public class GoogleCloudDialogflowV2EntityType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Indicates whether the entity type can be automatically expanded.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("autoExpansionMode")]
public virtual string AutoExpansionMode { get; set; }
/// <summary>Required. The name of the entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. The collection of entities associated with the entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entities")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2EntityTypeEntity> Entities { get; set; }
/// <summary>Required. Indicates the kind of entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Required for all methods except `create` (`create` populates the name automatically. The unique
/// identifier of the entity type. Format: `projects//agent/entityTypes/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Optional. Represents an entity.</summary>
public class GoogleCloudDialogflowV2EntityTypeEntity : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. A collection of synonyms. For `KIND_LIST` entity types this must contain exactly one
/// synonym equal to `value`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("synonyms")]
public virtual System.Collections.Generic.IList<string> Synonyms { get; set; }
/// <summary>Required. For `KIND_MAP` entity types: A canonical name to be used in place of synonyms. For
/// `KIND_LIST` entity types: A string that can contain references to other entity types (with or without
/// aliases).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Events allow for matching intents by event name instead of the natural language input. For instance,
/// input `` can trigger a personalized welcome response. The parameter `name` may be used by the agent in the
/// response: `“Hello #welcome_event.name! What can I do for you today?”`.</summary>
public class GoogleCloudDialogflowV2EventInput : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The language of this query. See [Language Support](https://dialogflow.com/docs/languages)
/// for a list of the currently supported language codes. Note that queries in the same session do not
/// necessarily need to specify the same language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Required. The unique identifier of the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of parameters associated with the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IDictionary<string,object> Parameters { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Agents.ExportAgent.</summary>
public class GoogleCloudDialogflowV2ExportAgentResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The exported agent.
///
/// Example for how to export an agent to a zip file via a command line: curl \
/// 'https://dialogflow.googleapis.com/v2/projects/project_name/agent:export'\ -X POST \ -H 'Authorization:
/// Bearer '$(gcloud auth application-default print-access-token) \ -H 'Accept: application/json' \ -H 'Content-
/// Type: application/json' \ --compressed \ --data-binary '{}' \ | grep agentContent | sed -e
/// 's/.*"agentContent": "\([^"]*\)".\1/' \ | base64 --decode > agent zip file</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentContent")]
public virtual string AgentContent { get; set; }
/// <summary>The URI to a file containing the exported agent. This field is populated only if `agent_uri` is
/// specified in `ExportAgentRequest`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUri")]
public virtual string AgentUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an intent. Intents convert a number of user expressions or patterns into an action. An
/// action is an extraction of a user command or sentence semantics.</summary>
public class GoogleCloudDialogflowV2Intent : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The name of the action associated with the intent. Note: The action name must not contain
/// whitespaces.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("action")]
public virtual string Action { get; set; }
/// <summary>Optional. The list of platforms for which the first response will be taken from among the messages
/// assigned to the DEFAULT_PLATFORM.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultResponsePlatforms")]
public virtual System.Collections.Generic.IList<string> DefaultResponsePlatforms { get; set; }
/// <summary>Required. The name of this intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. The collection of event names that trigger the intent. If the collection of input
/// contexts is not empty, all of the contexts must be present in the active user session for an event to
/// trigger this intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("events")]
public virtual System.Collections.Generic.IList<string> Events { get; set; }
/// <summary>Read-only. Information about all followup intents that have this intent as a direct or indirect
/// parent. We populate this field only in the output.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followupIntentInfo")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentFollowupIntentInfo> FollowupIntentInfo { get; set; }
/// <summary>Optional. The list of context names required for this intent to be triggered. Format:
/// `projects//agent/sessions/-/contexts/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputContextNames")]
public virtual System.Collections.Generic.IList<string> InputContextNames { get; set; }
/// <summary>Optional. Indicates whether this is a fallback intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isFallback")]
public virtual System.Nullable<bool> IsFallback { get; set; }
/// <summary>Optional. The collection of rich messages corresponding to the `Response` field in the Dialogflow
/// console.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("messages")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessage> Messages { get; set; }
/// <summary>Optional. Indicates whether Machine Learning is disabled for the intent. Note: If `ml_diabled`
/// setting is set to true, then this intent is not taken into account during inference in `ML ONLY` match mode.
/// Also, auto-markup in the UI is turned off.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mlDisabled")]
public virtual System.Nullable<bool> MlDisabled { get; set; }
/// <summary>Required for all methods except `create` (`create` populates the name automatically. The unique
/// identifier of this intent. Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of contexts that are activated when the intent is matched. Context
/// messages in this collection should not set the parameters field. Setting the `lifespan_count` to 0 will
/// reset the context when the intent is matched. Format: `projects//agent/sessions/-/contexts/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputContexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2Context> OutputContexts { get; set; }
/// <summary>Optional. The collection of parameters associated with the intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentParameter> Parameters { get; set; }
/// <summary>Read-only after creation. The unique identifier of the parent intent in the chain of followup
/// intents. You can set this field when creating an intent, for example with CreateIntent or
/// BatchUpdateIntents, in order to make this intent a followup intent.
///
/// It identifies the parent followup intent. Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentFollowupIntentName")]
public virtual string ParentFollowupIntentName { get; set; }
/// <summary>Optional. The priority of this intent. Higher numbers represent higher priorities. If this is zero
/// or unspecified, we use the default priority 500000.
///
/// Negative numbers mean that the intent is disabled.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("priority")]
public virtual System.Nullable<int> Priority { get; set; }
/// <summary>Optional. Indicates whether to delete all contexts in the current session when this intent is
/// matched.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resetContexts")]
public virtual System.Nullable<bool> ResetContexts { get; set; }
/// <summary>Read-only. The unique identifier of the root intent in the chain of followup intents. It identifies
/// the correct followup intents chain for this intent. We populate this field only in the output.
///
/// Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rootFollowupIntentName")]
public virtual string RootFollowupIntentName { get; set; }
/// <summary>Optional. The collection of examples/templates that the agent is trained on.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trainingPhrases")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentTrainingPhrase> TrainingPhrases { get; set; }
/// <summary>Optional. Indicates whether webhooks are enabled for the intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookState")]
public virtual string WebhookState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a single followup intent in the chain.</summary>
public class GoogleCloudDialogflowV2IntentFollowupIntentInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The unique identifier of the followup intent. Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followupIntentName")]
public virtual string FollowupIntentName { get; set; }
/// <summary>The unique identifier of the followup intent's parent. Format:
/// `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentFollowupIntentName")]
public virtual string ParentFollowupIntentName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Corresponds to the `Response` field in the Dialogflow console.</summary>
public class GoogleCloudDialogflowV2IntentMessage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The basic card response for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("basicCard")]
public virtual GoogleCloudDialogflowV2IntentMessageBasicCard BasicCard { get; set; }
/// <summary>The card response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("card")]
public virtual GoogleCloudDialogflowV2IntentMessageCard Card { get; set; }
/// <summary>The carousel card response for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("carouselSelect")]
public virtual GoogleCloudDialogflowV2IntentMessageCarouselSelect CarouselSelect { get; set; }
/// <summary>The image response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2IntentMessageImage Image { get; set; }
/// <summary>The link out suggestion chip for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("linkOutSuggestion")]
public virtual GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion LinkOutSuggestion { get; set; }
/// <summary>The list card response for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("listSelect")]
public virtual GoogleCloudDialogflowV2IntentMessageListSelect ListSelect { get; set; }
/// <summary>Returns a response containing a custom, platform-specific payload. See the Intent.Message.Platform
/// type for a description of the structure that may be required for your platform.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>Optional. The platform that this message is intended for.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platform")]
public virtual string Platform { get; set; }
/// <summary>The quick replies response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("quickReplies")]
public virtual GoogleCloudDialogflowV2IntentMessageQuickReplies QuickReplies { get; set; }
/// <summary>The voice and text-only responses for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("simpleResponses")]
public virtual GoogleCloudDialogflowV2IntentMessageSimpleResponses SimpleResponses { get; set; }
/// <summary>The suggestion chips for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("suggestions")]
public virtual GoogleCloudDialogflowV2IntentMessageSuggestions Suggestions { get; set; }
/// <summary>The text response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual GoogleCloudDialogflowV2IntentMessageText Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The basic card message. Useful for displaying information.</summary>
public class GoogleCloudDialogflowV2IntentMessageBasicCard : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of card buttons.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("buttons")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessageBasicCardButton> Buttons { get; set; }
/// <summary>Required, unless image is present. The body text of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("formattedText")]
public virtual string FormattedText { get; set; }
/// <summary>Optional. The image for the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2IntentMessageImage Image { get; set; }
/// <summary>Optional. The subtitle of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subtitle")]
public virtual string Subtitle { get; set; }
/// <summary>Optional. The title of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The button object that appears at the bottom of a card.</summary>
public class GoogleCloudDialogflowV2IntentMessageBasicCardButton : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Action to take when a user taps on the button.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("openUriAction")]
public virtual GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction OpenUriAction { get; set; }
/// <summary>Required. The title of the button.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Opens the given URI.</summary>
public class GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The HTTP or HTTPS scheme URI.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uri")]
public virtual string Uri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The card response message.</summary>
public class GoogleCloudDialogflowV2IntentMessageCard : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of card buttons.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("buttons")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessageCardButton> Buttons { get; set; }
/// <summary>Optional. The public URI to an image file for the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("imageUri")]
public virtual string ImageUri { get; set; }
/// <summary>Optional. The subtitle of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subtitle")]
public virtual string Subtitle { get; set; }
/// <summary>Optional. The title of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Optional. Contains information about a button.</summary>
public class GoogleCloudDialogflowV2IntentMessageCardButton : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The text to send back to the Dialogflow API or a URI to open.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("postback")]
public virtual string Postback { get; set; }
/// <summary>Optional. The text to show on the button.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The card for presenting a carousel of options to select from.</summary>
public class GoogleCloudDialogflowV2IntentMessageCarouselSelect : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Carousel items.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessageCarouselSelectItem> Items { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An item in the carousel.</summary>
public class GoogleCloudDialogflowV2IntentMessageCarouselSelectItem : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The body text of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Optional. The image to display.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2IntentMessageImage Image { get; set; }
/// <summary>Required. Additional info about the option item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("info")]
public virtual GoogleCloudDialogflowV2IntentMessageSelectItemInfo Info { get; set; }
/// <summary>Required. Title of the carousel item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The image response message.</summary>
public class GoogleCloudDialogflowV2IntentMessageImage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. A text description of the image to be used for accessibility, e.g., screen
/// readers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("accessibilityText")]
public virtual string AccessibilityText { get; set; }
/// <summary>Optional. The public URI to an image file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("imageUri")]
public virtual string ImageUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The suggestion chip message that allows the user to jump out to the app or website associated with this
/// agent.</summary>
public class GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The name of the app or site this chip is linking to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("destinationName")]
public virtual string DestinationName { get; set; }
/// <summary>Required. The URI of the app or site to open when the user taps the suggestion chip.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uri")]
public virtual string Uri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The card for presenting a list of options to select from.</summary>
public class GoogleCloudDialogflowV2IntentMessageListSelect : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. List items.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessageListSelectItem> Items { get; set; }
/// <summary>Optional. The overall title of the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An item in the list.</summary>
public class GoogleCloudDialogflowV2IntentMessageListSelectItem : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The main text describing the item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Optional. The image to display.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2IntentMessageImage Image { get; set; }
/// <summary>Required. Additional information about this option.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("info")]
public virtual GoogleCloudDialogflowV2IntentMessageSelectItemInfo Info { get; set; }
/// <summary>Required. The title of the list item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The quick replies response message.</summary>
public class GoogleCloudDialogflowV2IntentMessageQuickReplies : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of quick replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("quickReplies")]
public virtual System.Collections.Generic.IList<string> QuickReplies { get; set; }
/// <summary>Optional. The title of the collection of quick replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Additional info about the select item for when it is triggered in a dialog.</summary>
public class GoogleCloudDialogflowV2IntentMessageSelectItemInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. A unique key that will be sent back to the agent if this response is given.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>Optional. A list of synonyms that can also be used to trigger this item in dialog.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("synonyms")]
public virtual System.Collections.Generic.IList<string> Synonyms { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The simple response message containing speech or text.</summary>
public class GoogleCloudDialogflowV2IntentMessageSimpleResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The text to display.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayText")]
public virtual string DisplayText { get; set; }
/// <summary>One of text_to_speech or ssml must be provided. Structured spoken response to the user in the SSML
/// format. Mutually exclusive with text_to_speech.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssml")]
public virtual string Ssml { get; set; }
/// <summary>One of text_to_speech or ssml must be provided. The plain text of the speech output. Mutually
/// exclusive with ssml.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("textToSpeech")]
public virtual string TextToSpeech { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The collection of simple response candidates. This message in `QueryResult.fulfillment_messages` and
/// `WebhookResponse.fulfillment_messages` should contain only one `SimpleResponse`.</summary>
public class GoogleCloudDialogflowV2IntentMessageSimpleResponses : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The list of simple responses.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("simpleResponses")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessageSimpleResponse> SimpleResponses { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The suggestion chip message that the user can tap to quickly post a reply to the
/// conversation.</summary>
public class GoogleCloudDialogflowV2IntentMessageSuggestion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The text shown the in the suggestion chip.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The collection of suggestions.</summary>
public class GoogleCloudDialogflowV2IntentMessageSuggestions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The list of suggested replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("suggestions")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessageSuggestion> Suggestions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The text response message.</summary>
public class GoogleCloudDialogflowV2IntentMessageText : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of the agent's responses.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual System.Collections.Generic.IList<string> Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents intent parameters.</summary>
public class GoogleCloudDialogflowV2IntentParameter : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The default value to use when the `value` yields an empty result. Default values can be
/// extracted from contexts by using the following syntax: `#context_name.parameter_name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultValue")]
public virtual string DefaultValue { get; set; }
/// <summary>Required. The name of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. The name of the entity type, prefixed with `@`, that describes values of the parameter.
/// If the parameter is required, this must be provided.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypeDisplayName")]
public virtual string EntityTypeDisplayName { get; set; }
/// <summary>Optional. Indicates whether the parameter represents a list of values.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isList")]
public virtual System.Nullable<bool> IsList { get; set; }
/// <summary>Optional. Indicates whether the parameter is required. That is, whether the intent cannot be
/// completed without collecting the parameter value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mandatory")]
public virtual System.Nullable<bool> Mandatory { get; set; }
/// <summary>The unique identifier of this parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of prompts that the agent can present to the user in order to collect
/// value for the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("prompts")]
public virtual System.Collections.Generic.IList<string> Prompts { get; set; }
/// <summary>Optional. The definition of the parameter value. It can be: - a constant string, - a parameter
/// value defined as `$parameter_name`, - an original parameter value defined as `$parameter_name.original`, - a
/// parameter value from some context defined as `#context_name.parameter_name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an example or template that the agent is trained on.</summary>
public class GoogleCloudDialogflowV2IntentTrainingPhrase : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The unique identifier of this training phrase.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Required. The collection of training phrase parts (can be annotated). Fields: `entity_type`,
/// `alias` and `user_defined` should be populated only for the annotated parts of the training
/// phrase.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentTrainingPhrasePart> Parts { get; set; }
/// <summary>Optional. Indicates how many times this example or template was added to the intent. Each time a
/// developer adds an existing sample by editing an intent or training, this counter is increased.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timesAddedCount")]
public virtual System.Nullable<int> TimesAddedCount { get; set; }
/// <summary>Required. The type of the training phrase.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a part of a training phrase.</summary>
public class GoogleCloudDialogflowV2IntentTrainingPhrasePart : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The parameter name for the value extracted from the annotated part of the
/// example.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("alias")]
public virtual string Alias { get; set; }
/// <summary>Optional. The entity type name prefixed with `@`. This field is required for the annotated part of
/// the text and applies only to examples.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityType")]
public virtual string EntityType { get; set; }
/// <summary>Required. The text corresponding to the example or template, if there are no annotations. For
/// annotated examples, it is the text for one of the example's parts.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>Optional. Indicates whether the text was manually annotated by the developer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userDefined")]
public virtual System.Nullable<bool> UserDefined { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the contents of the original request that was passed to the `[Streaming]DetectIntent`
/// call.</summary>
public class GoogleCloudDialogflowV2OriginalDetectIntentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. This field is set to the value of the `QueryParameters.payload` field passed in the
/// request. Some integrations that query a Dialogflow agent may provide additional information in the payload.
///
/// In particular for the Telephony Gateway this field has the form: { "telephony": { "caller_id":
/// "+18558363987" } } Note: The caller ID field (`caller_id`) will be redacted for Standard Edition agents and
/// populated with the caller ID in [E.164 format](https://en.wikipedia.org/wiki/E.164) for Enterprise Edition
/// agents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>The source of this request, e.g., `google`, `facebook`, `slack`. It is set by Dialogflow-owned
/// servers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("source")]
public virtual string Source { get; set; }
/// <summary>Optional. The version of the protocol used for this request. This field is AoG-specific.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the result of conversational query or event processing.</summary>
public class GoogleCloudDialogflowV2QueryResult : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The action name from the matched intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("action")]
public virtual string Action { get; set; }
/// <summary>This field is set to: - `false` if the matched intent has required parameters and not all of the
/// required parameter values have been collected. - `true` if all required parameter values have been
/// collected, or if the matched intent doesn't contain any required parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allRequiredParamsPresent")]
public virtual System.Nullable<bool> AllRequiredParamsPresent { get; set; }
/// <summary>The free-form diagnostic info. For example, this field could contain webhook call latency. The
/// string keys of the Struct's fields map can change without notice.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("diagnosticInfo")]
public virtual System.Collections.Generic.IDictionary<string,object> DiagnosticInfo { get; set; }
/// <summary>The collection of rich messages to present to the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentMessages")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessage> FulfillmentMessages { get; set; }
/// <summary>The text to be pronounced to the user or shown on the screen.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentText")]
public virtual string FulfillmentText { get; set; }
/// <summary>The intent that matched the conversational query. Some, not all fields are filled in this message,
/// including but not limited to: `name`, `display_name` and `webhook_state`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intent")]
public virtual GoogleCloudDialogflowV2Intent Intent { get; set; }
/// <summary>The intent detection confidence. Values range from 0.0 (completely uncertain) to 1.0 (completely
/// certain). If there are `multiple knowledge_answers` messages, this value is set to the greatest
/// `knowledgeAnswers.match_confidence` value in the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intentDetectionConfidence")]
public virtual System.Nullable<float> IntentDetectionConfidence { get; set; }
/// <summary>The language that was triggered during intent detection. See [Language
/// Support](https://dialogflow.com/docs/reference/language) for a list of the currently supported language
/// codes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>The collection of output contexts. If applicable, `output_contexts.parameters` contains entries
/// with name `.original` containing the original parameter values before the query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputContexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2Context> OutputContexts { get; set; }
/// <summary>The collection of extracted parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IDictionary<string,object> Parameters { get; set; }
/// <summary>The original conversational query text: - If natural language text was provided as input,
/// `query_text` contains a copy of the input. - If natural language speech audio was provided as input,
/// `query_text` contains the speech recognition result. If speech recognizer produced multiple alternatives, a
/// particular one is picked. - If an event was provided as input, `query_text` is not set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryText")]
public virtual string QueryText { get; set; }
/// <summary>The Speech recognition confidence between 0.0 and 1.0. A higher number indicates an estimated
/// greater likelihood that the recognized words are correct. The default of 0.0 is a sentinel value indicating
/// that confidence was not set.
///
/// This field is not guaranteed to be accurate or set. In particular this field isn't set for
/// StreamingDetectIntent since the streaming endpoint has separate confidence estimates per portion of the
/// audio in StreamingRecognitionResult.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("speechRecognitionConfidence")]
public virtual System.Nullable<float> SpeechRecognitionConfidence { get; set; }
/// <summary>If the query was fulfilled by a webhook call, this field is set to the value of the `payload` field
/// returned in the webhook response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookPayload")]
public virtual System.Collections.Generic.IDictionary<string,object> WebhookPayload { get; set; }
/// <summary>If the query was fulfilled by a webhook call, this field is set to the value of the `source` field
/// returned in the webhook response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookSource")]
public virtual string WebhookSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for a webhook call.</summary>
public class GoogleCloudDialogflowV2WebhookRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The contents of the original request that was passed to `[Streaming]DetectIntent`
/// call.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("originalDetectIntentRequest")]
public virtual GoogleCloudDialogflowV2OriginalDetectIntentRequest OriginalDetectIntentRequest { get; set; }
/// <summary>The result of the conversational query or event processing. Contains the same value as
/// `[Streaming]DetectIntentResponse.query_result`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryResult")]
public virtual GoogleCloudDialogflowV2QueryResult QueryResult { get; set; }
/// <summary>The unique identifier of the response. Contains the same value as
/// `[Streaming]DetectIntentResponse.response_id`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseId")]
public virtual string ResponseId { get; set; }
/// <summary>The unique identifier of detectIntent request session. Can be used to identify end-user inside
/// webhook implementation. Format: `projects//agent/sessions/`, or
/// `projects//agent/environments//users//sessions/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("session")]
public virtual string Session { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for a webhook call.</summary>
public class GoogleCloudDialogflowV2WebhookResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Makes the platform immediately invoke another `DetectIntent` call internally with the
/// specified event as input.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followupEventInput")]
public virtual GoogleCloudDialogflowV2EventInput FollowupEventInput { get; set; }
/// <summary>Optional. The collection of rich messages to present to the user. This value is passed directly to
/// `QueryResult.fulfillment_messages`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentMessages")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2IntentMessage> FulfillmentMessages { get; set; }
/// <summary>Optional. The text to be shown on the screen. This value is passed directly to
/// `QueryResult.fulfillment_text`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentText")]
public virtual string FulfillmentText { get; set; }
/// <summary>Optional. The collection of output contexts. This value is passed directly to
/// `QueryResult.output_contexts`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputContexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2Context> OutputContexts { get; set; }
/// <summary>Optional. This value is passed directly to `QueryResult.webhook_payload`. See the related
/// `fulfillment_messages[i].payload field`, which may be used as an alternative to this field.
///
/// This field can be used for Actions on Google responses. It should have a structure similar to the JSON
/// message shown here. For more information, see [Actions on Google Webhook
/// Format](https://developers.google.com/actions/dialogflow/webhook) { "google": { "expectUserResponse": true,
/// "richResponse": { "items": [ { "simpleResponse": { "textToSpeech": "this is a simple response" } } ] } }
/// }</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>Optional. This value is passed directly to `QueryResult.webhook_source`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("source")]
public virtual string Source { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a conversational agent.</summary>
public class GoogleCloudDialogflowV2beta1Agent : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The URI of the agent's avatar. Avatars are used throughout the Dialogflow console and in
/// the self-hosted [Web Demo](https://dialogflow.com/docs/integrations/web-demo) integration.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("avatarUri")]
public virtual string AvatarUri { get; set; }
/// <summary>Optional. To filter out false positive results and still get variety in matched natural language
/// inputs for your agent, you can tune the machine learning classification threshold. If the returned score
/// value is less than the threshold value, then a fallback intent is be triggered or, if there are no fallback
/// intents defined, no intent will be triggered. The score values range from 0.0 (completely uncertain) to 1.0
/// (completely certain). If set to 0.0, the default of 0.3 is used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("classificationThreshold")]
public virtual System.Nullable<float> ClassificationThreshold { get; set; }
/// <summary>Required. The default language of the agent as a language tag. See [Language
/// Support](https://dialogflow.com/docs/reference/language) for a list of the currently supported language
/// codes. This field cannot be set by the `Update` method.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultLanguageCode")]
public virtual string DefaultLanguageCode { get; set; }
/// <summary>Optional. The description of this agent. The maximum length is 500 characters. If exceeded, the
/// request is rejected.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Required. The name of this agent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. Determines whether this agent should log conversation queries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("enableLogging")]
public virtual System.Nullable<bool> EnableLogging { get; set; }
/// <summary>Optional. Determines how intents are detected from user queries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("matchMode")]
public virtual string MatchMode { get; set; }
/// <summary>Required. The project of this agent. Format: `projects/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parent")]
public virtual string Parent { get; set; }
/// <summary>Optional. The list of all languages supported by this agent (except for the
/// `default_language_code`).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("supportedLanguageCodes")]
public virtual System.Collections.Generic.IList<string> SupportedLanguageCodes { get; set; }
/// <summary>Required. The time zone of this agent from the [time zone database](https://www.iana.org/time-
/// zones), e.g., America/New_York, Europe/Paris.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeZone")]
public virtual string TimeZone { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for EntityTypes.BatchCreateEntities.</summary>
public class GoogleCloudDialogflowV2beta1BatchCreateEntitiesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The entities to create.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entities")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityTypeEntity> Entities { get; set; }
/// <summary>Optional. The language of entity synonyms defined in `entities`. If not specified, the agent's
/// default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are
/// supported. Note: languages must be enabled in the agent, before they can be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for EntityTypes.BatchDeleteEntities.</summary>
public class GoogleCloudDialogflowV2beta1BatchDeleteEntitiesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The canonical `values` of the entities to delete. Note that these are not fully-qualified
/// names, i.e. they don't start with `projects/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityValues")]
public virtual System.Collections.Generic.IList<string> EntityValues { get; set; }
/// <summary>Optional. The language of entity synonyms defined in `entities`. If not specified, the agent's
/// default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are
/// supported. Note: languages must be enabled in the agent, before they can be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for EntityTypes.BatchDeleteEntityTypes.</summary>
public class GoogleCloudDialogflowV2beta1BatchDeleteEntityTypesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The names entity types to delete. All names must point to the same agent as
/// `parent`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypeNames")]
public virtual System.Collections.Generic.IList<string> EntityTypeNames { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Intents.BatchDeleteIntents.</summary>
public class GoogleCloudDialogflowV2beta1BatchDeleteIntentsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The collection of intents to delete. Only intent `name` must be filled in.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Intent> Intents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for EntityTypes.BatchUpdateEntities.</summary>
public class GoogleCloudDialogflowV2beta1BatchUpdateEntitiesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The entities to update or create.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entities")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityTypeEntity> Entities { get; set; }
/// <summary>Optional. The language of entity synonyms defined in `entities`. If not specified, the agent's
/// default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are
/// supported. Note: languages must be enabled in the agent, before they can be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for EntityTypes.BatchUpdateEntityTypes.</summary>
public class GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The collection of entity types to update or create.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypeBatchInline")]
public virtual GoogleCloudDialogflowV2beta1EntityTypeBatch EntityTypeBatchInline { get; set; }
/// <summary>The URI to a Google Cloud Storage file containing entity types to update or create. The file format
/// can either be a serialized proto (of EntityBatch type) or a JSON object. Note: The URI must start with
/// "gs://".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypeBatchUri")]
public virtual string EntityTypeBatchUri { get; set; }
/// <summary>Optional. The language of entity synonyms defined in `entity_types`. If not specified, the agent's
/// default language is used. [More than a dozen languages](https://dialogflow.com/docs/reference/language) are
/// supported. Note: languages must be enabled in the agent, before they can be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for EntityTypes.BatchUpdateEntityTypes.</summary>
public class GoogleCloudDialogflowV2beta1BatchUpdateEntityTypesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The collection of updated or created entity types.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypes")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityType> EntityTypes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Intents.BatchUpdateIntents.</summary>
public class GoogleCloudDialogflowV2beta1BatchUpdateIntentsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The collection of intents to update or create.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intentBatchInline")]
public virtual GoogleCloudDialogflowV2beta1IntentBatch IntentBatchInline { get; set; }
/// <summary>The URI to a Google Cloud Storage file containing intents to update or create. The file format can
/// either be a serialized proto (of IntentBatch type) or JSON object. Note: The URI must start with
/// "gs://".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intentBatchUri")]
public virtual string IntentBatchUri { get; set; }
/// <summary>Optional. The resource view to apply to the returned intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intentView")]
public virtual string IntentView { get; set; }
/// <summary>Optional. The language of training phrases, parameters and rich messages defined in `intents`. If
/// not specified, the agent's default language is used. [More than a dozen
/// languages](https://dialogflow.com/docs/reference/language) are supported. Note: languages must be enabled in
/// the agent, before they can be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. The mask to control which fields get updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Intents.BatchUpdateIntents.</summary>
public class GoogleCloudDialogflowV2beta1BatchUpdateIntentsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The collection of updated or created intents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Intent> Intents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a context.</summary>
public class GoogleCloudDialogflowV2beta1Context : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The number of conversational query requests after which the context expires. If set to
/// `0` (the default) the context expires immediately. Contexts expire automatically after 10 minutes even if
/// there are no matching queries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lifespanCount")]
public virtual System.Nullable<int> LifespanCount { get; set; }
/// <summary>Required. The unique identifier of the context. Format: `projects//agent/sessions//contexts/`, or
/// `projects//agent/environments//users//sessions//contexts/`.
///
/// The `Context ID` is always converted to lowercase, may only contain characters in a-zA-Z0-9_-% and may be at
/// most 250 bytes long.
///
/// If `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not specified,
/// we assume default '-' user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of parameters associated with this context. Refer to [this
/// doc](https://dialogflow.com/docs/actions-and-parameters) for syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IDictionary<string,object> Parameters { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request to detect user's intent.</summary>
public class GoogleCloudDialogflowV2beta1DetectIntentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The natural language speech audio to be processed. This field should be populated iff
/// `query_input` is set to an input audio config. A single request can contain up to 1 minute of speech audio
/// data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputAudio")]
public virtual string InputAudio { get; set; }
/// <summary>Optional. Instructs the speech synthesizer how to generate the output audio. If this field is not
/// set and agent-level speech synthesizer is not configured, no output audio is generated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputAudioConfig")]
public virtual GoogleCloudDialogflowV2beta1OutputAudioConfig OutputAudioConfig { get; set; }
/// <summary>Required. The input specification. It can be set to:
///
/// 1. an audio config which instructs the speech recognizer how to process the speech audio,
///
/// 2. a conversational query in the form of text, or
///
/// 3. an event that specifies which intent to trigger.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryInput")]
public virtual GoogleCloudDialogflowV2beta1QueryInput QueryInput { get; set; }
/// <summary>Optional. The parameters of this query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryParams")]
public virtual GoogleCloudDialogflowV2beta1QueryParameters QueryParams { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The message returned from the DetectIntent method.</summary>
public class GoogleCloudDialogflowV2beta1DetectIntentResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If Knowledge Connectors are enabled, there could be more than one result returned for a given query
/// or event, and this field will contain all results except for the top one, which is captured in query_result.
/// The alternative results are ordered by decreasing `QueryResult.intent_detection_confidence`. If Knowledge
/// Connectors are disabled, this field will be empty until multiple responses for regular intents are
/// supported, at which point those additional results will be surfaced here.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("alternativeQueryResults")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1QueryResult> AlternativeQueryResults { get; set; }
/// <summary>The audio data bytes encoded as specified in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputAudio")]
public virtual string OutputAudio { get; set; }
/// <summary>Instructs the speech synthesizer how to generate the output audio. This field is populated from the
/// agent-level speech synthesizer configuration, if enabled.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputAudioConfig")]
public virtual GoogleCloudDialogflowV2beta1OutputAudioConfig OutputAudioConfig { get; set; }
/// <summary>The selected results of the conversational query or event processing. See
/// `alternative_query_results` for additional potential results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryResult")]
public virtual GoogleCloudDialogflowV2beta1QueryResult QueryResult { get; set; }
/// <summary>The unique identifier of the response. It can be used to locate a response in the training example
/// set or for reporting issues.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseId")]
public virtual string ResponseId { get; set; }
/// <summary>Specifies the status of the webhook request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookStatus")]
public virtual GoogleRpcStatus WebhookStatus { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A document resource.
///
/// Note: resource `projects.agent.knowledgeBases.documents` is deprecated, please use
/// `projects.knowledgeBases.documents` instead.</summary>
public class GoogleCloudDialogflowV2beta1Document : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ knowledge
/// types. Note: This field is in the process of being deprecated, please use raw_content instead.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("content")]
public virtual string Content { get; set; }
/// <summary>The URI where the file content is located.
///
/// For documents stored in Google Cloud Storage, these URIs must have the form `gs:`.
///
/// NOTE: External URLs must correspond to public webpages, i.e., they must be indexed by Google Search. In
/// particular, URLs for showing documents in Google Cloud Storage (i.e. the URL in your browser) are not
/// supported. Instead use the `gs://` format URI described above.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("contentUri")]
public virtual string ContentUri { get; set; }
/// <summary>Required. The display name of the document. The name must be 1024 bytes or less; otherwise, the
/// creation request fails.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Required. The knowledge type of document content.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("knowledgeTypes")]
public virtual System.Collections.Generic.IList<string> KnowledgeTypes { get; set; }
/// <summary>Required. The MIME type of this document.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>The document resource name. The name must be empty when creating a document. Format:
/// `projects//knowledgeBases//documents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The raw content of the document. This field is only permitted for EXTRACTIVE_QA and FAQ knowledge
/// types.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rawContent")]
public virtual string RawContent { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an entity type. Entity types serve as a tool for extracting parameter values from natural
/// language queries.</summary>
public class GoogleCloudDialogflowV2beta1EntityType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Indicates whether the entity type can be automatically expanded.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("autoExpansionMode")]
public virtual string AutoExpansionMode { get; set; }
/// <summary>Required. The name of the entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. The collection of entities associated with the entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entities")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityTypeEntity> Entities { get; set; }
/// <summary>Required. Indicates the kind of entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Required for all methods except `create` (`create` populates the name automatically. The unique
/// identifier of the entity type. Format: `projects//agent/entityTypes/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This message is a wrapper around a collection of entity types.</summary>
public class GoogleCloudDialogflowV2beta1EntityTypeBatch : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A collection of entity types.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypes")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityType> EntityTypes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Optional. Represents an entity.</summary>
public class GoogleCloudDialogflowV2beta1EntityTypeEntity : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. A collection of synonyms. For `KIND_LIST` entity types this must contain exactly one
/// synonym equal to `value`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("synonyms")]
public virtual System.Collections.Generic.IList<string> Synonyms { get; set; }
/// <summary>Required. For `KIND_MAP` entity types: A canonical name to be used in place of synonyms. For
/// `KIND_LIST` entity types: A string that can contain references to other entity types (with or without
/// aliases).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Events allow for matching intents by event name instead of the natural language input. For instance,
/// input `` can trigger a personalized welcome response. The parameter `name` may be used by the agent in the
/// response: `“Hello #welcome_event.name! What can I do for you today?”`.</summary>
public class GoogleCloudDialogflowV2beta1EventInput : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The language of this query. See [Language Support](https://dialogflow.com/docs/languages)
/// for a list of the currently supported language codes. Note that queries in the same session do not
/// necessarily need to specify the same language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Required. The unique identifier of the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of parameters associated with the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IDictionary<string,object> Parameters { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Agents.ExportAgent.</summary>
public class GoogleCloudDialogflowV2beta1ExportAgentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The [Google Cloud Storage](https://cloud.google.com/storage/docs/) URI to export the
/// agent to. The format of this URI must be `gs:`. If left unspecified, the serialized agent is returned
/// inline.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUri")]
public virtual string AgentUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Agents.ExportAgent.</summary>
public class GoogleCloudDialogflowV2beta1ExportAgentResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The exported agent.
///
/// Example for how to export an agent to a zip file via a command line: curl \
/// 'https://dialogflow.googleapis.com/v2beta1/projects/project_name/agent:export'\ -X POST \ -H 'Authorization:
/// Bearer '$(gcloud auth application-default print-access-token) \ -H 'Accept: application/json' \ -H 'Content-
/// Type: application/json' \ --compressed \ --data-binary '{}' \ | grep agentContent | sed -e
/// 's/.*"agentContent": "\([^"]*\)".\1/' \ | base64 --decode > agent zip file</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentContent")]
public virtual string AgentContent { get; set; }
/// <summary>The URI to a file containing the exported agent. This field is populated only if `agent_uri` is
/// specified in `ExportAgentRequest`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUri")]
public virtual string AgentUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Agents.ImportAgent.</summary>
public class GoogleCloudDialogflowV2beta1ImportAgentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The agent to import.
///
/// Example for how to import an agent via the command line: curl \
/// 'https://dialogflow.googleapis.com/v2beta1/projects/project_name/agent:import\ -X POST \ -H 'Authorization:
/// Bearer '$(gcloud auth application-default print-access-token) \ -H 'Accept: application/json' \ -H 'Content-
/// Type: application/json' \ --compressed \ --data-binary "{ 'agentContent': '$(cat agent zip file | base64 -w
/// 0)' }"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentContent")]
public virtual string AgentContent { get; set; }
/// <summary>The URI to a Google Cloud Storage file containing the agent to import. Note: The URI must start
/// with "gs://".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUri")]
public virtual string AgentUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Instructs the speech recognizer how to process the audio content.</summary>
public class GoogleCloudDialogflowV2beta1InputAudioConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Audio encoding of the audio content to process.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioEncoding")]
public virtual string AudioEncoding { get; set; }
/// <summary>Required. The language of the supplied audio. Dialogflow does not do translations. See [Language
/// Support](https://dialogflow.com/docs/languages) for a list of the currently supported language codes. Note
/// that queries in the same session do not necessarily need to specify the same language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Optional. Which Speech model to select for the given request. Select the model best suited to your
/// domain to get best results. If a model is not explicitly specified, then we auto-select a model based on the
/// parameters in the InputAudioConfig. If enhanced speech model is enabled for the agent and an enhanced
/// version of the specified model for the language does not exist, then the speech is recognized using the
/// standard version of the specified model. Refer to [Cloud Speech API documentation](https://cloud.google.com
/// /speech-to-text/docs/basics#select-model) for more details.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>Optional. The collection of phrase hints which are used to boost accuracy of speech recognition.
/// Refer to [Cloud Speech API documentation](https://cloud.google.com/speech-to-text/docs/basics#phrase-hints)
/// for more details.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("phraseHints")]
public virtual System.Collections.Generic.IList<string> PhraseHints { get; set; }
/// <summary>Required. Sample rate (in Hertz) of the audio content sent in the query. Refer to [Cloud Speech API
/// documentation](https://cloud.google.com/speech-to-text/docs/basics) for more details.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sampleRateHertz")]
public virtual System.Nullable<int> SampleRateHertz { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an intent. Intents convert a number of user expressions or patterns into an action. An
/// action is an extraction of a user command or sentence semantics.</summary>
public class GoogleCloudDialogflowV2beta1Intent : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The name of the action associated with the intent. Note: The action name must not contain
/// whitespaces.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("action")]
public virtual string Action { get; set; }
/// <summary>Optional. The list of platforms for which the first response will be taken from among the messages
/// assigned to the DEFAULT_PLATFORM.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultResponsePlatforms")]
public virtual System.Collections.Generic.IList<string> DefaultResponsePlatforms { get; set; }
/// <summary>Required. The name of this intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. Indicates that this intent ends an interaction. Some integrations (e.g., Actions on
/// Google or Dialogflow phone gateway) use this information to close interaction with an end user. Default is
/// false.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endInteraction")]
public virtual System.Nullable<bool> EndInteraction { get; set; }
/// <summary>Optional. The collection of event names that trigger the intent. If the collection of input
/// contexts is not empty, all of the contexts must be present in the active user session for an event to
/// trigger this intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("events")]
public virtual System.Collections.Generic.IList<string> Events { get; set; }
/// <summary>Read-only. Information about all followup intents that have this intent as a direct or indirect
/// parent. We populate this field only in the output.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followupIntentInfo")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentFollowupIntentInfo> FollowupIntentInfo { get; set; }
/// <summary>Optional. The list of context names required for this intent to be triggered. Format:
/// `projects//agent/sessions/-/contexts/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputContextNames")]
public virtual System.Collections.Generic.IList<string> InputContextNames { get; set; }
/// <summary>Optional. Indicates whether this is a fallback intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isFallback")]
public virtual System.Nullable<bool> IsFallback { get; set; }
/// <summary>Optional. The collection of rich messages corresponding to the `Response` field in the Dialogflow
/// console.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("messages")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessage> Messages { get; set; }
/// <summary>Optional. Indicates whether Machine Learning is disabled for the intent. Note: If `ml_disabled`
/// setting is set to true, then this intent is not taken into account during inference in `ML ONLY` match mode.
/// Also, auto-markup in the UI is turned off.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mlDisabled")]
public virtual System.Nullable<bool> MlDisabled { get; set; }
/// <summary>Optional. Indicates whether Machine Learning is enabled for the intent. Note: If `ml_enabled`
/// setting is set to false, then this intent is not taken into account during inference in `ML ONLY` match
/// mode. Also, auto-markup in the UI is turned off. DEPRECATED! Please use `ml_disabled` field instead. NOTE:
/// If both `ml_enabled` and `ml_disabled` are either not set or false, then the default value is determined as
/// follows: - Before April 15th, 2018 the default is: ml_enabled = false / ml_disabled = true. - After April
/// 15th, 2018 the default is: ml_enabled = true / ml_disabled = false.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mlEnabled")]
public virtual System.Nullable<bool> MlEnabled { get; set; }
/// <summary>Required for all methods except `create` (`create` populates the name automatically. The unique
/// identifier of this intent. Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of contexts that are activated when the intent is matched. Context
/// messages in this collection should not set the parameters field. Setting the `lifespan_count` to 0 will
/// reset the context when the intent is matched. Format: `projects//agent/sessions/-/contexts/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputContexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Context> OutputContexts { get; set; }
/// <summary>Optional. The collection of parameters associated with the intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentParameter> Parameters { get; set; }
/// <summary>Read-only after creation. The unique identifier of the parent intent in the chain of followup
/// intents. You can set this field when creating an intent, for example with CreateIntent or
/// BatchUpdateIntents, in order to make this intent a followup intent.
///
/// It identifies the parent followup intent. Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentFollowupIntentName")]
public virtual string ParentFollowupIntentName { get; set; }
/// <summary>Optional. The priority of this intent. Higher numbers represent higher priorities. If this is zero
/// or unspecified, we use the default priority 500000.
///
/// Negative numbers mean that the intent is disabled.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("priority")]
public virtual System.Nullable<int> Priority { get; set; }
/// <summary>Optional. Indicates whether to delete all contexts in the current session when this intent is
/// matched.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resetContexts")]
public virtual System.Nullable<bool> ResetContexts { get; set; }
/// <summary>Read-only. The unique identifier of the root intent in the chain of followup intents. It identifies
/// the correct followup intents chain for this intent. We populate this field only in the output.
///
/// Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rootFollowupIntentName")]
public virtual string RootFollowupIntentName { get; set; }
/// <summary>Optional. The collection of examples/templates that the agent is trained on.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trainingPhrases")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentTrainingPhrase> TrainingPhrases { get; set; }
/// <summary>Optional. Indicates whether webhooks are enabled for the intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookState")]
public virtual string WebhookState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This message is a wrapper around a collection of intents.</summary>
public class GoogleCloudDialogflowV2beta1IntentBatch : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A collection of intents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Intent> Intents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a single followup intent in the chain.</summary>
public class GoogleCloudDialogflowV2beta1IntentFollowupIntentInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The unique identifier of the followup intent. Format: `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followupIntentName")]
public virtual string FollowupIntentName { get; set; }
/// <summary>The unique identifier of the followup intent's parent. Format:
/// `projects//agent/intents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentFollowupIntentName")]
public virtual string ParentFollowupIntentName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Corresponds to the `Response` field in the Dialogflow console.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Displays a basic card for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("basicCard")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageBasicCard BasicCard { get; set; }
/// <summary>Displays a card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("card")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageCard Card { get; set; }
/// <summary>Displays a carousel card for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("carouselSelect")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageCarouselSelect CarouselSelect { get; set; }
/// <summary>Displays an image.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageImage Image { get; set; }
/// <summary>Displays a link out suggestion chip for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("linkOutSuggestion")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion LinkOutSuggestion { get; set; }
/// <summary>Displays a list card for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("listSelect")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageListSelect ListSelect { get; set; }
/// <summary>Returns a response containing a custom, platform-specific payload. See the Intent.Message.Platform
/// type for a description of the structure that may be required for your platform.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>Optional. The platform that this message is intended for.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("platform")]
public virtual string Platform { get; set; }
/// <summary>Displays quick replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("quickReplies")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageQuickReplies QuickReplies { get; set; }
/// <summary>Returns a voice or text-only response for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("simpleResponses")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageSimpleResponses SimpleResponses { get; set; }
/// <summary>Displays suggestion chips for Actions on Google.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("suggestions")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageSuggestions Suggestions { get; set; }
/// <summary>Plays audio from a file in Telephony Gateway.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("telephonyPlayAudio")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio TelephonyPlayAudio { get; set; }
/// <summary>Synthesizes speech in Telephony Gateway.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("telephonySynthesizeSpeech")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech TelephonySynthesizeSpeech { get; set; }
/// <summary>Transfers the call in Telephony Gateway.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("telephonyTransferCall")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall TelephonyTransferCall { get; set; }
/// <summary>Returns a text response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageText Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The basic card message. Useful for displaying information.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageBasicCard : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of card buttons.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("buttons")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton> Buttons { get; set; }
/// <summary>Required, unless image is present. The body text of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("formattedText")]
public virtual string FormattedText { get; set; }
/// <summary>Optional. The image for the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageImage Image { get; set; }
/// <summary>Optional. The subtitle of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subtitle")]
public virtual string Subtitle { get; set; }
/// <summary>Optional. The title of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The button object that appears at the bottom of a card.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageBasicCardButton : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Action to take when a user taps on the button.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("openUriAction")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenUriAction OpenUriAction { get; set; }
/// <summary>Required. The title of the button.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Opens the given URI.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageBasicCardButtonOpenUriAction : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The HTTP or HTTPS scheme URI.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uri")]
public virtual string Uri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The card response message.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageCard : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of card buttons.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("buttons")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessageCardButton> Buttons { get; set; }
/// <summary>Optional. The public URI to an image file for the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("imageUri")]
public virtual string ImageUri { get; set; }
/// <summary>Optional. The subtitle of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subtitle")]
public virtual string Subtitle { get; set; }
/// <summary>Optional. The title of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Optional. Contains information about a button.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageCardButton : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The text to send back to the Dialogflow API or a URI to open.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("postback")]
public virtual string Postback { get; set; }
/// <summary>Optional. The text to show on the button.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The card for presenting a carousel of options to select from.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageCarouselSelect : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Carousel items.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessageCarouselSelectItem> Items { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An item in the carousel.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageCarouselSelectItem : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The body text of the card.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Optional. The image to display.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageImage Image { get; set; }
/// <summary>Required. Additional info about the option item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("info")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo Info { get; set; }
/// <summary>Required. Title of the carousel item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The image response message.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageImage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A text description of the image to be used for accessibility, e.g., screen readers. Required if
/// image_uri is set for CarouselSelect.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("accessibilityText")]
public virtual string AccessibilityText { get; set; }
/// <summary>Optional. The public URI to an image file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("imageUri")]
public virtual string ImageUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The suggestion chip message that allows the user to jump out to the app or website associated with this
/// agent.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageLinkOutSuggestion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The name of the app or site this chip is linking to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("destinationName")]
public virtual string DestinationName { get; set; }
/// <summary>Required. The URI of the app or site to open when the user taps the suggestion chip.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uri")]
public virtual string Uri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The card for presenting a list of options to select from.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageListSelect : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. List items.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessageListSelectItem> Items { get; set; }
/// <summary>Optional. The overall title of the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An item in the list.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageListSelectItem : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The main text describing the item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Optional. The image to display.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("image")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageImage Image { get; set; }
/// <summary>Required. Additional information about this option.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("info")]
public virtual GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo Info { get; set; }
/// <summary>Required. The title of the list item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The quick replies response message.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageQuickReplies : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of quick replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("quickReplies")]
public virtual System.Collections.Generic.IList<string> QuickReplies { get; set; }
/// <summary>Optional. The title of the collection of quick replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Additional info about the select item for when it is triggered in a dialog.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageSelectItemInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. A unique key that will be sent back to the agent if this response is given.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>Optional. A list of synonyms that can also be used to trigger this item in dialog.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("synonyms")]
public virtual System.Collections.Generic.IList<string> Synonyms { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The simple response message containing speech or text.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageSimpleResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The text to display.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayText")]
public virtual string DisplayText { get; set; }
/// <summary>One of text_to_speech or ssml must be provided. Structured spoken response to the user in the SSML
/// format. Mutually exclusive with text_to_speech.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssml")]
public virtual string Ssml { get; set; }
/// <summary>One of text_to_speech or ssml must be provided. The plain text of the speech output. Mutually
/// exclusive with ssml.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("textToSpeech")]
public virtual string TextToSpeech { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The collection of simple response candidates. This message in `QueryResult.fulfillment_messages` and
/// `WebhookResponse.fulfillment_messages` should contain only one `SimpleResponse`.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageSimpleResponses : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The list of simple responses.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("simpleResponses")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessageSimpleResponse> SimpleResponses { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The suggestion chip message that the user can tap to quickly post a reply to the
/// conversation.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageSuggestion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The text shown the in the suggestion chip.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The collection of suggestions.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageSuggestions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The list of suggested replies.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("suggestions")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessageSuggestion> Suggestions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Plays audio from a file in Telephony Gateway.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageTelephonyPlayAudio : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. URI to a Google Cloud Storage object containing the audio to play, e.g.,
/// "gs://bucket/object". The object must contain a single channel (mono) of linear PCM audio (2 bytes / sample)
/// at 8kHz.
///
/// This object must be readable by the `service-@gcp-sa-dialogflow.iam.gserviceaccount.com` service account
/// where is the number of the Telephony Gateway project (usually the same as the Dialogflow agent project). If
/// the Google Cloud Storage bucket is in the Telephony Gateway project, this permission is added by default
/// when enabling the Dialogflow V2 API.
///
/// For audio from other sources, consider using the `TelephonySynthesizeSpeech` message with SSML.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioUri")]
public virtual string AudioUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Synthesizes speech and plays back the synthesized audio to the caller in Telephony Gateway.
///
/// Telephony Gateway takes the synthesizer settings from `DetectIntentResponse.output_audio_config` which can
/// either be set at request-level or can come from the agent-level synthesizer config.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageTelephonySynthesizeSpeech : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The SSML to be synthesized. For more information, see
/// [SSML](https://developers.google.com/actions/reference/ssml).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssml")]
public virtual string Ssml { get; set; }
/// <summary>The raw text to be synthesized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Transfers the call in Telephony Gateway.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageTelephonyTransferCall : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The phone number to transfer the call to in [E.164
/// format](https://en.wikipedia.org/wiki/E.164).
///
/// We currently only allow transferring to US numbers (+1xxxyyyzzzz).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("phoneNumber")]
public virtual string PhoneNumber { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The text response message.</summary>
public class GoogleCloudDialogflowV2beta1IntentMessageText : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of the agent's responses.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual System.Collections.Generic.IList<string> Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents intent parameters.</summary>
public class GoogleCloudDialogflowV2beta1IntentParameter : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The default value to use when the `value` yields an empty result. Default values can be
/// extracted from contexts by using the following syntax: `#context_name.parameter_name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultValue")]
public virtual string DefaultValue { get; set; }
/// <summary>Required. The name of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>Optional. The name of the entity type, prefixed with `@`, that describes values of the parameter.
/// If the parameter is required, this must be provided.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypeDisplayName")]
public virtual string EntityTypeDisplayName { get; set; }
/// <summary>Optional. Indicates whether the parameter represents a list of values.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isList")]
public virtual System.Nullable<bool> IsList { get; set; }
/// <summary>Optional. Indicates whether the parameter is required. That is, whether the intent cannot be
/// completed without collecting the parameter value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mandatory")]
public virtual System.Nullable<bool> Mandatory { get; set; }
/// <summary>The unique identifier of this parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The collection of prompts that the agent can present to the user in order to collect
/// value for the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("prompts")]
public virtual System.Collections.Generic.IList<string> Prompts { get; set; }
/// <summary>Optional. The definition of the parameter value. It can be: - a constant string, - a parameter
/// value defined as `$parameter_name`, - an original parameter value defined as `$parameter_name.original`, - a
/// parameter value from some context defined as `#context_name.parameter_name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an example or template that the agent is trained on.</summary>
public class GoogleCloudDialogflowV2beta1IntentTrainingPhrase : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The unique identifier of this training phrase.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Required. The collection of training phrase parts (can be annotated). Fields: `entity_type`,
/// `alias` and `user_defined` should be populated only for the annotated parts of the training
/// phrase.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart> Parts { get; set; }
/// <summary>Optional. Indicates how many times this example or template was added to the intent. Each time a
/// developer adds an existing sample by editing an intent or training, this counter is increased.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timesAddedCount")]
public virtual System.Nullable<int> TimesAddedCount { get; set; }
/// <summary>Required. The type of the training phrase.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a part of a training phrase.</summary>
public class GoogleCloudDialogflowV2beta1IntentTrainingPhrasePart : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The parameter name for the value extracted from the annotated part of the
/// example.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("alias")]
public virtual string Alias { get; set; }
/// <summary>Optional. The entity type name prefixed with `@`. This field is required for the annotated part of
/// the text and applies only to examples.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityType")]
public virtual string EntityType { get; set; }
/// <summary>Required. The text corresponding to the example or template, if there are no annotations. For
/// annotated examples, it is the text for one of the example's parts.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>Optional. Indicates whether the text was manually annotated by the developer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userDefined")]
public virtual System.Nullable<bool> UserDefined { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the result of querying a Knowledge base.</summary>
public class GoogleCloudDialogflowV2beta1KnowledgeAnswers : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of answers from Knowledge Connector.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("answers")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer> Answers { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An answer from Knowledge Connector.</summary>
public class GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The piece of text from the `source` knowledge base document that answers this conversational
/// query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("answer")]
public virtual string Answer { get; set; }
/// <summary>The corresponding FAQ question if the answer was extracted from a FAQ Document, empty
/// otherwise.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("faqQuestion")]
public virtual string FaqQuestion { get; set; }
/// <summary>The system's confidence score that this Knowledge answer is a good match for this conversational
/// query. The range is from 0.0 (completely uncertain) to 1.0 (completely certain). Note: The confidence score
/// is likely to vary somewhat (possibly even for identical requests), as the underlying model is under constant
/// improvement. It may be deprecated in the future. We recommend using `match_confidence_level` which should be
/// generally more stable.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("matchConfidence")]
public virtual System.Nullable<float> MatchConfidence { get; set; }
/// <summary>The system's confidence level that this knowledge answer is a good match for this conversational
/// query. NOTE: The confidence level for a given `` pair may change without notice, as it depends on models
/// that are constantly being improved. However, it will change less frequently than the confidence score below,
/// and should be preferred for referencing the quality of an answer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("matchConfidenceLevel")]
public virtual string MatchConfidenceLevel { get; set; }
/// <summary>Indicates which Knowledge Document this answer was extracted from. Format:
/// `projects//knowledgeBases//documents/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("source")]
public virtual string Source { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents knowledge base resource.
///
/// Note: resource `projects.agent.knowledgeBases` is deprecated, please use `projects.knowledgeBases`
/// instead.</summary>
public class GoogleCloudDialogflowV2beta1KnowledgeBase : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The display name of the knowledge base. The name must be 1024 bytes or less; otherwise,
/// the creation request fails.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>The knowledge base resource name. The name must be empty when creating a knowledge base. Format:
/// `projects//knowledgeBases/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Metadata in google::longrunning::Operation for Knowledge operations.</summary>
public class GoogleCloudDialogflowV2beta1KnowledgeOperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The current state of this operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Contexts.ListContexts.</summary>
public class GoogleCloudDialogflowV2beta1ListContextsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of contexts. There will be a maximum number of items returned based on the page_size field
/// in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("contexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Context> Contexts { get; set; }
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for Documents.ListDocuments.</summary>
public class GoogleCloudDialogflowV2beta1ListDocumentsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of documents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("documents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Document> Documents { get; set; }
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for EntityTypes.ListEntityTypes.</summary>
public class GoogleCloudDialogflowV2beta1ListEntityTypesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of agent entity types. There will be a maximum number of items returned based on the
/// page_size field in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityTypes")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityType> EntityTypes { get; set; }
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Intents.ListIntents.</summary>
public class GoogleCloudDialogflowV2beta1ListIntentsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of agent intents. There will be a maximum number of items returned based on the page_size
/// field in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Intent> Intents { get; set; }
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for KnowledgeBases.ListKnowledgeBases.</summary>
public class GoogleCloudDialogflowV2beta1ListKnowledgeBasesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of knowledge bases.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("knowledgeBases")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1KnowledgeBase> KnowledgeBases { get; set; }
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for SessionEntityTypes.ListSessionEntityTypes.</summary>
public class GoogleCloudDialogflowV2beta1ListSessionEntityTypesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of session entity types. There will be a maximum number of items returned based on the
/// page_size field in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sessionEntityTypes")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1SessionEntityType> SessionEntityTypes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the contents of the original request that was passed to the `[Streaming]DetectIntent`
/// call.</summary>
public class GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. This field is set to the value of the `QueryParameters.payload` field passed in the
/// request. Some integrations that query a Dialogflow agent may provide additional information in the payload.
///
/// In particular for the Telephony Gateway this field has the form: { "telephony": { "caller_id":
/// "+18558363987" } } Note: The caller ID field (`caller_id`) will be redacted for Standard Edition agents and
/// populated with the caller ID in [E.164 format](https://en.wikipedia.org/wiki/E.164) for Enterprise Edition
/// agents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>The source of this request, e.g., `google`, `facebook`, `slack`. It is set by Dialogflow-owned
/// servers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("source")]
public virtual string Source { get; set; }
/// <summary>Optional. The version of the protocol used for this request. This field is AoG-specific.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Instructs the speech synthesizer how to generate the output audio content.</summary>
public class GoogleCloudDialogflowV2beta1OutputAudioConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Audio encoding of the synthesized audio content.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioEncoding")]
public virtual string AudioEncoding { get; set; }
/// <summary>Optional. The synthesis sample rate (in hertz) for this audio. If not provided, then the
/// synthesizer will use the default sample rate based on the audio encoding. If this is different from the
/// voice's natural sample rate, then the synthesizer will honor this request by converting to the desired
/// sample rate (which might result in worse audio quality).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sampleRateHertz")]
public virtual System.Nullable<int> SampleRateHertz { get; set; }
/// <summary>Optional. Configuration of how speech should be synthesized.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("synthesizeSpeechConfig")]
public virtual GoogleCloudDialogflowV2beta1SynthesizeSpeechConfig SynthesizeSpeechConfig { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the query input. It can contain either:
///
/// 1. An audio config which instructs the speech recognizer how to process the speech audio.
///
/// 2. A conversational query in the form of text,.
///
/// 3. An event that specifies which intent to trigger.</summary>
public class GoogleCloudDialogflowV2beta1QueryInput : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Instructs the speech recognizer how to process the speech audio.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audioConfig")]
public virtual GoogleCloudDialogflowV2beta1InputAudioConfig AudioConfig { get; set; }
/// <summary>The event to be processed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("event")]
public virtual GoogleCloudDialogflowV2beta1EventInput Event__ { get; set; }
/// <summary>The natural language text to be processed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual GoogleCloudDialogflowV2beta1TextInput Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the parameters of the conversational query.</summary>
public class GoogleCloudDialogflowV2beta1QueryParameters : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The collection of contexts to be activated before this query is executed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("contexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Context> Contexts { get; set; }
/// <summary>Optional. The geo location of this conversational query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("geoLocation")]
public virtual GoogleTypeLatLng GeoLocation { get; set; }
/// <summary>Optional. KnowledgeBases to get alternative results from. If not set, the KnowledgeBases enabled in
/// the agent (through UI) will be used. Format: `projects//knowledgeBases/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("knowledgeBaseNames")]
public virtual System.Collections.Generic.IList<string> KnowledgeBaseNames { get; set; }
/// <summary>Optional. This field can be used to pass custom data into the webhook associated with the agent.
/// Arbitrary JSON objects are supported.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>Optional. Specifies whether to delete all contexts in the current session before the new ones are
/// activated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resetContexts")]
public virtual System.Nullable<bool> ResetContexts { get; set; }
/// <summary>Optional. Configures the type of sentiment analysis to perform. If not provided, sentiment analysis
/// is not performed. Note: Sentiment Analysis is only currently available for Enterprise Edition
/// agents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sentimentAnalysisRequestConfig")]
public virtual GoogleCloudDialogflowV2beta1SentimentAnalysisRequestConfig SentimentAnalysisRequestConfig { get; set; }
/// <summary>Optional. Additional session entity types to replace or extend developer entity types with. The
/// entity synonyms apply to all languages and persist for the session of this query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sessionEntityTypes")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1SessionEntityType> SessionEntityTypes { get; set; }
/// <summary>Optional. The time zone of this conversational query from the [time zone
/// database](https://www.iana.org/time-zones), e.g., America/New_York, Europe/Paris. If not provided, the time
/// zone specified in agent settings is used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeZone")]
public virtual string TimeZone { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the result of conversational query or event processing.</summary>
public class GoogleCloudDialogflowV2beta1QueryResult : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The action name from the matched intent.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("action")]
public virtual string Action { get; set; }
/// <summary>This field is set to: - `false` if the matched intent has required parameters and not all of the
/// required parameter values have been collected. - `true` if all required parameter values have been
/// collected, or if the matched intent doesn't contain any required parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allRequiredParamsPresent")]
public virtual System.Nullable<bool> AllRequiredParamsPresent { get; set; }
/// <summary>The free-form diagnostic info. For example, this field could contain webhook call latency. The
/// string keys of the Struct's fields map can change without notice.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("diagnosticInfo")]
public virtual System.Collections.Generic.IDictionary<string,object> DiagnosticInfo { get; set; }
/// <summary>The collection of rich messages to present to the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentMessages")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessage> FulfillmentMessages { get; set; }
/// <summary>The text to be pronounced to the user or shown on the screen.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentText")]
public virtual string FulfillmentText { get; set; }
/// <summary>The intent that matched the conversational query. Some, not all fields are filled in this message,
/// including but not limited to: `name`, `display_name` and `webhook_state`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intent")]
public virtual GoogleCloudDialogflowV2beta1Intent Intent { get; set; }
/// <summary>The intent detection confidence. Values range from 0.0 (completely uncertain) to 1.0 (completely
/// certain). If there are `multiple knowledge_answers` messages, this value is set to the greatest
/// `knowledgeAnswers.match_confidence` value in the list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intentDetectionConfidence")]
public virtual System.Nullable<float> IntentDetectionConfidence { get; set; }
/// <summary>The result from Knowledge Connector (if any), ordered by decreasing
/// `KnowledgeAnswers.match_confidence`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("knowledgeAnswers")]
public virtual GoogleCloudDialogflowV2beta1KnowledgeAnswers KnowledgeAnswers { get; set; }
/// <summary>The language that was triggered during intent detection. See [Language
/// Support](https://dialogflow.com/docs/reference/language) for a list of the currently supported language
/// codes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>The collection of output contexts. If applicable, `output_contexts.parameters` contains entries
/// with name `.original` containing the original parameter values before the query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputContexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Context> OutputContexts { get; set; }
/// <summary>The collection of extracted parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IDictionary<string,object> Parameters { get; set; }
/// <summary>The original conversational query text: - If natural language text was provided as input,
/// `query_text` contains a copy of the input. - If natural language speech audio was provided as input,
/// `query_text` contains the speech recognition result. If speech recognizer produced multiple alternatives, a
/// particular one is picked. - If an event was provided as input, `query_text` is not set.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryText")]
public virtual string QueryText { get; set; }
/// <summary>The sentiment analysis result, which depends on the `sentiment_analysis_request_config` specified
/// in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sentimentAnalysisResult")]
public virtual GoogleCloudDialogflowV2beta1SentimentAnalysisResult SentimentAnalysisResult { get; set; }
/// <summary>The Speech recognition confidence between 0.0 and 1.0. A higher number indicates an estimated
/// greater likelihood that the recognized words are correct. The default of 0.0 is a sentinel value indicating
/// that confidence was not set.
///
/// This field is not guaranteed to be accurate or set. In particular this field isn't set for
/// StreamingDetectIntent since the streaming endpoint has separate confidence estimates per portion of the
/// audio in StreamingRecognitionResult.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("speechRecognitionConfidence")]
public virtual System.Nullable<float> SpeechRecognitionConfidence { get; set; }
/// <summary>If the query was fulfilled by a webhook call, this field is set to the value of the `payload` field
/// returned in the webhook response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookPayload")]
public virtual System.Collections.Generic.IDictionary<string,object> WebhookPayload { get; set; }
/// <summary>If the query was fulfilled by a webhook call, this field is set to the value of the `source` field
/// returned in the webhook response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookSource")]
public virtual string WebhookSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for Documents.ReloadDocument.</summary>
public class GoogleCloudDialogflowV2beta1ReloadDocumentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Agents.RestoreAgent.</summary>
public class GoogleCloudDialogflowV2beta1RestoreAgentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The agent to restore.
///
/// Example for how to restore an agent via the command line: curl \
/// 'https://dialogflow.googleapis.com/v2beta1/projects/project_name/agent:restore\ -X POST \ -H 'Authorization:
/// Bearer '$(gcloud auth application-default print-access-token) \ -H 'Accept: application/json' \ -H 'Content-
/// Type: application/json' \ --compressed \ --data-binary "{ 'agentContent': '$(cat agent zip file | base64 -w
/// 0)' }"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentContent")]
public virtual string AgentContent { get; set; }
/// <summary>The URI to a Google Cloud Storage file containing the agent to restore. Note: The URI must start
/// with "gs://".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agentUri")]
public virtual string AgentUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Agents.SearchAgents.</summary>
public class GoogleCloudDialogflowV2beta1SearchAgentsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of agents. There will be a maximum number of items returned based on the page_size field
/// in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("agents")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Agent> Agents { get; set; }
/// <summary>Token to retrieve the next page of results, or empty if there are no more results in the
/// list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The sentiment, such as positive/negative feeling or association, for a unit of analysis, such as the
/// query text.</summary>
public class GoogleCloudDialogflowV2beta1Sentiment : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A non-negative number in the [0, +inf) range, which represents the absolute magnitude of sentiment,
/// regardless of score (positive or negative).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("magnitude")]
public virtual System.Nullable<float> Magnitude { get; set; }
/// <summary>Sentiment score between -1.0 (negative sentiment) and 1.0 (positive sentiment).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("score")]
public virtual System.Nullable<float> Score { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configures the types of sentiment analysis to perform.</summary>
public class GoogleCloudDialogflowV2beta1SentimentAnalysisRequestConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Instructs the service to perform sentiment analysis on `query_text`. If not provided,
/// sentiment analysis is not performed on `query_text`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analyzeQueryTextSentiment")]
public virtual System.Nullable<bool> AnalyzeQueryTextSentiment { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The result of sentiment analysis as configured by `sentiment_analysis_request_config`.</summary>
public class GoogleCloudDialogflowV2beta1SentimentAnalysisResult : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The sentiment analysis result for `query_text`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryTextSentiment")]
public virtual GoogleCloudDialogflowV2beta1Sentiment QueryTextSentiment { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a session entity type.
///
/// Extends or replaces a developer entity type at the user session level (we refer to the entity types defined at
/// the agent level as "developer entity types").
///
/// Note: session entity types apply to all queries, regardless of the language.</summary>
public class GoogleCloudDialogflowV2beta1SessionEntityType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The collection of entities associated with this session entity type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entities")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1EntityTypeEntity> Entities { get; set; }
/// <summary>Required. Indicates whether the additional data should override or supplement the developer entity
/// type definition.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityOverrideMode")]
public virtual string EntityOverrideMode { get; set; }
/// <summary>Required. The unique identifier of this session entity type. Format:
/// `projects//agent/sessions//entityTypes/`, or `projects//agent/environments//users//sessions//entityTypes/`.
/// If `Environment ID` is not specified, we assume default 'draft' environment. If `User ID` is not specified,
/// we assume default '-' user.
///
/// `` must be the display name of an existing entity type in the same agent that will be overridden or
/// supplemented.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configuration of how speech should be synthesized.</summary>
public class GoogleCloudDialogflowV2beta1SynthesizeSpeechConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. An identifier which selects 'audio effects' profiles that are applied on (post
/// synthesized) text to speech. Effects are applied on top of each other in the order they are given.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("effectsProfileId")]
public virtual System.Collections.Generic.IList<string> EffectsProfileId { get; set; }
/// <summary>Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20 semitones from the
/// original pitch. -20 means decrease 20 semitones from the original pitch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pitch")]
public virtual System.Nullable<double> Pitch { get; set; }
/// <summary>Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 is the normal native speed supported
/// by the specific voice. 2.0 is twice as fast, and 0.5 is half as fast. If unset(0.0), defaults to the native
/// 1.0 speed. Any other values < 0.25 or > 4.0 will return an error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("speakingRate")]
public virtual System.Nullable<double> SpeakingRate { get; set; }
/// <summary>Optional. The desired voice of the synthesized audio.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("voice")]
public virtual GoogleCloudDialogflowV2beta1VoiceSelectionParams Voice { get; set; }
/// <summary>Optional. Volume gain (in dB) of the normal native volume supported by the specific voice, in the
/// range [-96.0, 16.0]. If unset, or set to a value of 0.0 (dB), will play at normal native signal amplitude. A
/// value of -6.0 (dB) will play at approximately half the amplitude of the normal native signal amplitude. A
/// value of +6.0 (dB) will play at approximately twice the amplitude of the normal native signal amplitude. We
/// strongly recommend not to exceed +10 (dB) as there's usually no effective increase in loudness for any value
/// greater than that.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("volumeGainDb")]
public virtual System.Nullable<double> VolumeGainDb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the natural language text to be processed.</summary>
public class GoogleCloudDialogflowV2beta1TextInput : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The language of this conversational query. See [Language
/// Support](https://dialogflow.com/docs/languages) for a list of the currently supported language codes. Note
/// that queries in the same session do not necessarily need to specify the same language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Required. The UTF-8 encoded natural language text to be processed. Text length must not exceed 256
/// characters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("text")]
public virtual string Text { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Agents.TrainAgent.</summary>
public class GoogleCloudDialogflowV2beta1TrainAgentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Description of which voice to use for speech synthesis.</summary>
public class GoogleCloudDialogflowV2beta1VoiceSelectionParams : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The name of the voice. If not set, the service will choose a voice based on the other
/// parameters such as language_code and gender.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The preferred gender of the voice. If not set, the service will choose a voice based on
/// the other parameters such as language_code and name. Note that this is only a preference, not requirement.
/// If a voice of the appropriate gender is not available, the synthesizer should substitute a voice with a
/// different gender rather than failing the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ssmlGender")]
public virtual string SsmlGender { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for a webhook call.</summary>
public class GoogleCloudDialogflowV2beta1WebhookRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Alternative query results from KnowledgeService.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("alternativeQueryResults")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1QueryResult> AlternativeQueryResults { get; set; }
/// <summary>Optional. The contents of the original request that was passed to `[Streaming]DetectIntent`
/// call.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("originalDetectIntentRequest")]
public virtual GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest OriginalDetectIntentRequest { get; set; }
/// <summary>The result of the conversational query or event processing. Contains the same value as
/// `[Streaming]DetectIntentResponse.query_result`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryResult")]
public virtual GoogleCloudDialogflowV2beta1QueryResult QueryResult { get; set; }
/// <summary>The unique identifier of the response. Contains the same value as
/// `[Streaming]DetectIntentResponse.response_id`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("responseId")]
public virtual string ResponseId { get; set; }
/// <summary>The unique identifier of detectIntent request session. Can be used to identify end-user inside
/// webhook implementation. Format: `projects//agent/sessions/`, or
/// `projects//agent/environments//users//sessions/`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("session")]
public virtual string Session { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for a webhook call.</summary>
public class GoogleCloudDialogflowV2beta1WebhookResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Indicates that this intent ends an interaction. Some integrations (e.g., Actions on
/// Google or Dialogflow phone gateway) use this information to close interaction with an end user. Default is
/// false.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endInteraction")]
public virtual System.Nullable<bool> EndInteraction { get; set; }
/// <summary>Optional. Makes the platform immediately invoke another `DetectIntent` call internally with the
/// specified event as input.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("followupEventInput")]
public virtual GoogleCloudDialogflowV2beta1EventInput FollowupEventInput { get; set; }
/// <summary>Optional. The collection of rich messages to present to the user. This value is passed directly to
/// `QueryResult.fulfillment_messages`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentMessages")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1IntentMessage> FulfillmentMessages { get; set; }
/// <summary>Optional. The text to be shown on the screen. This value is passed directly to
/// `QueryResult.fulfillment_text`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fulfillmentText")]
public virtual string FulfillmentText { get; set; }
/// <summary>Optional. The collection of output contexts. This value is passed directly to
/// `QueryResult.output_contexts`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputContexts")]
public virtual System.Collections.Generic.IList<GoogleCloudDialogflowV2beta1Context> OutputContexts { get; set; }
/// <summary>Optional. This value is passed directly to `QueryResult.webhook_payload`. See the related
/// `fulfillment_messages[i].payload field`, which may be used as an alternative to this field.
///
/// This field can be used for Actions on Google responses. It should have a structure similar to the JSON
/// message shown here. For more information, see [Actions on Google Webhook
/// Format](https://developers.google.com/actions/dialogflow/webhook) { "google": { "expectUserResponse": true,
/// "richResponse": { "items": [ { "simpleResponse": { "textToSpeech": "this is a simple response" } } ] } }
/// }</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Collections.Generic.IDictionary<string,object> Payload { get; set; }
/// <summary>Optional. This value is passed directly to `QueryResult.webhook_source`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("source")]
public virtual string Source { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class GoogleLongrunningOperation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the value is `false`, it means the operation is still in progress. If `true`, the operation is
/// completed, and either `error` or `response` is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual GoogleRpcStatus Error { get; set; }
/// <summary>Service-specific metadata associated with the operation. It typically contains progress
/// information and common metadata such as create time. Some services might not provide such metadata. Any
/// method that returns a long-running operation should document the metadata type, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>The server-assigned name, which is only unique within the same service that originally returns it.
/// If you use the default HTTP mapping, the `name` should have the format of
/// `operations/some/unique/name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The normal response of the operation in case of success. If the original method returns no data on
/// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name
/// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class GoogleProtobufEmpty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `Status` type defines a logical error model that is suitable for different programming
/// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model
/// is designed to be:
///
/// - Simple to use and understand for most users - Flexible enough to meet unexpected needs
///
/// # Overview
///
/// The `Status` message contains three pieces of data: error code, error message, and error details. The error code
/// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error
/// message should be a developer-facing English message that helps developers *understand* and *resolve* the error.
/// If a localized user-facing error message is needed, put the localized message in the error details or localize
/// it in the client. The optional error details may contain arbitrary information about the error. There is a
/// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions.
///
/// # Language mapping
///
/// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire
/// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can
/// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped
/// to some error codes in C.
///
/// # Other uses
///
/// The error model and the `Status` message can be used in a variety of environments, either with or without APIs,
/// to provide a consistent developer experience across different environments.
///
/// Example uses of this error model include:
///
/// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the
/// normal response to indicate the partial errors.
///
/// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error
/// reporting.
///
/// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used
/// directly inside batch response, one for each error sub-response.
///
/// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of
/// those operations should be represented directly using the `Status` message.
///
/// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any
/// stripping needed for security/privacy reasons.</summary>
public class GoogleRpcStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>A list of messages that carry the error details. There is a common set of message types for APIs
/// to use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An object representing a latitude/longitude pair. This is expressed as a pair of doubles representing
/// degrees latitude and degrees longitude. Unless specified otherwise, this must conform to the WGS84 standard.
/// Values must be within normalized ranges.</summary>
public class GoogleTypeLatLng : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The latitude in degrees. It must be in the range [-90.0, +90.0].</summary>
[Newtonsoft.Json.JsonPropertyAttribute("latitude")]
public virtual System.Nullable<double> Latitude { get; set; }
/// <summary>The longitude in degrees. It must be in the range [-180.0, +180.0].</summary>
[Newtonsoft.Json.JsonPropertyAttribute("longitude")]
public virtual System.Nullable<double> Longitude { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 52.44419 | 206 | 0.543023 | [
"Apache-2.0"
] | gkmo/google-api-dotnet-client | Src/Generated/Google.Apis.Dialogflow.v2beta1/Google.Apis.Dialogflow.v2beta1.cs | 481,139 | C# |
// Copyright © 2020 Dmitry Sikorsky. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Magicalizer.Data.Entities.Abstractions;
namespace Platformus.ECommerce.Data.Entities
{
/// <summary>
/// Represents a cart.
/// </summary>
public class Cart : IEntity
{
/// <summary>
/// Gets or sets the unique identifier of the cart.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets the unique client-side identifier of the cart.
/// </summary>
public Guid ClientSideId { get; set; }
/// <summary>
/// Gets or sets the date and time this cart is created at.
/// </summary>
public DateTime Created { get; set; }
public virtual ICollection<Position> Positions { get; set; }
}
} | 27.96875 | 111 | 0.66257 | [
"Apache-2.0"
] | Platformus/Platformus | src/Platformus.ECommerce.Data.Entities/Cart.cs | 898 | C# |
using System;
using P01_HospitalDatabase.Data;
using P01_HospitalDatabase.Data.Models;
using P01_HospitalDatabase.Initializer;
namespace P01_HospitalDatabase
{
public class StartUp
{
public static void Main()
{
DatabaseInitializer.ResetDatabase();
using (var db = new HospitalContext())
{
//db.Database.EnsureCreated();
DatabaseInitializer.InitialSeed(db);
}
}
}
}
| 20.916667 | 52 | 0.583665 | [
"MIT"
] | Hris91/C-Development-New | DB Advanced/Code First/HospitalStartUp/StartUp.cs | 504 | C# |
namespace Weapsy.Blog.Domain.Blog.Exceptions
{
public class BlogNotDeletedException : BlogException
{
public BlogNotDeletedException(string message) : base(message)
{
}
}
}
| 18.3 | 64 | 0.759563 | [
"MIT"
] | 1713660/weapsy | src/Weapsy.Blog.Domain/Blog/Exceptions/BlogNotDeletedException.cs | 185 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
using NetOffice;
namespace NetOffice.WordApi
{
///<summary>
/// DispatchInterface SmartTagActions
/// SupportByVersion Word, 11,12,14,15
///</summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class SmartTagActions : COMObject ,IEnumerable<NetOffice.WordApi.SmartTagAction>
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(SmartTagActions);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public SmartTagActions(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SmartTagActions(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SmartTagActions(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SmartTagActions(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SmartTagActions(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SmartTagActions() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SmartTagActions(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Word 11, 12, 14, 15
/// Get
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
public Int32 Count
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Count", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Word 11, 12, 14, 15
/// Get
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
public NetOffice.WordApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.WordApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.WordApi.Application.LateBindingApiWrapperType) as NetOffice.WordApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Word 11, 12, 14, 15
/// Get
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
public Int32 Creator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Word 11, 12, 14, 15
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Word 11, 12, 14, 15
///
/// </summary>
/// <param name="index">object Index</param>
[SupportByVersionAttribute("Word", 11,12,14,15)]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")]
public NetOffice.WordApi.SmartTagAction this[object index]
{
get
{
object[] paramsArray = Invoker.ValidateParamsArray(index);
object returnItem = Invoker.MethodReturn(this, "Item", paramsArray);
NetOffice.WordApi.SmartTagAction newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.WordApi.SmartTagAction.LateBindingApiWrapperType) as NetOffice.WordApi.SmartTagAction;
return newObject;
}
}
/// <summary>
/// SupportByVersion Word 11, 12, 14, 15
///
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
public void ReloadActions()
{
object[] paramsArray = null;
Invoker.Method(this, "ReloadActions", paramsArray);
}
#endregion
#region IEnumerable<NetOffice.WordApi.SmartTagAction> Member
/// <summary>
/// SupportByVersionAttribute Word, 11,12,14,15
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
public IEnumerator<NetOffice.WordApi.SmartTagAction> GetEnumerator()
{
NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable);
foreach (NetOffice.WordApi.SmartTagAction item in innerEnumerator)
yield return item;
}
#endregion
#region IEnumerable Members
/// <summary>
/// SupportByVersionAttribute Word, 11,12,14,15
/// </summary>
[SupportByVersionAttribute("Word", 11,12,14,15)]
IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator()
{
return NetOffice.Utils.GetProxyEnumeratorAsProperty(this);
}
#endregion
#pragma warning restore
}
} | 32.018018 | 201 | 0.673326 | [
"MIT"
] | NetOffice/NetOffice | Source/Word/DispatchInterfaces/SmartTagActions.cs | 7,108 | C# |
using GitHub.Runner.Common;
using GitHub.Runner.Common.Util;
using GitHub.Runner.Sdk;
using System;
namespace GitHub.Runner.Listener.Configuration
{
[ServiceLocator(Default = typeof(PromptManager))]
public interface IPromptManager : IRunnerService
{
bool ReadBool(
string argName,
string description,
bool defaultValue,
bool unattended);
string ReadValue(
string argName,
string description,
bool secret,
string defaultValue,
Func<String, bool> validator,
bool unattended,
bool isOptional = false);
}
public sealed class PromptManager : RunnerService, IPromptManager
{
private ITerminal _terminal;
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_terminal = HostContext.GetService<ITerminal>();
}
public bool ReadBool(
string argName,
string description,
bool defaultValue,
bool unattended)
{
string answer = ReadValue(
argName: argName,
description: description,
secret: false,
defaultValue: defaultValue ? "Y" : "N",
validator: Validators.BoolValidator,
unattended: unattended);
return String.Equals(answer, "true", StringComparison.OrdinalIgnoreCase) ||
String.Equals(answer, "Y", StringComparison.CurrentCultureIgnoreCase);
}
public string ReadValue(
string argName,
string description,
bool secret,
string defaultValue,
Func<string, bool> validator,
bool unattended,
bool isOptional = false)
{
Trace.Info(nameof(ReadValue));
ArgUtil.NotNull(validator, nameof(validator));
string value = string.Empty;
// Check if unattended.
if (unattended)
{
// Return the default value if specified.
if (!string.IsNullOrEmpty(defaultValue))
{
return defaultValue;
}
else if (isOptional)
{
return string.Empty;
}
// Otherwise throw.
throw new Exception($"Invalid configuration provided for {argName}. Terminating unattended configuration.");
}
// Prompt until a valid value is read.
while (true)
{
// Write the message prompt.
_terminal.Write($"{description} ");
if(!string.IsNullOrEmpty(defaultValue))
{
_terminal.Write($"[press Enter for {defaultValue}] ");
}
else if (isOptional){
_terminal.Write($"[press Enter to skip] ");
}
// Read and trim the value.
value = secret ? _terminal.ReadSecret() : _terminal.ReadLine();
value = value?.Trim() ?? string.Empty;
// Return the default if not specified.
if (string.IsNullOrEmpty(value))
{
if (!string.IsNullOrEmpty(defaultValue))
{
Trace.Info($"Falling back to the default: '{defaultValue}'");
return defaultValue;
}
else if (isOptional)
{
return string.Empty;
}
}
// Return the value if it is not empty and it is valid.
// Otherwise try the loop again.
if (!string.IsNullOrEmpty(value))
{
if (validator(value))
{
return value;
}
else
{
Trace.Info("Invalid value.");
_terminal.WriteLine("Entered value is invalid", ConsoleColor.Yellow);
}
}
}
}
}
}
| 32.455224 | 124 | 0.48057 | [
"MIT"
] | 9996142202/runner | src/Runner.Listener/Configuration/PromptManager.cs | 4,349 | C# |
using Pathoschild.Stardew.LookupAnything.Framework.Lookups;
namespace Pathoschild.Stardew.LookupAnything.Framework
{
/// <summary>A central registry for subject lookups.</summary>
internal interface ISubjectRegistry
{
/*********
** Methods
*********/
/// <summary>Get the subject for an in-game entity, if available.</summary>
/// <param name="entity">The entity instance.</param>
ISubject GetByEntity(object entity);
}
}
| 30.4375 | 83 | 0.64271 | [
"MIT"
] | AlexDevolio/StardewMods | LookupAnything/Framework/ISubjectRegistry.cs | 487 | C# |
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class Untitled_DeckRPG : ModuleRules
{
public Untitled_DeckRPG(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Paper2D" });
}
}
| 26 | 113 | 0.760989 | [
"Artistic-2.0"
] | JeffereyAEL/UntitledDeckRPG | Source/Untitled_DeckRPG/Untitled_DeckRPG.Build.cs | 364 | C# |
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SharpTox.Encryption;
namespace SharpTox.Core
{
/// <summary>
/// Represents an instance of Tox.
/// </summary>
public class Tox : IDisposable
{
private ToxHandle _tox;
private CancellationTokenSource _cancelTokenSource;
private bool _running = false;
private bool _disposed = false;
#region Callback delegates
private ToxDelegates.CallbackFriendRequestDelegate _onFriendRequestCallback;
private ToxDelegates.CallbackFriendMessageDelegate _onFriendMessageCallback;
private ToxDelegates.CallbackNameChangeDelegate _onNameChangeCallback;
private ToxDelegates.CallbackStatusMessageDelegate _onStatusMessageCallback;
private ToxDelegates.CallbackUserStatusDelegate _onUserStatusCallback;
private ToxDelegates.CallbackTypingChangeDelegate _onTypingChangeCallback;
private ToxDelegates.CallbackConnectionStatusDelegate _onConnectionStatusCallback;
private ToxDelegates.CallbackFriendConnectionStatusDelegate _onFriendConnectionStatusCallback;
private ToxDelegates.CallbackReadReceiptDelegate _onReadReceiptCallback;
private ToxDelegates.CallbackFileControlDelegate _onFileControlCallback;
private ToxDelegates.CallbackFileReceiveChunkDelegate _onFileReceiveChunkCallback;
private ToxDelegates.CallbackFileReceiveDelegate _onFileReceiveCallback;
private ToxDelegates.CallbackFileRequestChunkDelegate _onFileRequestChunkCallback;
private ToxDelegates.CallbackFriendPacketDelegate _onFriendLossyPacketCallback;
private ToxDelegates.CallbackFriendPacketDelegate _onFriendLosslessPacketCallback;
private ToxDelegates.CallbackGroupInviteDelegate _onGroupInviteCallback;
private ToxDelegates.CallbackGroupActionDelegate _onGroupActionCallback;
private ToxDelegates.CallbackGroupMessageDelegate _onGroupMessageCallback;
private ToxDelegates.CallbackGroupNamelistChangeDelegate _onGroupNamelistChangeCallback;
private ToxDelegates.CallbackGroupTitleDelegate _onGroupTitleCallback;
#endregion
/// <summary>
/// Options that are used for this instance of Tox.
/// </summary>
public ToxOptions Options { get; private set; }
/// <summary>
/// Whether or not we're connected to the DHT.
/// </summary>
public bool IsConnected
{
get
{
ThrowIfDisposed();
return ToxFunctions.SelfGetConnectionStatus(_tox) != ToxConnectionStatus.None;
}
}
/// <summary>
/// An array of friendnumbers of this Tox instance.
/// </summary>
public int[] Friends
{
get
{
uint size = ToxFunctions.SelfGetFriendListSize(_tox);
uint[] friends = new uint[size];
ToxFunctions.SelfGetFriendList(_tox, friends);
return (int[])(object)friends;
}
}
/// <summary>
/// The nickname of this Tox instance.
/// </summary>
public string Name
{
get
{
ThrowIfDisposed();
byte[] bytes = new byte[ToxFunctions.SelfGetNameSize(_tox)];
ToxFunctions.SelfGetName(_tox, bytes);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
set
{
ThrowIfDisposed();
byte[] bytes = Encoding.UTF8.GetBytes(value);
var error = ToxErrorSetInfo.Ok;
ToxFunctions.SelfSetName(_tox, bytes, (ushort)bytes.Length, ref error);
}
}
/// <summary>
/// The status message of this Tox instance.
/// </summary>
public string StatusMessage
{
get
{
ThrowIfDisposed();
uint size = ToxFunctions.SelfGetStatusMessageSize(_tox);
byte[] status = new byte[size];
ToxFunctions.SelfGetStatusMessage(_tox, status);
return Encoding.UTF8.GetString(status, 0, status.Length);
}
set
{
ThrowIfDisposed();
byte[] msg = Encoding.UTF8.GetBytes(value);
var error = ToxErrorSetInfo.Ok;
ToxFunctions.SelfSetStatusMessage(_tox, msg, (uint)msg.Length, ref error);
}
}
/// <summary>
/// The Tox ID of this Tox instance.
/// </summary>
public ToxId Id
{
get
{
ThrowIfDisposed();
byte[] address = new byte[ToxConstants.AddressSize];
ToxFunctions.SelfGetAddress(_tox, address);
return new ToxId(address);
}
}
/// <summary>
/// Retrieves the temporary DHT public key of this Tox instance.
/// </summary>
public ToxKey DhtId
{
get
{
ThrowIfDisposed();
byte[] publicKey = new byte[ToxConstants.PublicKeySize];
ToxFunctions.SelfGetDhtId(_tox, publicKey);
return new ToxKey(ToxKeyType.Public, publicKey);
}
}
/// <summary>
/// Current user status of this Tox instance.
/// </summary>
public ToxUserStatus Status
{
get
{
ThrowIfDisposed();
return ToxFunctions.SelfGetStatus(_tox);
}
set
{
ThrowIfDisposed();
ToxFunctions.SelfSetStatus(_tox, value);
}
}
/// <summary>
/// The handle of this instance of Tox.
/// Do not dispose this handle manually, use the Dispose method in this class instead.
/// </summary>
internal ToxHandle Handle
{
get
{
return _tox;
}
}
/// <summary>
/// Initializes a new instance of Tox. If no secret key is specified, toxcore will generate a new keypair.
/// </summary>
/// <param name="options">The options to initialize this instance of Tox with.</param>
/// <param name="secretKey">Optionally, specify the secret key to initialize this instance of Tox with. Must be ToxConstants.SecretKeySize bytes in size.</param>
public Tox(ToxOptions options, ToxKey secretKey = null)
{
var error = ToxErrorNew.Ok;
var optionsStruct = options.Struct;
if (secretKey != null)
optionsStruct.SetData(secretKey.GetBytes(), ToxSaveDataType.SecretKey);
_tox = ToxFunctions.New(ref optionsStruct, ref error);
if (_tox == null || _tox.IsInvalid || error != ToxErrorNew.Ok)
throw new Exception("Could not create a new instance of tox, error: " + error.ToString());
optionsStruct.Free();
Options = options;
}
/// <summary>
/// Initializes a new instance of Tox.
/// </summary>
/// <param name="options">The options to initialize this instance of Tox with.</param>
/// <param name="data">A byte array containing Tox save data.</param>
public Tox(ToxOptions options, ToxData data)
{
if (data == null)
throw new ArgumentNullException("data");
var optionsStruct = options.Struct;
var error = ToxErrorNew.Ok;
optionsStruct.SetData(data.Bytes, ToxSaveDataType.ToxSave);
_tox = ToxFunctions.New(ref optionsStruct, ref error);
if (_tox == null || _tox.IsInvalid || error != ToxErrorNew.Ok)
throw new Exception("Could not create a new instance of tox, error: " + error.ToString());
optionsStruct.Free();
Options = options;
}
/// <summary>
/// Initializes a new instance of Tox.
/// </summary>
/// <param name="options">The options to initialize this instance of Tox with.</param>
/// <param name="data">A byte array containing Tox save data.</param>
/// <param name="key">The key to decrypt the given encrypted Tox profile data.</param>
public Tox(ToxOptions options, ToxData data, ToxEncryptionKey key)
{
if (data == null)
throw new ArgumentNullException("data");
if (key == null)
throw new ArgumentNullException("key");
if (!data.IsEncrypted)
throw new Exception("This data is not encrypted");
var optionsStruct = options.Struct;
var error = ToxErrorNew.Ok;
var decryptError = ToxErrorDecryption.Ok;
byte[] decryptedData = ToxEncryption.DecryptData(data.Bytes, key, out decryptError);
optionsStruct.SetData(decryptedData, ToxSaveDataType.ToxSave);
_tox = ToxFunctions.New(ref optionsStruct, ref error);
if (_tox == null || _tox.IsInvalid || error != ToxErrorNew.Ok || decryptError != ToxErrorDecryption.Ok)
throw new Exception(string.Format("Could not create a new instance of tox, error: {0}, decrypt error: {1}" + error.ToString(), decryptError.ToString()));
optionsStruct.Free();
Options = options;
}
/// <summary>
/// Initializes a new instance of Tox.
/// </summary>
/// <param name="options">The options to initialize this instance of Tox with.</param>
/// <param name="data">A byte array containing Tox save data.</param>
/// <param name="password">The password to decrypt the given encrypted Tox profile data.</param>
public Tox(ToxOptions options, ToxData data, string password)
{
if (data == null)
throw new ArgumentNullException("data");
if (password == null)
throw new ArgumentNullException("password");
if (!data.IsEncrypted)
throw new Exception("This data is not encrypted");
var optionsStruct = options.Struct;
var error = ToxErrorNew.Ok;
var decryptError = ToxErrorDecryption.Ok;
byte[] decryptedData = ToxEncryption.DecryptData(data.Bytes, password, out decryptError);
optionsStruct.SetData(decryptedData, ToxSaveDataType.ToxSave);
_tox = ToxFunctions.New(ref optionsStruct, ref error);
if (_tox == null || _tox.IsInvalid || error != ToxErrorNew.Ok || decryptError != ToxErrorDecryption.Ok)
throw new Exception(string.Format("Could not create a new instance of tox, error: {0}, decrypt error: {1}" + error.ToString(), decryptError.ToString()));
optionsStruct.Free();
Options = options;
}
/// <summary>
/// Releases all resources used by this instance of Tox.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
//dispose pattern as described on msdn for a class that uses a safe handle
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_cancelTokenSource != null)
{
_cancelTokenSource.Cancel();
_cancelTokenSource.Dispose();
}
}
if (_tox != null && !_tox.IsInvalid && !_tox.IsClosed)
_tox.Dispose();
_disposed = true;
}
/// <summary>
/// Starts the main 'tox_iterate' loop at an interval retrieved with 'tox_iteration_interval'.
/// If you want to manage your own loop, use the Iterate method instead.
/// </summary>
public void Start()
{
ThrowIfDisposed();
if (_running)
return;
Loop();
}
/// <summary>
/// Stops the main tox_do loop if it's running.
/// </summary>
public void Stop()
{
ThrowIfDisposed();
if (!_running)
return;
if (_cancelTokenSource != null)
{
_cancelTokenSource.Cancel();
_cancelTokenSource.Dispose();
_running = false;
}
}
/// <summary>
/// Runs the tox_iterate once in the current thread.
/// </summary>
/// <returns>The next timeout.</returns>
public int Iterate()
{
ThrowIfDisposed();
if (_running)
throw new Exception("Loop already running");
return DoIterate();
}
private int DoIterate()
{
ToxFunctions.Iterate(_tox);
return (int)ToxFunctions.IterationInterval(_tox);
}
private void Loop()
{
_cancelTokenSource = new CancellationTokenSource();
_running = true;
Task.Factory.StartNew(async () =>
{
while (_running)
{
if (_cancelTokenSource.IsCancellationRequested)
break;
int delay = DoIterate();
await Task.Delay(delay);
}
}, _cancelTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
/// <summary>
/// Adds a friend to the friend list and sends a friend request.
/// </summary>
/// <param name="id">The Tox id of the friend to add.</param>
/// <param name="message">The message that will be sent along with the friend request.</param>
/// <param name="error"></param>
/// <returns>The friend number.</returns>
public int AddFriend(ToxId id, string message, out ToxErrorFriendAdd error)
{
ThrowIfDisposed();
if (id == null)
throw new ArgumentNullException("id");
byte[] msg = Encoding.UTF8.GetBytes(message);
error = ToxErrorFriendAdd.Ok;
return ToxTools.Map(ToxFunctions.FriendAdd(_tox, id.Bytes, msg, (uint)msg.Length, ref error));
}
/// <summary>
/// Adds a friend to the friend list and sends a friend request.
/// </summary>
/// <param name="id">The Tox id of the friend to add.</param>
/// <param name="message">The message that will be sent along with the friend request.</param>
/// <returns>The friend number.</returns>
public int AddFriend(ToxId id, string message)
{
var error = ToxErrorFriendAdd.Ok;
return AddFriend(id, message, out error);
}
/// <summary>
/// Adds a friend to the friend list without sending a friend request.
/// This method should be used to accept friend requests.
/// </summary>
/// <param name="publicKey">The public key of the friend to add.</param>
/// <param name="error"></param>
/// <returns>The friend number.</returns>
public int AddFriendNoRequest(ToxKey publicKey, out ToxErrorFriendAdd error)
{
ThrowIfDisposed();
if (publicKey == null)
throw new ArgumentNullException("publicKey");
error = ToxErrorFriendAdd.Ok;
return ToxTools.Map(ToxFunctions.FriendAddNoRequest(_tox, publicKey.GetBytes(), ref error));
}
/// <summary>
/// Adds a friend to the friend list without sending a friend request.
/// This method should be used to accept friend requests.
/// </summary>
/// <param name="publicKey">The public key of the friend to add.</param>
/// <returns>The friend number.</returns>
public int AddFriendNoRequest(ToxKey publicKey)
{
var error = ToxErrorFriendAdd.Ok;
return AddFriendNoRequest(publicKey, out error);
}
/// <summary>
/// Adds a node as a TCP relay.
/// This method can be used to initiate TCP connections to different ports on the same bootstrap node, or to add TCP relays without using them as bootstrap nodes.
/// </summary>
/// <param name="node">The node to add.</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool AddTcpRelay(ToxNode node, out ToxErrorBootstrap error)
{
ThrowIfDisposed();
if (node == null)
throw new ArgumentNullException("node");
error = ToxErrorBootstrap.Ok;
return ToxFunctions.AddTcpRelay(_tox, node.Address, (ushort)node.Port, node.PublicKey.GetBytes(), ref error);
}
/// <summary>
/// Adds a node as a TCP relay.
/// This method can be used to initiate TCP connections to different ports on the same bootstrap node, or to add TCP relays without using them as bootstrap nodes.
/// </summary>
/// <param name="node">The node to add.</param>
/// <returns>True on success.</returns>
public bool AddTcpRelay(ToxNode node)
{
var error = ToxErrorBootstrap.Ok;
return AddTcpRelay(node, out error);
}
/// <summary>
/// Attempts to bootstrap this Tox instance with a ToxNode. A 'getnodes' request is sent to the given node.
/// </summary>
/// <param name="node">The node to bootstrap off of.</param>
/// <param name="error"></param>
/// <returns>True if the 'getnodes' request was sent successfully.</returns>
public bool Bootstrap(ToxNode node, out ToxErrorBootstrap error)
{
ThrowIfDisposed();
if (node == null)
throw new ArgumentNullException("node");
error = ToxErrorBootstrap.Ok;
return ToxFunctions.Bootstrap(_tox, node.Address, (ushort)node.Port, node.PublicKey.GetBytes(), ref error);
}
/// <summary>
/// Attempts to bootstrap this Tox instance with a ToxNode. A 'getnodes' request is sent to the given node.
/// </summary>
/// <param name="node">The node to bootstrap off of.</param>
/// <returns>True if the 'getnodes' request was sent successfully.</returns>
public bool Bootstrap(ToxNode node)
{
var error = ToxErrorBootstrap.Ok;
return Bootstrap(node, out error);
}
/// <summary>
/// Checks if there exists a friend with given friendNumber.
/// </summary>
/// <param name="friendNumber">The friend number to check.</param>
/// <returns>True if the friend exists.</returns>
public bool FriendExists(int friendNumber)
{
ThrowIfDisposed();
return ToxFunctions.FriendExists(_tox, ToxTools.Map(friendNumber));
}
/// <summary>
/// Retrieves the typing status of a friend.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the typing status of.</param>
/// <param name="error"></param>
/// <returns>True if the friend is typing.</returns>
public bool GetFriendTypingStatus(int friendNumber, out ToxErrorFriendQuery error)
{
ThrowIfDisposed();
error = ToxErrorFriendQuery.Ok;
return ToxFunctions.FriendGetTyping(_tox, ToxTools.Map(friendNumber), ref error);
}
/// <summary>
/// Retrieves the typing status of a friend.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the typing status of.</param>
/// <returns>True if the friend is typing.</returns>
public bool GetFriendTypingStatus(int friendNumber)
{
var error = ToxErrorFriendQuery.Ok;
return GetFriendTypingStatus(friendNumber, out error);
}
/// <summary>
/// Retrieves the friendNumber associated with the specified public key.
/// </summary>
/// <param name="publicKey">The public key to look for.</param>
/// <param name="error"></param>
/// <returns>The friend number on success.</returns>
public int GetFriendByPublicKey(ToxKey publicKey, out ToxErrorFriendByPublicKey error)
{
ThrowIfDisposed();
if (publicKey == null)
throw new ArgumentNullException("publicKey");
error = ToxErrorFriendByPublicKey.Ok;
return ToxTools.Map(ToxFunctions.FriendByPublicKey(_tox, publicKey.GetBytes(), ref error));
}
/// <summary>
/// Retrieves the friendNumber associated with the specified public key.
/// </summary>
/// <param name="publicKey">The public key to look for.</param>
/// <returns>The friend number on success.</returns>
public int GetFriendByPublicKey(ToxKey publicKey)
{
var error = ToxErrorFriendByPublicKey.Ok;
return GetFriendByPublicKey(publicKey, out error);
}
/// <summary>
/// Retrieves a friend's connection status.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the connection status of.</param>
/// <param name="error"></param>
/// <returns>The connection status on success.</returns>
public ToxConnectionStatus GetFriendConnectionStatus(int friendNumber, out ToxErrorFriendQuery error)
{
ThrowIfDisposed();
error = ToxErrorFriendQuery.Ok;
return ToxFunctions.FriendGetConnectionStatus(_tox, ToxTools.Map(friendNumber), ref error);
}
/// <summary>
/// Retrieves a friend's connection status.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the connection status of.</param>
/// <returns>The connection status on success.</returns>
public ToxConnectionStatus GetFriendConnectionStatus(int friendNumber)
{
var error = ToxErrorFriendQuery.Ok;
return GetFriendConnectionStatus(friendNumber, out error);
}
/// <summary>
/// Check whether or not a friend is online.
/// </summary>
/// <param name="friendNumber">The friend number.</param>
/// <returns>True if the friend is online.</returns>
public bool IsFriendOnline(int friendNumber)
{
return GetFriendConnectionStatus(friendNumber) != ToxConnectionStatus.None;
}
/// <summary>
/// Retrieves a friend's public key.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the public key of.</param>
/// <param name="error"></param>
/// <returns>The friend's public key on success.</returns>
public ToxKey GetFriendPublicKey(int friendNumber, out ToxErrorFriendGetPublicKey error)
{
ThrowIfDisposed();
byte[] address = new byte[ToxConstants.PublicKeySize];
error = ToxErrorFriendGetPublicKey.Ok;
if (!ToxFunctions.FriendGetPublicKey(_tox, ToxTools.Map(friendNumber), address, ref error))
return null;
return new ToxKey(ToxKeyType.Public, address);
}
/// <summary>
/// Retrieves a friend's public key.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the public key of.</param>
/// <returns>The friend's public key on success.</returns>
public ToxKey GetFriendPublicKey(int friendNumber)
{
var error = ToxErrorFriendGetPublicKey.Ok;
return GetFriendPublicKey(friendNumber, out error);
}
/// <summary>
/// Retrieves a friend's current status.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the status of.</param>
/// <param name="error"></param>
/// <returns>The friend's status on success.</returns>
public ToxUserStatus GetFriendStatus(int friendNumber, out ToxErrorFriendQuery error)
{
ThrowIfDisposed();
error = ToxErrorFriendQuery.Ok;
return ToxFunctions.FriendGetStatus(_tox, ToxTools.Map(friendNumber), ref error);
}
/// <summary>
/// Retrieves a friend's current status.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the status of.</param>
/// <returns>The friend's status on success.</returns>
public ToxUserStatus GetFriendStatus(int friendNumber)
{
var error = ToxErrorFriendQuery.Ok;
return GetFriendStatus(friendNumber, out error);
}
/// <summary>
/// Sets the typing status of this Tox instance for a friend.
/// </summary>
/// <param name="friendNumber">The friend number to set the typing status for.</param>
/// <param name="isTyping">Whether or not we're typing.</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool SetTypingStatus(int friendNumber, bool isTyping, out ToxErrorSetTyping error)
{
ThrowIfDisposed();
error = ToxErrorSetTyping.Ok;
return ToxFunctions.SelfSetTyping(_tox, ToxTools.Map(friendNumber), isTyping, ref error);
}
/// <summary>
/// Sets the typing status of this Tox instance for a friend.
/// </summary>
/// <param name="friendNumber">The friend number to set the typing status for.</param>
/// <param name="isTyping">Whether or not we're typing.</param>
/// <returns>True on success.</returns>
public bool SetTypingStatus(int friendNumber, bool isTyping)
{
var error = ToxErrorSetTyping.Ok;
return SetTypingStatus(friendNumber, isTyping, out error);
}
/// <summary>
/// Sends a message to a friend.
/// </summary>
/// <param name="friendNumber">The friend number to send the message to.</param>
/// <param name="message">The message to be sent. Maximum length: <see cref="ToxConstants.MaxMessageLength"/></param>
/// <param name="type">The type of this message.</param>
/// <param name="error"></param>
/// <returns>Message ID on success.</returns>
public int SendMessage(int friendNumber, string message, ToxMessageType type, out ToxErrorSendMessage error)
{
ThrowIfDisposed();
byte[] bytes = Encoding.UTF8.GetBytes(message);
error = ToxErrorSendMessage.Ok;
return ToxTools.Map(ToxFunctions.FriendSendMessage(_tox, ToxTools.Map(friendNumber), type, bytes, (uint)bytes.Length, ref error));
}
/// <summary>
/// Sends a message to a friend.
/// </summary>
/// <param name="friendNumber">The friend number to send the message to.</param>
/// <param name="message">The message to be sent. Maximum length: <see cref="ToxConstants.MaxMessageLength"/></param>
/// <param name="type">The type of this message.</param>
/// <returns>Message ID on success.</returns>
public int SendMessage(int friendNumber, string message, ToxMessageType type)
{
var error = ToxErrorSendMessage.Ok;
return SendMessage(friendNumber, message, type, out error);
}
/// <summary>
/// Deletes a friend from the friend list.
/// </summary>
/// <param name="friendNumber">The friend number to be deleted.</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool DeleteFriend(int friendNumber, out ToxErrorFriendDelete error)
{
ThrowIfDisposed();
error = ToxErrorFriendDelete.Ok;
return ToxFunctions.FriendDelete(_tox, ToxTools.Map(friendNumber), ref error);
}
/// <summary>
/// Deletes a friend from the friend list.
/// </summary>
/// <param name="friendNumber">The friend number to be deleted.</param>
/// <returns>True on success.</returns>
public bool DeleteFriend(int friendNumber)
{
var error = ToxErrorFriendDelete.Ok;
return DeleteFriend(friendNumber, out error);
}
/// <summary>
/// Retrieves a ToxData object that contains the profile data of this Tox instance.
/// </summary>
/// <returns></returns>
public ToxData GetData()
{
ThrowIfDisposed();
byte[] bytes = new byte[ToxFunctions.GetSaveDataSize(_tox)];
ToxFunctions.GetSaveData(_tox, bytes);
return ToxData.FromBytes(bytes);
}
/// <summary>
/// Retrieves a ToxData object that contains the profile data of this Tox instance, encrypted with the provided key.
/// </summary>
/// <param name="key">The key to encrypt the Tox data with.</param>
/// <returns></returns>
public ToxData GetData(ToxEncryptionKey key)
{
ThrowIfDisposed();
var data = GetData();
byte[] encrypted = ToxEncryption.EncryptData(data.Bytes, key);
return ToxData.FromBytes(encrypted);
}
public ToxData GetData(string password)
{
ThrowIfDisposed();
var data = GetData();
byte[] encrypted = ToxEncryption.EncryptData(data.Bytes, password);
return ToxData.FromBytes(encrypted);
}
/// <summary>
/// Retrieves the private key of this Tox instance.
/// </summary>
/// <returns>The private key of this Tox instance.</returns>
public ToxKey GetPrivateKey()
{
ThrowIfDisposed();
byte[] key = new byte[ToxConstants.PublicKeySize];
ToxFunctions.SelfGetSecretKey(_tox, key);
return new ToxKey(ToxKeyType.Secret, key);
}
/// <summary>
/// Retrieves the name of a friend.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the name of.</param>
/// <param name="error"></param>
/// <returns>The friend's name on success.</returns>
public string GetFriendName(int friendNumber, out ToxErrorFriendQuery error)
{
ThrowIfDisposed();
error = ToxErrorFriendQuery.Ok;
uint size = ToxFunctions.FriendGetNameSize(_tox, ToxTools.Map(friendNumber), ref error);
if (error != ToxErrorFriendQuery.Ok)
return string.Empty;
byte[] name = new byte[size];
if (!ToxFunctions.FriendGetName(_tox, ToxTools.Map(friendNumber), name, ref error))
return string.Empty;
return Encoding.UTF8.GetString(name, 0, name.Length);
}
/// <summary>
/// Retrieves the name of a friend.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the name of.</param>
/// <returns>The friend's name on success.</returns>
public string GetFriendName(int friendNumber)
{
var error = ToxErrorFriendQuery.Ok;
return GetFriendName(friendNumber, out error);
}
/// <summary>
/// Retrieves the status message of a friend.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the status message of.</param>
/// <param name="error"></param>
/// <returns>The friend's status message on success.</returns>
public string GetFriendStatusMessage(int friendNumber, out ToxErrorFriendQuery error)
{
ThrowIfDisposed();
error = ToxErrorFriendQuery.Ok;
uint size = ToxFunctions.FriendGetStatusMessageSize(_tox, ToxTools.Map(friendNumber), ref error);
if (error != ToxErrorFriendQuery.Ok)
return string.Empty;
byte[] message = new byte[size];
if (!ToxFunctions.FriendGetStatusMessage(_tox, ToxTools.Map(friendNumber), message, ref error))
return string.Empty;
return Encoding.UTF8.GetString(message, 0, message.Length);
}
/// <summary>
/// Retrieves the status message of a friend.
/// </summary>
/// <param name="friendNumber">The friend number to retrieve the status message of.</param>
/// <returns>The friend's status message on success.</returns>
public string GetFriendStatusMessage(int friendNumber)
{
var error = ToxErrorFriendQuery.Ok;
return GetFriendStatusMessage(friendNumber, out error);
}
/// <summary>
/// Retrieves the UDP port this instance of Tox is bound to.
/// </summary>
/// <param name="error"></param>
/// <returns>The UDP port on success.</returns>
public int GetUdpPort(out ToxErrorGetPort error)
{
ThrowIfDisposed();
error = ToxErrorGetPort.Ok;
return ToxFunctions.SelfGetUdpPort(_tox, ref error);
}
/// <summary>
/// Retrieves the UDP port this instance of Tox is bound to.
/// </summary>
/// <returns>The UDP port on success.</returns>
public int GetUdpPort()
{
var error = ToxErrorGetPort.Ok;
return GetUdpPort(out error);
}
/// <summary>
/// Retrieves the TCP port this instance of Tox is bound to.
/// </summary>
/// <param name="error"></param>
/// <returns>The TCP port on success.</returns>
public int GetTcpPort(out ToxErrorGetPort error)
{
ThrowIfDisposed();
error = ToxErrorGetPort.Ok;
return ToxFunctions.SelfGetTcpPort(_tox, ref error);
}
/// <summary>
/// Retrieves the TCP port this instance of Tox is bound to.
/// </summary>
/// <returns>The TCP port on success.</returns>
public int GetTcpPort()
{
var error = ToxErrorGetPort.Ok;
return GetTcpPort(out error);
}
/// <summary>
/// Sets the nospam value for this Tox instance.
/// </summary>
/// <param name="nospam">The nospam value to set.</param>
public void SetNospam(int nospam)
{
ThrowIfDisposed();
ToxFunctions.SelfSetNospam(_tox, ToxTools.Map(nospam));
}
/// <summary>
/// Retrieves the nospam value of this Tox instance.
/// </summary>
/// <returns>The nospam value.</returns>
public int GetNospam()
{
ThrowIfDisposed();
return ToxTools.Map(ToxFunctions.SelfGetNospam(_tox));
}
/// <summary>
/// Sends a file control command to a friend for a given file transfer.
/// </summary>
/// <param name="friendNumber">The friend to send the file control to.</param>
/// <param name="fileNumber">The file transfer that this control is meant for.</param>
/// <param name="control">The control to send.</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool FileControl(int friendNumber, int fileNumber, ToxFileControl control, out ToxErrorFileControl error)
{
ThrowIfDisposed();
error = ToxErrorFileControl.Ok;
return ToxFunctions.FileControl(_tox, ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), control, ref error);
}
/// <summary>
/// Sends a file control command to a friend for a given file transfer.
/// </summary>
/// <param name="friendNumber">The friend to send the file control to.</param>
/// <param name="fileNumber">The file transfer that this control is meant for.</param>
/// <param name="control">The control to send.</param>
/// <returns>True on success.</returns>
public bool FileControl(int friendNumber, int fileNumber, ToxFileControl control)
{
var error = ToxErrorFileControl.Ok;
return FileControl(friendNumber, fileNumber, control, out error);
}
/// <summary>
/// Send a file transmission request.
/// </summary>
/// <param name="friendNumber">The friend number to send the request to.</param>
/// <param name="kind">The kind of file that will be transferred.</param>
/// <param name="fileSize">The size of the file that will be transferred.</param>
/// <param name="fileName">The filename of the file that will be transferred.</param>
/// <param name="error"></param>
/// <returns>Info about the file transfer on success.</returns>
public ToxFileInfo FileSend(int friendNumber, ToxFileKind kind, long fileSize, string fileName, out ToxErrorFileSend error)
{
ThrowIfDisposed();
error = ToxErrorFileSend.Ok;
byte[] fileNameBytes = Encoding.UTF8.GetBytes(fileName);
int fileNumber = ToxTools.Map(ToxFunctions.FileSend(_tox, ToxTools.Map(friendNumber), kind, (ulong)fileSize, null, fileNameBytes, (uint)fileNameBytes.Length, ref error));
if (error == ToxErrorFileSend.Ok)
return new ToxFileInfo(fileNumber, FileGetId(friendNumber, fileNumber));
return null;
}
/// <summary>
/// Send a file transmission request.
/// </summary>
/// <param name="friendNumber">The friend number to send the request to.</param>
/// <param name="kind">The kind of file that will be transferred.</param>
/// <param name="fileSize">The size of the file that will be transferred.</param>
/// <param name="fileName">The filename of the file that will be transferred.</param>
/// <returns>Info about the file transfer on success.</returns>
public ToxFileInfo FileSend(int friendNumber, ToxFileKind kind, long fileSize, string fileName)
{
var error = ToxErrorFileSend.Ok;
return FileSend(friendNumber, kind, fileSize, fileName, out error);
}
/// <summary>
/// Send a file transmission request.
/// </summary>
/// <param name="friendNumber">The friend number to send the request to.</param>
/// <param name="kind">The kind of file that will be transferred.</param>
/// <param name="fileSize">The size of the file that will be transferred.</param>
/// <param name="fileName">The filename of the file that will be transferred.</param>
/// <param name="fileId">The id to identify this transfer with. Should be ToxConstants.FileIdLength bytes long.</param>
/// <param name="error"></param>
/// <returns>Info about the file transfer on success.</returns>
public ToxFileInfo FileSend(int friendNumber, ToxFileKind kind, long fileSize, string fileName, byte[] fileId, out ToxErrorFileSend error)
{
ThrowIfDisposed();
if (fileId.Length != ToxConstants.FileIdLength)
throw new ArgumentException("fileId should be exactly ToxConstants.FileIdLength bytes long", "fileId");
error = ToxErrorFileSend.Ok;
byte[] fileNameBytes = Encoding.UTF8.GetBytes(fileName);
int fileNumber = ToxTools.Map(ToxFunctions.FileSend(_tox, ToxTools.Map(friendNumber), kind, (ulong)fileSize, fileId, fileNameBytes, (uint)fileNameBytes.Length, ref error));
if (error == ToxErrorFileSend.Ok)
return new ToxFileInfo(fileNumber, fileId);
return null;
}
/// <summary>
/// Send a file transmission request.
/// </summary>
/// <param name="friendNumber">The friend number to send the request to.</param>
/// <param name="kind">The kind of file that will be transferred.</param>
/// <param name="fileSize">The size of the file that will be transferred.</param>
/// <param name="fileName">The filename of the file that will be transferred.</param>
/// <param name="fileId">The id to identify this transfer with. Should be ToxConstants.FileIdLength bytes long.</param>
/// <returns>Info about the file transfer on success.</returns>
public ToxFileInfo FileSend(int friendNumber, ToxFileKind kind, long fileSize, string fileName, byte[] fileId)
{
var error = ToxErrorFileSend.Ok;
return FileSend(friendNumber, kind, fileSize, fileName, fileId, out error);
}
/// <summary>
/// Sends a file seek control command to a friend for a given file transfer.
/// </summary>
/// <param name="friendNumber">The friend to send the seek command to.</param>
/// <param name="fileNumber">The file transfer that this command is meant for.</param>
/// <param name="position">The position that the friend should change his stream to.</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool FileSeek(int friendNumber, int fileNumber, long position, out ToxErrorFileSeek error)
{
ThrowIfDisposed();
error = ToxErrorFileSeek.Ok;
return ToxFunctions.FileSeek(_tox, ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), (ulong)position, ref error);
}
/// <summary>
/// Sends a file seek control command to a friend for a given file transfer.
/// </summary>
/// <param name="friendNumber">The friend to send the seek command to.</param>
/// <param name="fileNumber">The file transfer that this command is meant for.</param>
/// <param name="position">The position that the friend should change his stream to.</param>
/// <returns>True on success.</returns>
public bool FileSeek(int friendNumber, int fileNumber, long position)
{
var error = ToxErrorFileSeek.Ok;
return FileSeek(friendNumber, fileNumber, position, out error);
}
/// <summary>
/// Sends a chunk of file data to a friend. This should be called in response to OnFileChunkRequested.
/// </summary>
/// <param name="friendNumber">The friend to send the chunk to.</param>
/// <param name="fileNumber">The file transfer that this chunk belongs to.</param>
/// <param name="position">The position from which to continue reading.</param>
/// <param name="data">The data to send. (should be equal to 'Length' received through OnFileChunkRequested).</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool FileSendChunk(int friendNumber, int fileNumber, long position, byte[] data, out ToxErrorFileSendChunk error)
{
ThrowIfDisposed();
if (data == null)
throw new ArgumentNullException("data");
error = ToxErrorFileSendChunk.Ok;
return ToxFunctions.FileSendChunk(_tox, ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), (ulong)position, data, (uint)data.Length, ref error);
}
/// <summary>
/// Sends a chunk of file data to a friend. This should be called in response to OnFileChunkRequested.
/// </summary>
/// <param name="friendNumber">The friend to send the chunk to.</param>
/// <param name="fileNumber">The file transfer that this chunk belongs to.</param>
/// <param name="position">The position from which to continue reading.</param>
/// <param name="data">The data to send. (should be equal to 'Length' received through OnFileChunkRequested).</param>
/// <returns>True on success.</returns>
public bool FileSendChunk(int friendNumber, int fileNumber, long position, byte[] data)
{
var error = ToxErrorFileSendChunk.Ok;
return FileSendChunk(friendNumber, fileNumber, position, data, out error);
}
/// <summary>
/// Retrieves the unique id of a file transfer. This can be used to uniquely identify file transfers across core restarts.
/// </summary>
/// <param name="friendNumber">The friend number that's associated with this transfer.</param>
/// <param name="fileNumber">The target file transfer.</param>
/// <param name="error"></param>
/// <returns>File transfer id on success.</returns>
public byte[] FileGetId(int friendNumber, int fileNumber, out ToxErrorFileGet error)
{
ThrowIfDisposed();
error = ToxErrorFileGet.Ok;
byte[] id = new byte[ToxConstants.FileIdLength];
if (!ToxFunctions.FileGetFileId(_tox, ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), id, ref error))
return null;
return id;
}
/// <summary>
/// Retrieves the unique id of a file transfer. This can be used to uniquely identify file transfers across core restarts.
/// </summary>
/// <param name="friendNumber">The friend number that's associated with this transfer.</param>
/// <param name="fileNumber">The target file transfer.</param>
/// <returns>File transfer id on success.</returns>
public byte[] FileGetId(int friendNumber, int fileNumber)
{
var error = ToxErrorFileGet.Ok;
return FileGetId(friendNumber, fileNumber, out error);
}
/// <summary>
/// Sends a custom lossy packet to a friend.
/// Lossy packets are like UDP packets, they may never reach the other side, arrive more than once or arrive in the wrong order.
/// </summary>
/// <param name="friendNumber">The friend to send the packet to.</param>
/// <param name="data">The data to send. The first byte must be in the range 200-254. The maximum length of the data is ToxConstants.MaxCustomPacketSize</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool FriendSendLossyPacket(int friendNumber, byte[] data, out ToxErrorFriendCustomPacket error)
{
ThrowIfDisposed();
if (data == null)
throw new ArgumentNullException("data");
error = ToxErrorFriendCustomPacket.Ok;
return ToxFunctions.FriendSendLossyPacket(_tox, ToxTools.Map(friendNumber), data, (uint)data.Length, ref error);
}
/// <summary>
/// Sends a custom lossy packet to a friend.
/// Lossy packets are like UDP packets, they may never reach the other side, arrive more than once or arrive in the wrong order.
/// </summary>
/// <param name="friendNumber">The friend to send the packet to.</param>
/// <param name="data">The data to send. The first byte must be in the range 200-254. The maximum length of the data is ToxConstants.MaxCustomPacketSize</param>
/// <returns>True on success.</returns>
public bool FriendSendLossyPacket(int friendNumber, byte[] data)
{
var error = ToxErrorFriendCustomPacket.Ok;
return FriendSendLossyPacket(friendNumber, data, out error);
}
/// <summary>
/// Sends a custom lossless packet to a friend.
/// Lossless packets behave like TCP, they're reliable and arrive in order. The difference is that it's not a stream.
/// </summary>
/// <param name="friendNumber">The friend to send the packet to.</param>
/// <param name="data">The data to send. The first byte must be in the range 160-191. The maximum length of the data is ToxConstants.MaxCustomPacketSize</param>
/// <param name="error"></param>
/// <returns>True on success.</returns>
public bool FriendSendLosslessPacket(int friendNumber, byte[] data, out ToxErrorFriendCustomPacket error)
{
ThrowIfDisposed();
if (data == null)
throw new ArgumentNullException("data");
error = ToxErrorFriendCustomPacket.Ok;
return ToxFunctions.FriendSendLosslessPacket(_tox, ToxTools.Map(friendNumber), data, (uint)data.Length, ref error);
}
/// <summary>
/// Sends a custom lossless packet to a friend.
/// Lossless packets behave like TCP, they're reliable and arrive in order. The difference is that it's not a stream.
/// </summary>
/// <param name="friendNumber">The friend to send the packet to.</param>
/// <param name="data">The data to send. The first byte must be in the range 160-191. The maximum length of the data is ToxConstants.MaxCustomPacketSize</param>
/// <returns>True on success.</returns>
public bool FriendSendLosslessPacket(int friendNumber, byte[] data)
{
var error = ToxErrorFriendCustomPacket.Ok;
return FriendSendLosslessPacket(friendNumber, data, out error);
}
/// <summary>
/// Retrieves an array of group member names.
/// </summary>
/// <param name="groupNumber">The group to retrieve member names of.</param>
/// <returns>A string array of group member names on success.</returns>
public string[] GetGroupNames(int groupNumber)
{
ThrowIfDisposed();
int count = ToxFunctions.GroupNumberPeers(_tox, groupNumber);
if (count <= 0)
return new string[0];
ushort[] lengths = new ushort[count];
byte[,] matrix = new byte[count, ToxConstants.MaxNameLength];
int result = ToxFunctions.GroupGetNames(_tox, groupNumber, matrix, lengths, (ushort)count);
string[] names = new string[count];
for (int i = 0; i < count; i++)
{
byte[] name = new byte[lengths[i]];
for (int j = 0; j < name.Length; j++)
name[j] = matrix[i, j];
names[i] = Encoding.UTF8.GetString(name, 0, name.Length);
}
return names;
}
/// <summary>
/// Joins a group with the given public key of the group.
/// </summary>
/// <param name="friendNumber">The friend number we received an invite from.</param>
/// <param name="data">Data obtained from the OnGroupInvite event.</param>
/// <returns>The group number on success.</returns>
public int JoinGroup(int friendNumber, byte[] data)
{
ThrowIfDisposed();
if (data == null)
throw new ArgumentNullException("data");
return ToxFunctions.JoinGroupchat(_tox, friendNumber, data, (ushort)data.Length);
}
/// <summary>
/// Retrieves the name of a group member.
/// </summary>
/// <param name="groupNumber">The group that the peer is in.</param>
/// <param name="peerNumber">The peer to retrieve the name of.</param>
/// <returns>The peer's name on success.</returns>
public string GetGroupMemberName(int groupNumber, int peerNumber)
{
ThrowIfDisposed();
byte[] name = new byte[ToxConstants.MaxNameLength];
if (ToxFunctions.GroupPeername(_tox, groupNumber, peerNumber, name) == -1)
throw new Exception("Could not get peer name");
return ToxTools.RemoveNull(Encoding.UTF8.GetString(name, 0, name.Length));
}
/// <summary>
/// Retrieves the number of group members in a group chat.
/// </summary>
/// <param name="groupNumber">The group to get the member count of.</param>
/// <returns>The member count on success.</returns>
public int GetGroupMemberCount(int groupNumber)
{
ThrowIfDisposed();
return ToxFunctions.GroupNumberPeers(_tox, groupNumber);
}
/// <summary>
/// Deletes a group chat.
/// </summary>
/// <param name="groupNumber">The group to delete.</param>
/// <returns>True on success.</returns>
public bool DeleteGroupChat(int groupNumber)
{
ThrowIfDisposed();
return ToxFunctions.DelGroupchat(_tox, groupNumber) == 0;
}
/// <summary>
/// Invites a friend to a group chat.
/// </summary>
/// <param name="friendNumber">The friend to invite to a group.</param>
/// <param name="groupNumber">The group to invite the friend to.</param>
/// <returns>True on success.</returns>
public bool InviteFriend(int friendNumber, int groupNumber)
{
ThrowIfDisposed();
return ToxFunctions.InviteFriend(_tox, friendNumber, groupNumber) == 0;
}
/// <summary>
/// Sends a message to a group.
/// </summary>
/// <param name="groupNumber">The group to send the message to.</param>
/// <param name="message">The message to send.</param>
/// <returns>True on success.</returns>
public bool SendGroupMessage(int groupNumber, string message)
{
ThrowIfDisposed();
byte[] msg = Encoding.UTF8.GetBytes(message);
return ToxFunctions.GroupMessageSend(_tox, groupNumber, msg, (ushort)msg.Length) == 0;
}
/// <summary>
/// Sends an action to a group.
/// </summary>
/// <param name="groupNumber">The group to send the action to.</param>
/// <param name="action">The action to send.</param>
/// <returns>True on success.</returns>
public bool SendGroupAction(int groupNumber, string action)
{
ThrowIfDisposed();
byte[] act = Encoding.UTF8.GetBytes(action);
return ToxFunctions.GroupActionSend(_tox, groupNumber, act, (ushort)act.Length) == 0;
}
/// <summary>
/// Creates a new group and retrieves the group number.
/// </summary>
/// <returns>The number of the created group on success.</returns>
public int NewGroup()
{
ThrowIfDisposed();
return ToxFunctions.AddGroupchat(_tox);
}
/// <summary>
/// Check if the given peernumber corresponds to ours.
/// </summary>
/// <param name="groupNumber">The group to check in.</param>
/// <param name="peerNumber">The peer number to check.</param>
/// <returns>True if the given peer number is ours.</returns>
public bool PeerNumberIsOurs(int groupNumber, int peerNumber)
{
ThrowIfDisposed();
return ToxFunctions.GroupPeerNumberIsOurs(_tox, groupNumber, peerNumber) == 1;
}
/// <summary>
/// Changes the title of a group.
/// </summary>
/// <param name="groupNumber">The group to change the title of.</param>
/// <param name="title">The title to set.</param>
/// <returns>True on success.</returns>
public bool SetGroupTitle(int groupNumber, string title)
{
ThrowIfDisposed();
if (Encoding.UTF8.GetByteCount(title) > ToxConstants.MaxNameLength)
throw new ArgumentException("The specified group title is longer than 256 bytes");
byte[] bytes = Encoding.UTF8.GetBytes(title);
return ToxFunctions.GroupSetTitle(_tox, groupNumber, bytes, (byte)bytes.Length) == 0;
}
/// <summary>
/// Retrieves the type of a group.
/// </summary>
/// <param name="groupNumber">The group to retrieve the type of.</param>
/// <returns>The group type on success.</returns>
public ToxGroupType GetGroupType(int groupNumber)
{
ThrowIfDisposed();
return (ToxGroupType)ToxFunctions.GroupGetType(_tox, groupNumber);
}
/// <summary>
/// Retrieves the title of a group.
/// </summary>
/// <param name="groupNumber">The group to retrieve the title of.</param>
/// <returns>The group's title on success.</returns>
public string GetGroupTitle(int groupNumber)
{
ThrowIfDisposed();
byte[] title = new byte[ToxConstants.MaxNameLength];
int length = ToxFunctions.GroupGetTitle(_tox, groupNumber, title, (uint)title.Length);
if (length == -1)
return string.Empty;
return Encoding.UTF8.GetString(title, 0, length);
}
/// <summary>
/// Retrieves the public key of a peer.
/// </summary>
/// <param name="groupNumber">The group that the peer is in.</param>
/// <param name="peerNumber">The peer to retrieve the public key of.</param>
/// <returns>The peer's public key on success.</returns>
public ToxKey GetGroupPeerPublicKey(int groupNumber, int peerNumber)
{
ThrowIfDisposed();
byte[] key = new byte[ToxConstants.PublicKeySize];
int result = ToxFunctions.GroupPeerPubkey(_tox, groupNumber, peerNumber, key);
if (result != 0)
return null;
return new ToxKey(ToxKeyType.Public, key);
}
/// <summary>
/// Retrieves the time a friend was last seen online.
/// </summary>
/// <param name="friendNumber">The friend to retrieve the 'last online' of.</param>
/// <param name="error"></param>
/// <returns>The time this friend was last seen online, on success.</returns>
public DateTime GetFriendLastOnline(int friendNumber, out ToxErrorFriendGetLastOnline error)
{
error = ToxErrorFriendGetLastOnline.Ok;
ulong time = ToxFunctions.FriendGetLastOnline(_tox, ToxTools.Map(friendNumber), ref error);
return ToxTools.EpochToDateTime(time);
}
/// <summary>
/// Retrieves the time a friend was last seen online.
/// </summary>
/// <param name="friendNumber">The friend to retrieve the 'last online' of.</param>
/// <returns>The time this friend was last seen online, on success.</returns>
public DateTime GetFriendLastOnline(int friendNumber)
{
var error = ToxErrorFriendGetLastOnline.Ok;
return GetFriendLastOnline(friendNumber, out error);
}
#region Events
private EventHandler<ToxEventArgs.FriendRequestEventArgs> _onFriendRequestReceived;
/// <summary>
/// Occurs when a friend request is received.
/// Friend requests should be accepted with AddFriendNoRequest.
/// </summary>
public event EventHandler<ToxEventArgs.FriendRequestEventArgs> OnFriendRequestReceived
{
add
{
if (_onFriendRequestCallback == null)
{
_onFriendRequestCallback = (IntPtr tox, byte[] publicKey, byte[] message, uint length, IntPtr userData) =>
{
if (_onFriendRequestReceived != null)
_onFriendRequestReceived(this, new ToxEventArgs.FriendRequestEventArgs(new ToxKey(ToxKeyType.Public, ToxTools.HexBinToString(publicKey)), Encoding.UTF8.GetString(message, 0, (int)length)));
};
ToxFunctions.RegisterFriendRequestCallback(_tox, _onFriendRequestCallback, IntPtr.Zero);
}
_onFriendRequestReceived += value;
}
remove
{
if (_onFriendRequestReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFriendRequestCallback(_tox, null, IntPtr.Zero);
_onFriendRequestCallback = null;
}
_onFriendRequestReceived -= value;
}
}
private EventHandler<ToxEventArgs.FriendMessageEventArgs> _onFriendMessageReceived;
/// <summary>
/// Occurs when a message is received from a friend.
/// </summary>
public event EventHandler<ToxEventArgs.FriendMessageEventArgs> OnFriendMessageReceived
{
add
{
if (_onFriendMessageCallback == null)
{
_onFriendMessageCallback = (IntPtr tox, uint friendNumber, ToxMessageType type, byte[] message, uint length, IntPtr userData) =>
{
if (_onFriendMessageReceived != null)
_onFriendMessageReceived(this, new ToxEventArgs.FriendMessageEventArgs(ToxTools.Map(friendNumber), Encoding.UTF8.GetString(message, 0, (int)length), type));
};
ToxFunctions.RegisterFriendMessageCallback(_tox, _onFriendMessageCallback, IntPtr.Zero);
}
_onFriendMessageReceived += value;
}
remove
{
if (_onFriendMessageReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFriendMessageCallback(_tox, null, IntPtr.Zero);
_onFriendMessageCallback = null;
}
_onFriendMessageReceived -= value;
}
}
private EventHandler<ToxEventArgs.NameChangeEventArgs> _onFriendNameChanged;
/// <summary>
/// Occurs when a friend has changed his/her name.
/// </summary>
public event EventHandler<ToxEventArgs.NameChangeEventArgs> OnFriendNameChanged
{
add
{
if (_onNameChangeCallback == null)
{
_onNameChangeCallback = (IntPtr tox, uint friendNumber, byte[] newName, uint length, IntPtr userData) =>
{
if (_onFriendNameChanged != null)
_onFriendNameChanged(this, new ToxEventArgs.NameChangeEventArgs(ToxTools.Map(friendNumber), Encoding.UTF8.GetString(newName, 0, (int)length)));
};
ToxFunctions.RegisterNameChangeCallback(_tox, _onNameChangeCallback, IntPtr.Zero);
}
_onFriendNameChanged += value;
}
remove
{
if (_onFriendNameChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterNameChangeCallback(_tox, null, IntPtr.Zero);
_onNameChangeCallback = null;
}
_onFriendNameChanged -= value;
}
}
private EventHandler<ToxEventArgs.StatusMessageEventArgs> _onFriendStatusMessageChanged;
/// <summary>
/// Occurs when a friend has changed their status message.
/// </summary>
public event EventHandler<ToxEventArgs.StatusMessageEventArgs> OnFriendStatusMessageChanged
{
add
{
if (_onStatusMessageCallback == null)
{
_onStatusMessageCallback = (IntPtr tox, uint friendNumber, byte[] newStatus, uint length, IntPtr userData) =>
{
if (_onFriendStatusMessageChanged != null)
_onFriendStatusMessageChanged(this, new ToxEventArgs.StatusMessageEventArgs(ToxTools.Map(friendNumber), Encoding.UTF8.GetString(newStatus, 0, (int)length)));
};
ToxFunctions.RegisterStatusMessageCallback(_tox, _onStatusMessageCallback, IntPtr.Zero);
}
_onFriendStatusMessageChanged += value;
}
remove
{
if (_onFriendStatusMessageChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterStatusMessageCallback(_tox, null, IntPtr.Zero);
_onStatusMessageCallback = null;
}
_onFriendStatusMessageChanged -= value;
}
}
private EventHandler<ToxEventArgs.StatusEventArgs> _onFriendStatusChanged;
/// <summary>
/// Occurs when a friend has changed their user status.
/// </summary>
public event EventHandler<ToxEventArgs.StatusEventArgs> OnFriendStatusChanged
{
add
{
if (_onUserStatusCallback == null)
{
_onUserStatusCallback = (IntPtr tox, uint friendNumber, ToxUserStatus status, IntPtr userData) =>
{
if (_onFriendStatusChanged != null)
_onFriendStatusChanged(this, new ToxEventArgs.StatusEventArgs(ToxTools.Map(friendNumber), status));
};
ToxFunctions.RegisterUserStatusCallback(_tox, _onUserStatusCallback, IntPtr.Zero);
}
_onFriendStatusChanged += value;
}
remove
{
if (_onFriendStatusChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterUserStatusCallback(_tox, null, IntPtr.Zero);
_onUserStatusCallback = null;
}
_onFriendStatusChanged -= value;
}
}
private EventHandler<ToxEventArgs.TypingStatusEventArgs> _onFriendTypingChanged;
/// <summary>
/// Occurs when a friend's typing status has changed.
/// </summary>
public event EventHandler<ToxEventArgs.TypingStatusEventArgs> OnFriendTypingChanged
{
add
{
if (_onTypingChangeCallback == null)
{
_onTypingChangeCallback = (IntPtr tox, uint friendNumber, bool typing, IntPtr userData) =>
{
if (_onFriendTypingChanged != null)
_onFriendTypingChanged(this, new ToxEventArgs.TypingStatusEventArgs(ToxTools.Map(friendNumber), typing));
};
ToxFunctions.RegisterTypingChangeCallback(_tox, _onTypingChangeCallback, IntPtr.Zero);
}
_onFriendTypingChanged += value;
}
remove
{
if (_onFriendTypingChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterTypingChangeCallback(_tox, null, IntPtr.Zero);
_onTypingChangeCallback = null;
}
_onFriendTypingChanged -= value;
}
}
private EventHandler<ToxEventArgs.ConnectionStatusEventArgs> _onConnectionStatusChanged;
/// <summary>
/// Occurs when the connection status of this Tox instance has changed.
/// </summary>
public event EventHandler<ToxEventArgs.ConnectionStatusEventArgs> OnConnectionStatusChanged
{
add
{
if (_onConnectionStatusCallback == null)
{
_onConnectionStatusCallback = (IntPtr tox, ToxConnectionStatus status, IntPtr userData) =>
{
if (_onConnectionStatusChanged != null)
_onConnectionStatusChanged(this, new ToxEventArgs.ConnectionStatusEventArgs(status));
};
ToxFunctions.RegisterConnectionStatusCallback(_tox, _onConnectionStatusCallback, IntPtr.Zero);
}
_onConnectionStatusChanged += value;
}
remove
{
if (_onConnectionStatusChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterConnectionStatusCallback(_tox, null, IntPtr.Zero);
_onConnectionStatusCallback = null;
}
_onConnectionStatusChanged -= value;
}
}
private EventHandler<ToxEventArgs.FriendConnectionStatusEventArgs> _onFriendConnectionStatusChanged;
/// <summary>
/// Occurs when the connection status of a friend has changed.
/// </summary>
public event EventHandler<ToxEventArgs.FriendConnectionStatusEventArgs> OnFriendConnectionStatusChanged
{
add
{
if (_onFriendConnectionStatusCallback == null)
{
_onFriendConnectionStatusCallback = (IntPtr tox, uint friendNumber, ToxConnectionStatus status, IntPtr userData) =>
{
if (_onFriendConnectionStatusChanged != null)
_onFriendConnectionStatusChanged(this, new ToxEventArgs.FriendConnectionStatusEventArgs(ToxTools.Map(friendNumber), status));
};
ToxFunctions.RegisterFriendConnectionStatusCallback(_tox, _onFriendConnectionStatusCallback, IntPtr.Zero);
}
_onFriendConnectionStatusChanged += value;
}
remove
{
if (_onFriendConnectionStatusChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFriendConnectionStatusCallback(_tox, null, IntPtr.Zero);
_onFriendConnectionStatusCallback = null;
}
_onFriendConnectionStatusChanged -= value;
}
}
private EventHandler<ToxEventArgs.ReadReceiptEventArgs> _onReadReceiptReceived;
/// <summary>
/// Occurs when a read receipt is received.
/// </summary>
public event EventHandler<ToxEventArgs.ReadReceiptEventArgs> OnReadReceiptReceived
{
add
{
if (_onReadReceiptCallback == null)
{
_onReadReceiptCallback = (IntPtr tox, uint friendNumber, uint receipt, IntPtr userData) =>
{
if (_onReadReceiptReceived != null)
_onReadReceiptReceived(this, new ToxEventArgs.ReadReceiptEventArgs(ToxTools.Map(friendNumber), ToxTools.Map(receipt)));
};
ToxFunctions.RegisterFriendReadReceiptCallback(_tox, _onReadReceiptCallback, IntPtr.Zero);
}
_onReadReceiptReceived += value;
}
remove
{
if (_onReadReceiptReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFriendReadReceiptCallback(_tox, null, IntPtr.Zero);
_onReadReceiptCallback = null;
}
_onReadReceiptReceived -= value;
}
}
private EventHandler<ToxEventArgs.FileControlEventArgs> _onFileControlReceived;
/// <summary>
/// Occurs when a file control is received.
/// </summary>
public event EventHandler<ToxEventArgs.FileControlEventArgs> OnFileControlReceived
{
add
{
if (_onFileControlCallback == null)
{
_onFileControlCallback = (IntPtr tox, uint friendNumber, uint fileNumber, ToxFileControl control, IntPtr userData) =>
{
if (_onFileControlReceived != null)
_onFileControlReceived(this, new ToxEventArgs.FileControlEventArgs(ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), control));
};
ToxFunctions.RegisterFileControlRecvCallback(_tox, _onFileControlCallback, IntPtr.Zero);
}
_onFileControlReceived += value;
}
remove
{
if (_onFileControlReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFileControlRecvCallback(_tox, null, IntPtr.Zero);
_onFileControlCallback = null;
}
_onFileControlReceived -= value;
}
}
private EventHandler<ToxEventArgs.FileChunkEventArgs> _onFileChunkReceived;
/// <summary>
/// Occurs when a chunk of data from a file transfer is received
/// </summary>
public event EventHandler<ToxEventArgs.FileChunkEventArgs> OnFileChunkReceived
{
add
{
if (_onFileReceiveChunkCallback == null)
{
_onFileReceiveChunkCallback = (IntPtr tox, uint friendNumber, uint fileNumber, ulong position, byte[] data, uint length, IntPtr userData) =>
{
if (_onFileChunkReceived != null)
_onFileChunkReceived(this, new ToxEventArgs.FileChunkEventArgs(ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), data, (long)position));
};
ToxFunctions.RegisterFileReceiveChunkCallback(_tox, _onFileReceiveChunkCallback, IntPtr.Zero);
}
_onFileChunkReceived += value;
}
remove
{
if (_onFileChunkReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFileReceiveChunkCallback(_tox, null, IntPtr.Zero);
_onFileReceiveChunkCallback = null;
}
_onFileChunkReceived -= value;
}
}
private EventHandler<ToxEventArgs.FileSendRequestEventArgs> _onFileSendRequestReceived;
/// <summary>
/// Occurs when a new file transfer request has been received.
/// </summary>
public event EventHandler<ToxEventArgs.FileSendRequestEventArgs> OnFileSendRequestReceived
{
add
{
if (_onFileReceiveCallback == null)
{
_onFileReceiveCallback = (IntPtr tox, uint friendNumber, uint fileNumber, ToxFileKind kind, ulong fileSize, byte[] filename, uint filenameLength, IntPtr userData) =>
{
if (_onFileSendRequestReceived != null)
_onFileSendRequestReceived(this, new ToxEventArgs.FileSendRequestEventArgs(ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), kind, (long)fileSize, filename == null ? string.Empty : Encoding.UTF8.GetString(filename, 0, filename.Length)));
};
ToxFunctions.RegisterFileReceiveCallback(_tox, _onFileReceiveCallback, IntPtr.Zero);
}
_onFileSendRequestReceived += value;
}
remove
{
if (_onFileSendRequestReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFileReceiveCallback(_tox, null, IntPtr.Zero);
_onFileReceiveCallback = null;
}
_onFileSendRequestReceived -= value;
}
}
private EventHandler<ToxEventArgs.FileRequestChunkEventArgs> _onFileChunkRequested;
/// <summary>
/// Occurs when the core requests the next chunk of the file.
/// </summary>
public event EventHandler<ToxEventArgs.FileRequestChunkEventArgs> OnFileChunkRequested
{
add
{
if (_onFileRequestChunkCallback == null)
{
_onFileRequestChunkCallback = (IntPtr tox, uint friendNumber, uint fileNumber, ulong position, uint length, IntPtr userData) =>
{
if (_onFileChunkRequested != null)
_onFileChunkRequested(this, new ToxEventArgs.FileRequestChunkEventArgs(ToxTools.Map(friendNumber), ToxTools.Map(fileNumber), (long)position, (int)length));
};
ToxFunctions.RegisterFileChunkRequestCallback(_tox, _onFileRequestChunkCallback, IntPtr.Zero);
}
_onFileChunkRequested += value;
}
remove
{
if (_onFileChunkRequested.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFileChunkRequestCallback(_tox, null, IntPtr.Zero);
_onFileRequestChunkCallback = null;
}
_onFileChunkRequested -= value;
}
}
private EventHandler<ToxEventArgs.FriendPacketEventArgs> _onFriendLossyPacketReceived;
/// <summary>
/// Occurs when a lossy packet from a friend is received.
/// </summary>
public event EventHandler<ToxEventArgs.FriendPacketEventArgs> OnFriendLossyPacketReceived
{
add
{
if (_onFriendLossyPacketCallback == null)
{
_onFriendLossyPacketCallback = (IntPtr tox, uint friendNumber, byte[] data, uint length, IntPtr userData) =>
{
if (_onFriendLossyPacketReceived != null)
_onFriendLossyPacketReceived(this, new ToxEventArgs.FriendPacketEventArgs(ToxTools.Map(friendNumber), data));
};
ToxFunctions.RegisterFriendLossyPacketCallback(_tox, _onFriendLossyPacketCallback, IntPtr.Zero);
}
_onFriendLossyPacketReceived += value;
}
remove
{
if (_onFriendLossyPacketReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFriendLossyPacketCallback(_tox, null, IntPtr.Zero);
_onFriendLossyPacketCallback = null;
}
_onFriendLossyPacketReceived -= value;
}
}
private EventHandler<ToxEventArgs.FriendPacketEventArgs> _onFriendLosslessPacketReceived;
/// <summary>
/// Occurs when a lossless packet from a friend is received.
/// </summary>
public event EventHandler<ToxEventArgs.FriendPacketEventArgs> OnFriendLosslessPacketReceived
{
add
{
if (_onFriendLosslessPacketCallback == null)
{
_onFriendLosslessPacketCallback = (IntPtr tox, uint friendNumber, byte[] data, uint length, IntPtr userData) =>
{
if (_onFriendLosslessPacketReceived != null)
_onFriendLosslessPacketReceived(this, new ToxEventArgs.FriendPacketEventArgs(ToxTools.Map(friendNumber), data));
};
ToxFunctions.RegisterFriendLosslessPacketCallback(_tox, _onFriendLosslessPacketCallback, IntPtr.Zero);
}
_onFriendLosslessPacketReceived += value;
}
remove
{
if (_onFriendLosslessPacketReceived.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterFriendLosslessPacketCallback(_tox, null, IntPtr.Zero);
_onFriendLosslessPacketCallback = null;
}
_onFriendLosslessPacketReceived -= value;
}
}
private EventHandler<ToxEventArgs.GroupActionEventArgs> _onGroupAction;
/// <summary>
/// Occurs when an action is received from a group.
/// </summary>
public event EventHandler<ToxEventArgs.GroupActionEventArgs> OnGroupAction
{
add
{
if (_onGroupActionCallback == null)
{
_onGroupActionCallback = (IntPtr tox, int groupNumber, int peerNumber, byte[] action, ushort length, IntPtr userData) =>
{
if (_onGroupAction != null)
_onGroupAction(this, new ToxEventArgs.GroupActionEventArgs(groupNumber, peerNumber, Encoding.UTF8.GetString(action, 0, length)));
};
ToxFunctions.RegisterGroupActionCallback(_tox, _onGroupActionCallback, IntPtr.Zero);
}
_onGroupAction += value;
}
remove
{
if (_onGroupAction.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterGroupActionCallback(_tox, null, IntPtr.Zero);
_onGroupActionCallback = null;
}
_onGroupAction -= value;
}
}
private EventHandler<ToxEventArgs.GroupMessageEventArgs> _onGroupMessage;
/// <summary>
/// Occurs when a message is received from a group.
/// </summary>
public event EventHandler<ToxEventArgs.GroupMessageEventArgs> OnGroupMessage
{
add
{
if (_onGroupMessageCallback == null)
{
_onGroupMessageCallback = (IntPtr tox, int groupNumber, int peerNumber, byte[] message, ushort length, IntPtr userData) =>
{
if (_onGroupMessage != null)
_onGroupMessage(this, new ToxEventArgs.GroupMessageEventArgs(groupNumber, peerNumber, Encoding.UTF8.GetString(message, 0, length)));
};
ToxFunctions.RegisterGroupMessageCallback(_tox, _onGroupMessageCallback, IntPtr.Zero);
}
_onGroupMessage += value;
}
remove
{
if (_onGroupMessage.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterGroupMessageCallback(_tox, null, IntPtr.Zero);
_onGroupMessageCallback = null;
}
_onGroupMessage -= value;
}
}
private EventHandler<ToxEventArgs.GroupInviteEventArgs> _onGroupInvite;
/// <summary>
/// Occurs when a friend has sent an invite to a group.
/// </summary>
public event EventHandler<ToxEventArgs.GroupInviteEventArgs> OnGroupInvite
{
add
{
if (_onGroupInviteCallback == null)
{
_onGroupInviteCallback = (IntPtr tox, int friendNumber, byte type, byte[] data, ushort length, IntPtr userData) =>
{
if (_onGroupInvite != null)
_onGroupInvite(this, new ToxEventArgs.GroupInviteEventArgs(friendNumber, (ToxGroupType)type, data));
};
ToxFunctions.RegisterGroupInviteCallback(_tox, _onGroupInviteCallback, IntPtr.Zero);
}
_onGroupInvite += value;
}
remove
{
if (_onGroupInvite.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterGroupInviteCallback(_tox, null, IntPtr.Zero);
_onGroupInviteCallback = null;
}
_onGroupInvite -= value;
}
}
private EventHandler<ToxEventArgs.GroupNamelistChangeEventArgs> _onGroupNamelistChange;
/// <summary>
/// Occurs when the name list of a group has changed.
/// </summary>
public event EventHandler<ToxEventArgs.GroupNamelistChangeEventArgs> OnGroupNamelistChange
{
add
{
if (_onGroupNamelistChangeCallback == null)
{
_onGroupNamelistChangeCallback = (IntPtr tox, int groupNumber, int peerNumber, ToxChatChange change, IntPtr userData) =>
{
if (_onGroupNamelistChange != null)
_onGroupNamelistChange(this, new ToxEventArgs.GroupNamelistChangeEventArgs(groupNumber, peerNumber, change));
};
ToxFunctions.RegisterGroupNamelistChangeCallback(_tox, _onGroupNamelistChangeCallback, IntPtr.Zero);
}
_onGroupNamelistChange += value;
}
remove
{
if (_onGroupNamelistChange.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterGroupNamelistChangeCallback(_tox, null, IntPtr.Zero);
_onGroupNamelistChangeCallback = null;
}
_onGroupNamelistChange -= value;
}
}
private EventHandler<ToxEventArgs.GroupTitleEventArgs> _onGroupTitleChanged;
/// <summary>
/// Occurs when the title of a groupchat is changed.
/// </summary>
public event EventHandler<ToxEventArgs.GroupTitleEventArgs> OnGroupTitleChanged
{
add
{
if (_onGroupTitleCallback == null)
{
_onGroupTitleCallback = (IntPtr tox, int groupNumber, int peerNumber, byte[] title, byte length, IntPtr userData) =>
{
if (_onGroupTitleChanged != null)
_onGroupTitleChanged(this, new ToxEventArgs.GroupTitleEventArgs(groupNumber, peerNumber, Encoding.UTF8.GetString(title, 0, length)));
};
ToxFunctions.RegisterGroupTitleCallback(_tox, _onGroupTitleCallback, IntPtr.Zero);
}
_onGroupTitleChanged += value;
}
remove
{
if (_onGroupTitleChanged.GetInvocationList().Length == 1)
{
ToxFunctions.RegisterGroupTitleCallback(_tox, null, IntPtr.Zero);
_onGroupTitleCallback = null;
}
_onGroupTitleChanged -= value;
}
}
#endregion
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(GetType().FullName);
}
}
}
| 41.263109 | 270 | 0.566845 | [
"MIT"
] | Impyy/SharpTox | SharpTox/Core/Tox.cs | 86,770 | C# |
//-----------------------------------------------------------------------
// <copyright file="BasicTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.Basic
{
[TestClass]
public class BasicTests
{
[TestMethod]
public void TestNotUndoableField()
{
Csla.ApplicationContext.GlobalContext.Clear();
Csla.Test.DataBinding.ParentEntity p = Csla.Test.DataBinding.ParentEntity.NewParentEntity();
p.NotUndoable = "something";
p.Data = "data";
p.BeginEdit();
p.NotUndoable = "something else";
p.Data = "new data";
p.CancelEdit();
//NotUndoable property points to a private field marked with [NotUndoable()]
//so its state is never copied when BeginEdit() is called
Assert.AreEqual("something else", p.NotUndoable);
//the Data property points to a field that is undoable, so it reverts
Assert.AreEqual("data", p.Data);
}
[TestMethod]
public void TestReadOnlyList()
{
//ReadOnlyList list = ReadOnlyList.GetReadOnlyList();
// Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["ReadOnlyList"]);
}
[TestMethod]
public void TestNameValueList()
{
NameValueListObj nvList = NameValueListObj.GetNameValueListObj();
Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["NameValueListObj"]);
Assert.AreEqual("element_1", nvList[1].Value);
//won't work, because IsReadOnly is set to true after object is populated in the for
//loop in DataPortal_Fetch
//NameValueListObj.NameValuePair newPair = new NameValueListObj.NameValuePair(45, "something");
//nvList.Add(newPair);
//Assert.AreEqual("something", nvList[45].Value);
}
[TestMethod]
public void TestCommandBase()
{
Csla.ApplicationContext.GlobalContext.Clear();
CommandObject obj = new CommandObject();
Assert.AreEqual("Executed", obj.ExecuteServerCode().AProperty);
}
[TestMethod]
public void CreateGenRoot()
{
Csla.ApplicationContext.GlobalContext.Clear();
GenRoot root;
root = GenRoot.NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["GenRoot"]);
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void InheritanceUndo()
{
Csla.ApplicationContext.GlobalContext.Clear();
GenRoot root;
root = GenRoot.NewRoot();
root.BeginEdit();
root.Data = "abc";
root.CancelEdit();
Csla.ApplicationContext.GlobalContext.Clear();
root = GenRoot.NewRoot();
root.BeginEdit();
root.Data = "abc";
root.ApplyEdit();
}
[TestMethod]
public void CreateRoot()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root;
root = Csla.Test.Basic.Root.NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["Root"]);
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void AddChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddRemoveChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Remove(root.Children[0]);
Assert.AreEqual(0, root.Children.Count);
}
[TestMethod]
public void AddRemoveAddChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Add("2");
root.CancelEdit();
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddGrandChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
Assert.AreEqual(1, child.GrandChildren.Count);
Assert.AreEqual("1", child.GrandChildren[0].Data);
}
[TestMethod]
public void AddRemoveGrandChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
child.GrandChildren.Remove(child.GrandChildren[0]);
Assert.AreEqual(0, child.GrandChildren.Count);
}
///<remarks>"the non-generic method AreEqual cannot be used with type arguments" - though
///it is used with type arguments in BasicTests.vb
///</remarks>
//[TestMethod]
//public void CloneGraph()
//{
// Csla.ApplicationContext.GlobalContext.Clear();
// Root root = Csla.Test.Basic.Root.NewRoot();
// FormSimulator form = new FormSimulator(root);
// SerializableListener listener = new SerializableListener(root);
// root.Children.Add("1");
// Child child = root.Children[0];
// Child.GrandChildren.Add("1");
// Assert.AreEqual<int>(1, child.GrandChildren.Count);
// Assert.AreEqual<string>("1", child.GrandChildren[0].Data);
// Root clone = ((Root)(root.Clone()));
// child = clone.Children[0];
// Assert.AreEqual<int>(1, child.GrandChildren.Count);
// Assert.AreEqual<string>("1", child.GrandChildren[0].Data);
// Assert.AreEqual<string>("root Deserialized", ((string)(Csla.ApplicationContext.GlobalContext["Deserialized"])));
// Assert.AreEqual<string>("GC Deserialized", ((string)(Csla.ApplicationContext.GlobalContext["GCDeserialized"])));
//}
[TestMethod]
public void ClearChildList()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("A");
root.Children.Add("B");
root.Children.Add("C");
root.Children.Clear();
Assert.AreEqual(0, root.Children.Count, "Count should be 0");
Assert.AreEqual(3, root.Children.DeletedCount, "Deleted count should be 3");
}
[TestMethod]
public void NestedAddAcceptchild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.BeginEdit();
root.Children.Add("A");
root.BeginEdit();
root.Children.Add("B");
root.BeginEdit();
root.Children.Add("C");
root.ApplyEdit();
root.ApplyEdit();
root.ApplyEdit();
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void NestedAddDeleteAcceptChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.BeginEdit();
root.Children.Add("A");
root.BeginEdit();
root.Children.Add("B");
root.BeginEdit();
root.Children.Add("C");
Child childC = root.Children[2];
Assert.AreEqual(true, root.Children.Contains(childC), "Child should be in collection");
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Assert.AreEqual(false, root.Children.Contains(childC), "Child should not be in collection");
Assert.AreEqual(true, root.Children.ContainsDeleted(childC), "Deleted child should be in deleted collection");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after first applyedit");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after ApplyEdit");
root.ApplyEdit();
Assert.AreEqual(0, root.Children.Count, "No children should remain");
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after third applyedit");
}
[TestMethod]
public void BasicEquality()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root r1 = Root.NewRoot();
r1.Data = "abc";
Assert.AreEqual(true, r1.Equals(r1), "objects should be equal on instance compare");
Assert.AreEqual(true, Equals(r1, r1), "objects should be equal on static compare");
Csla.ApplicationContext.GlobalContext.Clear();
Root r2 = Root.NewRoot();
r2.Data = "xyz";
Assert.AreEqual(false, r1.Equals(r2), "objects should not be equal");
Assert.AreEqual(false, Equals(r1, r2), "objects should not be equal");
Assert.AreEqual(false, r1.Equals(null), "Objects should not be equal");
Assert.AreEqual(false, Equals(r1, null), "Objects should not be equal");
Assert.AreEqual(false, Equals(null, r2), "Objects should not be equal");
}
[TestMethod]
public void ChildEquality()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Root.NewRoot();
root.Children.Add("abc");
root.Children.Add("xyz");
root.Children.Add("123");
Child c1 = root.Children[0];
Child c2 = root.Children[1];
Child c3 = root.Children[2];
root.Children.Remove(c3);
Assert.AreEqual(true, c1.Equals(c1), "objects should be equal");
Assert.AreEqual(true, Equals(c1, c1), "objects should be equal");
Assert.AreEqual(false, c1.Equals(c2), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, c2), "objects should not be equal");
Assert.AreEqual(false, c1.Equals(null), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, null), "objects should not be equal");
Assert.AreEqual(false, Equals(null, c2), "objects should not be equal");
Assert.AreEqual(true, root.Children.Contains(c1), "Collection should contain c1");
Assert.AreEqual(true, root.Children.Contains(c2), "collection should contain c2");
Assert.AreEqual(false, root.Children.Contains(c3), "collection should not contain c3");
Assert.AreEqual(true, root.Children.ContainsDeleted(c3), "Deleted collection should contain c3");
}
[TestMethod]
public void DeletedListTest()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Add("2");
root.Children.Add("3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.ApplyEdit();
Root copy = root.Clone();
var deleted = copy.Children.GetDeletedList();
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
}
[TestMethod]
public void DeletedListTestWithCancel()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Add("2");
root.Children.Add("3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Root copy = root.Clone();
var deleted = copy.Children.GetDeletedList();
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
root.CancelEdit();
deleted = root.Children.GetDeletedList();
Assert.AreEqual(0, deleted.Count);
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void SuppressListChangedEventsDoNotRaiseCollectionChanged()
{
bool changed = false;
var obj = new RootList();
obj.ListChanged += (o, e) =>
{
changed = true;
};
var child = new RootListChild(); // object is marked as child
Assert.IsTrue(obj.RaiseListChangedEvents);
using (obj.SuppressListChangedEvents)
{
Assert.IsFalse(obj.RaiseListChangedEvents);
obj.Add(child);
}
Assert.IsFalse(changed, "Should not raise ListChanged event");
Assert.IsTrue(obj.RaiseListChangedEvents);
Assert.AreEqual(child, obj[0]);
}
[TestCleanup]
public void ClearContextsAfterEachTest() {
Csla.ApplicationContext.GlobalContext.Clear();
}
}
public class FormSimulator
{
private Core.BusinessBase _obj;
public FormSimulator(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged);
this._obj = obj;
}
private void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{}
}
[Serializable()]
public class SerializableListener
{
private Core.BusinessBase _obj;
public SerializableListener(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged);
this._obj = obj;
}
public void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{ }
}
} | 37.635294 | 149 | 0.585495 | [
"MIT"
] | ronnymgm/csla-light | Source/csla.netcore.test/Basic/BasicTests.cs | 15,995 | C# |
#if ShouldMatchApproved
using JetBrains.Annotations;
namespace Shouldly.Configuration
{
public class KnownDoNotLaunchStrategies
{
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool NCrunch = new DoNotLaunchWhenEnvVariableIsPresent("NCRUNCH");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool TeamCity = new DoNotLaunchWhenEnvVariableIsPresent("TeamCity");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool AppVeyor = new DoNotLaunchWhenEnvVariableIsPresent("AppVeyor");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool VSTS = new DoNotLaunchWhenEnvVariableIsPresent("TF_BUILD");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool GitLabCI = new DoNotLaunchWhenEnvVariableIsPresent("GITLAB_CI");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool Jenkins = new DoNotLaunchWhenEnvVariableIsPresent("JENKINS_URL");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool MyGet = new DoNotLaunchWhenEnvVariableIsPresent("BuildRunner");
[UsedImplicitly]
public readonly IShouldNotLaunchDiffTool TravisCI = new DoNotLaunchWhenEnvVariableIsPresent("TRAVIS");
}
}
#endif
| 46.407407 | 114 | 0.766959 | [
"BSD-3-Clause"
] | dennisroche/shouldly | src/Shouldly/Configuration/KnownDoNotLaunchStrategies.cs | 1,253 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Common;
using NPOI.Util;
namespace TestCases.POIFS.Storage
{
/// <summary>
/// Summary description for TestBATBlock
/// </summary>
[TestFixture]
public class TestBATBlock
{
[Test]
public void TestCreateBATBlocks()
{
// Test 0 Length array (basic sanity)
BATBlock[] rvalue = BATBlock.CreateBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(0));
Assert.AreEqual(0, rvalue.Length);
// Test array of Length 1
rvalue = BATBlock.CreateBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(1));
Assert.AreEqual(1, rvalue.Length);
VerifyContents(rvalue, 1);
// Test array of Length 127
rvalue = BATBlock.CreateBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(127));
Assert.AreEqual(1, rvalue.Length);
VerifyContents(rvalue, 127);
// Test array of Length 128
rvalue = BATBlock.CreateBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(128));
Assert.AreEqual(1, rvalue.Length);
VerifyContents(rvalue, 128);
// Test array of Length 129
rvalue = BATBlock.CreateBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(129));
Assert.AreEqual(2, rvalue.Length);
VerifyContents(rvalue, 129);
}
private int[] CreateTestArray(int count)
{
int[] rvalue = new int[count];
for (int j = 0; j < count; j++)
{
rvalue[j] = j;
}
return rvalue;
}
private void VerifyContents(BATBlock[] blocks, int entries)
{
byte[] expected = new byte[512 * blocks.Length];
for (int i = 0; i < expected.Length; i++)
{
expected[i] = (byte)0xFF;
}
int offset = 0;
for (int j = 0; j < entries; j++)
{
expected[offset++] = (byte)j;
expected[offset++] = 0;
expected[offset++] = 0;
expected[offset++] = 0;
}
MemoryStream stream = new MemoryStream(512
* blocks.Length);
for (int j = 0; j < blocks.Length; j++)
{
blocks[j].WriteBlocks(stream);
}
byte[] actual = stream.ToArray();
Assert.AreEqual(expected.Length, actual.Length);
for (int j = 0; j < expected.Length; j++)
{
Assert.AreEqual(expected[j], actual[j]);
}
}
/**
* Test CreateXBATBlocks
*
* @exception IOException
*/
[Test]
public void TestCreateXBATBlocks()
{
// Test 0 Length array (basic sanity)
BATBlock[] rvalue = BATBlock.CreateXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(0), 1);
Assert.AreEqual(0, rvalue.Length);
// Test array of Length 1
rvalue = BATBlock.CreateXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(1), 1);
Assert.AreEqual(1, rvalue.Length);
verifyXBATContents(rvalue, 1, 1);
// Test array of Length 127
rvalue = BATBlock.CreateXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(127), 1);
Assert.AreEqual(1, rvalue.Length);
verifyXBATContents(rvalue, 127, 1);
// Test array of Length 128
rvalue = BATBlock.CreateXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(128), 1);
Assert.AreEqual(2, rvalue.Length);
verifyXBATContents(rvalue, 128, 1);
// Test array of Length 254
rvalue = BATBlock.CreateXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(254), 1);
Assert.AreEqual(2, rvalue.Length);
verifyXBATContents(rvalue, 254, 1);
// Test array of Length 255
rvalue = BATBlock.CreateXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, CreateTestArray(255), 1);
Assert.AreEqual(3, rvalue.Length);
verifyXBATContents(rvalue, 255, 1);
}
private void verifyXBATContents(BATBlock[] blocks, int entries,
int start_block)
{
byte[] expected = new byte[512 * blocks.Length];
for (int i = 0; i < expected.Length; i++)
{
expected[i] = (byte)0xFF;
}
int offset = 0;
for (int j = 0; j < entries; j++)
{
if ((j % 127) == 0)
{
if (j != 0)
{
offset += 4;
}
}
expected[offset++] = (byte)j;
expected[offset++] = 0;
expected[offset++] = 0;
expected[offset++] = 0;
}
for (int j = 0; j < (blocks.Length - 1); j++)
{
offset = 508 + (j * 512);
expected[offset++] = (byte)(start_block + j + 1);
expected[offset++] = 0;
expected[offset++] = 0;
expected[offset++] = 0;
}
offset = (blocks.Length * 512) - 4;
expected[offset++] = unchecked((byte)-2);
expected[offset++] = unchecked((byte)-1);
expected[offset++] = unchecked((byte)-1);
expected[offset++] = unchecked((byte)-1);
MemoryStream stream = new MemoryStream(512
* blocks.Length);
for (int j = 0; j < blocks.Length; j++)
{
blocks[j].WriteBlocks(stream);
}
byte[] actual = stream.ToArray();
Assert.AreEqual(expected.Length, actual.Length);
for (int j = 0; j < expected.Length; j++)
{
Assert.AreEqual(expected[j], actual[j], "offset " + j);
}
}
/**
* Test calculateXBATStorageRequirements
*/
[Test]
public void TestCalculateXBATStorageRequirements()
{
int[] blockCounts =
{
0, 1, 127, 128
};
int[] requirements =
{
0, 1, 1, 2
};
for (int j = 0; j < blockCounts.Length; j++)
{
Assert.AreEqual(
requirements[j],
BATBlock.CalculateXBATStorageRequirements(blockCounts[j]),
"requirement for " + blockCounts[j]);
}
}
/**
* Test entriesPerBlock
*/
[Test]
public void TestEntriesPerBlock()
{
Assert.AreEqual(128, BATBlock.EntriesPerBlock);
}
/**
* Test entriesPerXBATBlock
*/
[Test]
public void TestEntriesPerXBATBlock()
{
Assert.AreEqual(127, BATBlock.EntriesPerXBATBlock);
}
/**
* Test getXBATChainOffset
*/
[Test]
public void TestGetXBATChainOffset()
{
Assert.AreEqual(508, BATBlock.XBATChainOffset);
}
[Test]
public void TestCalculateMaximumSize()
{
// Zero fat blocks isn't technically valid, but it'd be header only
Assert.AreEqual(
512,
BATBlock.CalculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 0)
);
Assert.AreEqual(
4096,
BATBlock.CalculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 0)
);
// A single FAT block can address 128/1024 blocks
Assert.AreEqual(
512 + 512 * 128,
BATBlock.CalculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1)
);
Assert.AreEqual(
4096 + 4096 * 1024,
BATBlock.CalculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 1)
);
Assert.AreEqual(
512 + 4 * 512 * 128,
BATBlock.CalculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 4)
);
Assert.AreEqual(
4096 + 4 * 4096 * 1024,
BATBlock.CalculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 4)
);
// One XBAT block holds 127/1023 individual BAT blocks, so they can address
// a fairly hefty amount of space themselves
// However, the BATs continue as before
Assert.AreEqual(
512 + 109 * 512 * 128,
BATBlock.CalculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 109)
);
Assert.AreEqual(
4096 + 109 * 4096 * 1024,
BATBlock.CalculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 109)
);
Assert.AreEqual(
512 + 110 * 512 * 128,
BATBlock.CalculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 110)
);
Assert.AreEqual(
4096 + 110 * 4096 * 1024,
BATBlock.CalculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 110)
);
Assert.AreEqual(
512 + 112 * 512 * 128,
BATBlock.CalculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 112)
);
Assert.AreEqual(
4096 + 112 * 4096 * 1024,
BATBlock.CalculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 112)
);
}
[Test]
public void TestGetBATBlockAndIndex()
{
HeaderBlock header = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
List<BATBlock> blocks = new List<BATBlock>();
int offset;
// First, try a one BAT block file
header.BATCount = (1);
blocks.Add(
BATBlock.CreateBATBlock(header.BigBlockSize, new ByteBuffer(512, 512))
);
offset = 0;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1;
Assert.AreEqual(1, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 127;
Assert.AreEqual(127, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
// Now go for one with multiple BAT blocks
header.BATCount = (2);
blocks.Add(
BATBlock.CreateBATBlock(header.BigBlockSize, new ByteBuffer(512, 512))
);
offset = 0;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 127;
Assert.AreEqual(127, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 128;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(1, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 129;
Assert.AreEqual(1, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(1, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
// The XBAT count makes no difference, as we flatten in memory
header.BATCount = (1);
header.XBATCount = (1);
offset = 0;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 126;
Assert.AreEqual(126, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 127;
Assert.AreEqual(127, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 128;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(1, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 129;
Assert.AreEqual(1, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(1, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
// Check with the bigger block size too
header = new HeaderBlock(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS);
offset = 0;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1022;
Assert.AreEqual(1022, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1023;
Assert.AreEqual(1023, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1024;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(1, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
// Biggr block size, back to real BATs
header.BATCount = (2);
offset = 0;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1022;
Assert.AreEqual(1022, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1023;
Assert.AreEqual(1023, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(0, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
offset = 1024;
Assert.AreEqual(0, BATBlock.GetBATBlockAndIndex(offset, header, blocks).Index);
Assert.AreEqual(1, blocks.IndexOf(BATBlock.GetBATBlockAndIndex(offset, header, blocks).Block));
}
}
}
| 40.269406 | 129 | 0.552047 | [
"Apache-2.0"
] | sunshinele/npoi | testcases/main/POIFS/Storage/TestBATBlock.cs | 17,640 | C# |
using Eric.Morrison.Harmony.Chords;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Eric.Morrison.Harmony
{
public partial class Arpeggiator
{
class StateSnapshot : IEquatable<StateSnapshot>
{
ArpeggiationContext ArpeggiationContext { get; set; }
Chord StartingChord { get; set; }
DirectionEnum StartingDirection { get; set; }
Note StartingNote { get; set; }
List<Note> NoteHistory { get; set; } = new List<Note>();
public StateSnapshot(Arpeggiator arp)
{
this.ArpeggiationContext = arp.CurrentContext;
this.StartingChord = arp.CurrentChord;
this.StartingNote = arp.CurrentNote;
this.StartingDirection = arp.Direction;
this.NoteHistory = new List<Note>(arp.NoteHistory);
}
public static implicit operator StateSnapshot(Arpeggiator arp)
{
StateSnapshot temp = new StateSnapshot(arp);
return temp;
}
public bool Equals(Arpeggiator arp)
{
var result = false;
bool success = true;
if (success)
{
success = this.ArpeggiationContext.Equals(arp.CurrentContext);
if (!success) { new object(); }
}
if (success)
{
success = this.StartingChord.Equals(arp.CurrentChord);
if (!success) { new object(); }
}
if (success)
{
success = this.StartingNote.Equals(arp.CurrentNote);
if (!success) { new object(); }
}
if (success)
{
success = this.StartingDirection == arp.Direction;
if (!success) { new object(); }
}
if (success)
{
if (this.NoteHistory.Count != arp.NoteHistory.Count)
success = false;
else
{
var count = this.NoteHistory.Count;
for (int i = 0; i < count; ++i)
{
if (this.NoteHistory[i] != arp.NoteHistory[i])
{
success = false;
break;
}
}
if (!success) { new object(); }
}
}
if (success)
{
result = true;
}
#if DEBUG
#warning FIXME: debug logic start.
else
{
var noteRange = new FiveStringBassRange(FiveStringBassPositionEnum.FifthPosition);
var key = KeySignature.GMajor;
var chord = new Chord(
ChordFormulaFactory.Create(NoteName.A,
ChordType.Minor7th,
key),
noteRange);
if (chord.ToString() == this.StartingChord.ToString()
&& chord.ToString() == arp.CurrentChord.ToString())
{
new object();
}
}
#warning FIXME: debug logic end.
#endif
return result;
}
public bool Equals(StateSnapshot other)
{
throw new NotSupportedException();
return this.Equals(other);
}
public override int GetHashCode()
{
var result = this.ArpeggiationContext.GetHashCode()
^ this.StartingChord.GetHashCode()
^ this.StartingDirection.GetHashCode()
^ this.StartingNote.GetHashCode();
return result;
}
public override bool Equals(object obj)
{
var result = false;
if (obj is StateSnapshot)
result = this.Equals(obj as Note);
return result;
}
public static bool operator ==(StateSnapshot snapshot, Arpeggiator arp)
{
var result = snapshot.Equals(arp);
return result;
}
public static bool operator !=(StateSnapshot snapshot, Arpeggiator arp)
{
var result = !snapshot.Equals(arp);
return result;
}
public override string ToString()
{
return $"{base.ToString()}: StartingChord={this.StartingChord}, StartingNote={this.StartingNote}, StartingDirection={this.StartingDirection}";
}
}//class
}//class
}//ns
| 23.763514 | 146 | 0.638328 | [
"MIT"
] | emorrison1962/HarmonyHelper | HarmonyHelper/HarmonyHelper/Arpeggiator/Arpeggiator_Snapshot.cs | 3,519 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace todo_list_api.Models
{
public partial class List
{
public List()
{
Tasks = new HashSet<Tasks>();
DateCreate = DateTime.Now;
}
public int Idlist { get; set; }
public string DescriptionList { get; set; }
public DateTime? DateCreate { get; private set; }
public DateTime? DateUpdate { get; set; }
public virtual ICollection<Tasks> Tasks { get; set; }
}
}
| 22.208333 | 61 | 0.594747 | [
"MIT"
] | werikorus/todo-list-api | todo-list-api/Models/List.cs | 535 | 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\MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type DepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequestBuilder.
/// </summary>
public partial class DepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequestBuilder : BaseActionMethodRequestBuilder<IDepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequest>, IDepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="DepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public DepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IDepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new DepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequest(functionUrl, this.Client, options);
return request;
}
}
}
| 47.531915 | 267 | 0.662489 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/DepOnboardingSettingSyncWithAppleDeviceEnrollmentProgramRequestBuilder.cs | 2,234 | C# |
using System;
using System.Collections.Generic;
using SimpleCardGames.Data.Card;
namespace SimpleCardGames.Battle.UI.Card
{
//------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Pile of cards. Add or Remove cards and be notified when changes happen.
/// </summary>
public abstract class UiCardPile : UiListener, IUiCardPile, IRestartGame
{
//--------------------------------------------------------------------------------------------------------------
#region Unitycallbacks
protected virtual void Awake()
{
//initialize register
Cards = new List<IUiCard>();
Restart();
}
#endregion
//--------------------------------------------------------------------------------------------------------------
#region Properties
/// <summary>
/// List with all cards.
/// </summary>
public List<IUiCard> Cards { get; private set; }
public Action<IUiCard[]> OnPileChanged { get; set; } = card => { };
#endregion
//--------------------------------------------------------------------------------------------------------------
#region Operations
/// <summary>
/// Add a card to the pile.
/// </summary>
/// <param name="card"></param>
public virtual void AddCard(IUiCard card)
{
if (card == null)
throw new ArgumentNullException("Null is not a valid argument.");
Cards.Add(card);
card.transform.SetParent(transform);
card.Initialize();
NotifyPileChange();
card.Draw();
}
/// <summary>
/// Remove a card from the pile.
/// </summary>
/// <param name="card"></param>
public virtual void RemoveCard(IUiCard card)
{
if (card == null)
throw new ArgumentNullException("Null is not a valid argument.");
Cards.Remove(card);
NotifyPileChange();
}
/// <summary>
/// Clear all the pile.
/// </summary>
[Button]
public virtual void Restart()
{
var childCards = GetComponentsInChildren<IUiCard>();
foreach (var uiCardHand in childCards)
CardFactory.Instance.ReleasePooledObject(uiCardHand.gameObject);
Cards.Clear();
}
/// <summary>
/// Notify all listeners of this pile that some change has been made.
/// </summary>
[Button]
public void NotifyPileChange() => OnPileChanged?.Invoke(Cards.ToArray());
void IRestartGame.OnRestart() => Restart();
#endregion
//--------------------------------------------------------------------------------------------------------------
}
} | 29.60396 | 120 | 0.42408 | [
"MIT"
] | led0warlpl/SimpleCard | Assets/Scripts/Battle/UI/UiCard/UiCardPile/UiCardPile.cs | 2,992 | C# |
using PizzaBox.Domain.Models;
using Xunit;
namespace PizzaBox.Testing.Tests
{
public class PizzaTests
{
[Fact]
public void Test_CustomePizza_Fact()
{
// arrange
var sut = new CustomPizza(){
Name = "Custom Pizza"
};
var expected = "Custom Pizza";
// act
var actual = sut.Name;
// assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("Custom Pizza")]
public void Test_CustomPizza_Theory(string expected)
{
// arrange
var sut = new CustomPizza(){
Name = "Custom Pizza"
};
// act
var actual = sut.Name;
// assert
Assert.Equal(expected, actual);
}
[Fact]
public void Test_PepperoniPizza_Fact()
{
// arrange
var sut = new PepperoniPizza(){
Name = "Pepperoni Pizza"
};
var expected = "Pepperoni Pizza";
// act
var actual = sut.Name;
// assert
Assert.Equal(expected, actual);
}
[Fact]
public void Test_VeggiePizza_Fact()
{
// arrange
var sut = new VeggiePizza(){
Name = "Veggie Pizza"
};
var expected = "Veggie Pizza";
// act
var actual = sut.Name;
// assert
Assert.Equal(expected, actual);
}
[Fact]
public void Test_CheesePizza_Fact()
{
// arrange
var sut = new CheesePizza(){
Name = "Cheese Pizza"
};
var expected = "Cheese Pizza";
// act
var actual = sut.Name;
// assert
Assert.Equal(expected, actual);
}
}
} | 18.390805 | 56 | 0.5375 | [
"MIT"
] | 03012021-dotnet-uta/ChelseyGrice_p0 | PizzaBox.Testing/Tests/PizzaTests.cs | 1,600 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrearHuellas : MonoBehaviour
{
public GameObject prefabHuella;
public GameObject huella;
public GameObject huellaAnt;
// Start is called before the first frame update
void Start()
{
StartCoroutine(creaHuella());
}
// Update is called once per frame
void Update()
{
}
IEnumerator creaHuella()
{
yield return new WaitForSeconds(0.5f);
//INSTANCIAR PREFAB
huella = Instantiate(prefabHuella, new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z), this.transform.rotation);
if (huellaAnt != null)
{
huellaAnt.GetComponent<ScriptHuella>().sigHuella = huella;
}
huellaAnt = huella;
//CODE
StartCoroutine(creaHuella());
}
}
| 21.255814 | 162 | 0.640044 | [
"Apache-2.0"
] | VRSDevs/XO-Rivals | XO Rivals/Assets/Scripts/Fantasmas/CrearHuellas.cs | 914 | C# |
using System.Linq;
using Content.Server.Warps;
using Content.Shared.Administration;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.Enums;
using Robust.Shared.Map;
using Robust.Shared.Physics;
namespace Content.Server.Administration.Commands
{
[AdminCommand(AdminFlags.Admin)]
public sealed class WarpCommand : IConsoleCommand
{
public string Command => "warp";
public string Description => "Teleports you to predefined areas on the map.";
public string Help =>
"warp <location>\nLocations you can teleport to are predefined by the map. " +
"You can specify '?' as location to get a list of valid locations.";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
if (player == null)
{
shell.WriteLine("Only players can use this command");
return;
}
if (args.Length != 1)
{
shell.WriteLine("Expected a single argument.");
return;
}
var entMan = IoCManager.Resolve<IEntityManager>();
var location = args[0];
if (location == "?")
{
var locations = string.Join(", ", GetWarpPointNames(entMan));
shell.WriteLine(locations);
}
else
{
if (player.Status != SessionStatus.InGame || player.AttachedEntity is not {Valid: true} playerEntity)
{
shell.WriteLine("You are not in-game!");
return;
}
var mapManager = IoCManager.Resolve<IMapManager>();
var currentMap = entMan.GetComponent<TransformComponent>(playerEntity).MapID;
var currentGrid = entMan.GetComponent<TransformComponent>(playerEntity).GridUid;
var found = entMan.EntityQuery<WarpPointComponent>(true)
.Where(p => p.Location == location)
.Select(p => entMan.GetComponent<TransformComponent>(p.Owner).Coordinates)
.OrderBy(p => p, Comparer<EntityCoordinates>.Create((a, b) =>
{
// Sort so that warp points on the same grid/map are first.
// So if you have two maps loaded with the same warp points,
// it will prefer the warp points on the map you're currently on.
var aGrid = a.GetGridUid(entMan);
var bGrid = b.GetGridUid(entMan);
if (aGrid == bGrid)
{
return 0;
}
if (aGrid == currentGrid)
{
return -1;
}
if (bGrid == currentGrid)
{
return 1;
}
var mapA = a.GetMapId(entMan);
var mapB = a.GetMapId(entMan);
if (mapA == mapB)
{
return 0;
}
if (mapA == currentMap)
{
return -1;
}
if (mapB == currentMap)
{
return 1;
}
return 0;
}))
.FirstOrDefault();
var entityUid = found.GetGridUid(entMan);
if (entityUid != EntityUid.Invalid)
{
entMan.GetComponent<TransformComponent>(playerEntity).Coordinates = found;
if (entMan.TryGetComponent(playerEntity, out IPhysBody? physics))
{
physics.LinearVelocity = Vector2.Zero;
}
}
else
{
shell.WriteLine("That location does not exist!");
}
}
}
private static IEnumerable<string> GetWarpPointNames(IEntityManager entMan)
{
return entMan.EntityQuery<WarpPointComponent>(true)
.Select(p => p.Location)
.Where(p => p != null)
.OrderBy(p => p)
.Distinct()!;
}
public CompletionResult GetCompletion(IConsoleShell shell, string[] args)
{
if (args.Length == 1)
{
var ent = IoCManager.Resolve<IEntityManager>();
var options = new[] { "?" }.Concat(GetWarpPointNames(ent));
return CompletionResult.FromHintOptions(options, "<warp point | ?>");
}
return CompletionResult.Empty;
}
}
}
| 35.111111 | 117 | 0.462421 | [
"MIT"
] | EmoGarbage404/space-station-14 | Content.Server/Administration/Commands/WarpCommand.cs | 5,056 | C# |
using SanAndreasUnity.Importing.Vehicles;
using SanAndreasUnity.Utilities;
using System.Linq;
using UnityEngine;
using VConsts = SanAndreasUnity.Behaviours.Vehicles.VehiclePhysicsConstants;
namespace SanAndreasUnity.Behaviours.Vehicles
{
[RequireComponent(typeof(Rigidbody))]
public partial class Vehicle
{
private Rigidbody _rigidBody;
[Range(-1, 1)]
public float Accelerator;
[Range(-1, 1)]
public float Steering;
[Range(0, 1)]
public float Braking = 1f;
public Vector3 Velocity { get { return _rigidBody.velocity; } }
public float AverageWheelHeight { get { return _wheels.Count == 0 ? transform.position.y : _wheels.Average(x => x.Child.position.y); } }
public Handling.Car HandlingData { get; private set; }
private void InitializePhysics()
{
//Debug.Log("aaa");
_geometryParts.AttachCollisionModel(transform, true);
//Debug.Log("bbb");
_rigidBody = gameObject.GetComponent<Rigidbody>();
HandlingData = Handling.Get<Handling.Car>(Definition.HandlingName);
VConsts.Changed += UpdateValues;
var vals = VConsts.Instance;
foreach (var wheel in _wheels)
{
var front = (wheel.Alignment & WheelAlignment.Front) == WheelAlignment.Front;
//Debug.LogFormat("Handling is Null?: {0}", HandlingData == null);
/*b = HandlingData == null;
Debug.Log(b);
Debug.Break();*/
wheel.Parent.position -= Vector3.up * HandlingData.SuspensionLowerLimit;
var scale = front ? Definition.WheelScaleFront : Definition.WheelScaleRear;
var mf = wheel.Child.GetComponent<MeshFilter>();
if (mf != null)
{
var size = mf.sharedMesh.bounds.size.y;
wheel.Child.localScale = Vector3.one * scale / size;
}
wheel.Collider = wheel.Parent.gameObject.AddComponent<WheelCollider>();
wheel.Collider.radius = scale * .5f;
wheel.Collider.suspensionDistance = HandlingData.SuspensionUpperLimit - HandlingData.SuspensionLowerLimit;
}
UpdateValues(vals);
}
private void UpdateValues(VConsts vals)
{
_rigidBody.drag = HandlingData.Drag * vals.DragScale;
_rigidBody.mass = HandlingData.Mass * vals.MassScale;
_rigidBody.centerOfMass = HandlingData.CentreOfMass;
foreach (var wheel in _wheels)
{
var spring = wheel.Collider.suspensionSpring;
spring.damper = HandlingData.SuspensionDampingLevel * vals.SuspensionDampingScale;
spring.spring = HandlingData.SuspensionForceLevel * vals.SuspensionForceScale;
spring.targetPosition = 0.5f;
wheel.Collider.suspensionSpring = spring;
var friction = wheel.Collider.sidewaysFriction;
friction.extremumSlip = vals.SideFrictionExtremumSlip;
friction.extremumValue = vals.SideFrictionExtremumValue;
friction.asymptoteSlip = vals.SideFrictionAsymptoteSlip;
friction.asymptoteValue = vals.SideFrictionAsymptoteValue;
friction.stiffness = 1f;
wheel.Collider.sidewaysFriction = friction;
friction = wheel.Collider.forwardFriction;
friction.extremumSlip = vals.ForwardFrictionExtremumSlip;
friction.extremumValue = vals.ForwardFrictionExtremumValue;
friction.asymptoteSlip = vals.ForwardFrictionAsymptoteSlip;
friction.asymptoteValue = vals.ForwardFrictionAsymptoteValue;
friction.stiffness = 1f;
wheel.Collider.forwardFriction = friction;
}
}
private float DriveBias(Wheel wheel)
{
switch (HandlingData.TransmissionDriveType)
{
case DriveType.Forward:
return wheel.IsFront ? 1f : 0f;
case DriveType.Rear:
return wheel.IsRear ? 1f : 0f;
default:
return 1f;
}
}
private bool ShouldSteer(Wheel wheel)
{
// TODO: look at flags
return wheel.IsFront;
}
private float BrakeBias(Wheel wheel)
{
return wheel.IsFront
? 1f - HandlingData.BrakeBias : wheel.IsRear
? HandlingData.BrakeBias : .5f;
}
private void PhysicsFixedUpdate()
{
//Debug.LogFormat("{0}?: {1}", _rigidBody == null, gameObject.GetGameObjectPath());
//Debug.Break();
var groundRay = new Ray(transform.position + Vector3.up, -Vector3.up);
//if (_rigidBody != null) // Must review: Why this is now null?
try
{
if (!Physics.SphereCast(groundRay, 0.25f, transform.position.y + 256f, (-1) ^ LayerMask))
{
_rigidBody.velocity = Vector3.zero;
_rigidBody.angularVelocity = Vector3.zero;
_rigidBody.useGravity = false;
}
else
{
_rigidBody.useGravity = true;
}
} catch { }
var vals = VConsts.Instance;
foreach (var wheel in _wheels)
{
if (ShouldSteer(wheel))
{
/*if (Steering != 0)
{
Debug.Log(HandlingData.SteeringLock);
Debug.Break();
}*/
wheel.Collider.steerAngle = HandlingData.SteeringLock * Steering;
}
wheel.Collider.motorTorque =
Accelerator * HandlingData.TransmissionEngineAccel
* vals.AccelerationScale * DriveBias(wheel);
wheel.Collider.brakeTorque =
Braking * HandlingData.BrakeDecel
* vals.BreakingScale * BrakeBias(wheel);
if (wheel.Complement != null) wheel.UpdateTravel();
}
foreach (var wheel in _wheels.Where(x => x.Complement != null))
{
if (wheel.Travel == wheel.Complement.Travel) continue;
if (!wheel.Collider.isGrounded) continue;
var force = (wheel.Complement.Travel - wheel.Travel) * vals.AntiRollScale;
_rigidBody.AddForceAtPosition(wheel.Parent.transform.up * force, wheel.Parent.position);
}
}
}
} | 35.780105 | 144 | 0.554726 | [
"MIT"
] | Bigbossbro08/SanAndreasUnity | Assets/Scripts/Behaviours/Vehicles/Vehicle_Physics.cs | 6,836 | C# |
namespace IxMilia.Iges.Entities
{
using System;
using System.Collections.Generic;
public class IgesNameProperty : IgesProperty
{
public String Name { get; private set; }
public IgesNameProperty():base()
{
this.FormNumber = 15;
}
internal override int ReadParameters(List<string> parameters, IgesReaderBinder binder)
{
var nextIndex = base.ReadParameters(parameters, binder);
this.Name = this.String(parameters, nextIndex);
return nextIndex + this.PropertyCount;
}
internal override void WriteParameters(List<object> parameters, IgesWriterBinder binder)
{
this.PropertyCount = 1;
base.WriteParameters(parameters, binder);
parameters.Add(this.Name);
}
}
} | 28.1 | 96 | 0.615658 | [
"Apache-2.0"
] | RSchwarzwald-Hexagon/iges | src/IxMilia.Iges/Entities/IgesNameProperty.cs | 845 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Contains the code for determining C# accessibility rules.
/// </summary>
internal static class AccessCheck
{
/// <summary>
/// Checks if 'symbol' is accessible from within assembly 'within'.
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
AssemblySymbol within,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
bool failedThroughTypeCheck;
return IsSymbolAccessibleCore(symbol, within, null, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteDiagnostics);
}
/// <summary>
/// Checks if 'symbol' is accessible from within type 'within', with
/// an optional qualifier of type "throughTypeOpt".
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
NamedTypeSymbol within,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
TypeSymbol throughTypeOpt = null)
{
bool failedThroughTypeCheck;
return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteDiagnostics);
}
/// <summary>
/// Checks if 'symbol' is accessible from within type 'within', with
/// an qualifier of type "throughTypeOpt". Sets "failedThroughTypeCheck" to true
/// if it failed the "through type" check.
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
NamedTypeSymbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
ConsList<Symbol> basesBeingResolved = null)
{
return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteDiagnostics, basesBeingResolved);
}
/// <summary>
/// Checks if 'symbol' is accessible from within 'within', which must be a NamedTypeSymbol
/// or an AssemblySymbol.
///
/// Note that NamedTypeSymbol, if available, is the type that is associated with the binder
/// that found the 'symbol', not the inner-most type that contains the access to the
/// 'symbol'.
///
/// If 'symbol' is accessed off of an expression then 'throughTypeOpt' is the type of that
/// expression. This is needed to properly do protected access checks. Sets
/// "failedThroughTypeCheck" to true if this protected check failed.
///
/// NOTE(cyrusn): I expect this function to be called a lot. As such, i do not do any memory
/// allocations in the function itself (including not making any iterators). This does mean
/// that certain helper functions that we'd like to call are inlined in this method to
/// prevent the overhead of returning collections or enumerators.
/// </summary>
private static bool IsSymbolAccessibleCore(
Symbol symbol,
Symbol within, // must be assembly or named type symbol
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert((object)symbol != null);
Debug.Assert((object)within != null);
Debug.Assert(within.IsDefinition);
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
failedThroughTypeCheck = false;
switch (symbol.Kind)
{
case SymbolKind.ArrayType:
return IsSymbolAccessibleCore(((ArrayTypeSymbol)symbol).ElementType, within, null, out failedThroughTypeCheck, compilation, ref useSiteDiagnostics, basesBeingResolved);
case SymbolKind.PointerType:
return IsSymbolAccessibleCore(((PointerTypeSymbol)symbol).PointedAtType, within, null, out failedThroughTypeCheck, compilation, ref useSiteDiagnostics, basesBeingResolved);
case SymbolKind.NamedType:
return IsNamedTypeAccessible((NamedTypeSymbol)symbol, within, ref useSiteDiagnostics, basesBeingResolved);
case SymbolKind.ErrorType:
// Always assume that error types are accessible.
return true;
case SymbolKind.TypeParameter:
case SymbolKind.Parameter:
case SymbolKind.Local:
case SymbolKind.Label:
case SymbolKind.Namespace:
case SymbolKind.DynamicType:
case SymbolKind.Assembly:
case SymbolKind.NetModule:
case SymbolKind.RangeVariable:
// These types of symbols are always accessible (if visible).
return true;
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
case SymbolKind.Field:
if (symbol.IsStatic)
{
// static members aren't accessed "through" an "instance" of any type. So we
// null out the "through" instance here. This ensures that we'll understand
// accessing protected statics properly.
throughTypeOpt = null;
}
return IsMemberAccessible(symbol.ContainingType, symbol.DeclaredAccessibility, within, throughTypeOpt, out failedThroughTypeCheck, compilation, ref useSiteDiagnostics);
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
// Is the named type "type accessible from within "within", which must be a named type or an
// assembly.
private static bool IsNamedTypeAccessible(NamedTypeSymbol type, Symbol within, ref HashSet<DiagnosticInfo> useSiteDiagnostics, ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)type != null);
var compilation = within.DeclaringCompilation;
bool unused;
if (!type.IsDefinition)
{
// All type argument must be accessible.
var typeArgs = type.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
foreach (var typeArg in typeArgs)
{
// type parameters are always accessible, so don't check those (so common it's
// worth optimizing this).
if (typeArg.Kind != SymbolKind.TypeParameter && !IsSymbolAccessibleCore(typeArg, within, null, out unused, compilation, ref useSiteDiagnostics, basesBeingResolved))
{
return false;
}
}
}
var containingType = type.ContainingType;
return (object)containingType == null
? IsNonNestedTypeAccessible(type.ContainingAssembly, type.DeclaredAccessibility, within)
: IsMemberAccessible(containingType, type.DeclaredAccessibility, within, null, out unused, compilation, ref useSiteDiagnostics, basesBeingResolved);
}
// Is a top-level type with accessibility "declaredAccessibility" inside assembly "assembly"
// accessible from "within", which must be a named type of an assembly.
private static bool IsNonNestedTypeAccessible(
AssemblySymbol assembly,
Accessibility declaredAccessibility,
Symbol within)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)assembly != null);
switch (declaredAccessibility)
{
case Accessibility.NotApplicable:
case Accessibility.Public:
// Public symbols are always accessible from any context
return true;
case Accessibility.Private:
case Accessibility.Protected:
case Accessibility.ProtectedAndInternal:
// Shouldn't happen except in error cases.
return false;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal:
// within is typically a type
var withinType = within as NamedTypeSymbol;
var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;
// An internal type is accessible if we're in the same assembly or we have
// friend access to the assembly it was defined in.
return (object)withinAssembly == (object)assembly || withinAssembly.HasInternalAccessTo(assembly);
default:
throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
}
}
// Is a member with declared accessibility "declaredAccessibility" accessible from within
// "within", which must be a named type or an assembly.
private static bool IsMemberAccessible(
NamedTypeSymbol containingType, // the symbol's containing type
Accessibility declaredAccessibility,
Symbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)containingType != null);
failedThroughTypeCheck = false;
if (containingType.IsTupleType)
{
containingType = containingType.TupleUnderlyingType;
}
// easy case - members of containing type are accessible.
if ((object)containingType == (object)within)
{
return true;
}
// A nested symbol is only accessible to us if its container is accessible as well.
if (!IsNamedTypeAccessible(containingType, within, ref useSiteDiagnostics, basesBeingResolved))
{
return false;
}
// public in accessible type is accessible
if (declaredAccessibility == Accessibility.Public)
{
return true;
}
return IsNonPublicMemberAccessible(
containingType,
declaredAccessibility,
within,
throughTypeOpt,
out failedThroughTypeCheck,
compilation,
ref useSiteDiagnostics,
basesBeingResolved);
}
private static bool IsNonPublicMemberAccessible(
NamedTypeSymbol containingType, // the symbol's containing type
Accessibility declaredAccessibility,
Symbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
ConsList<Symbol> basesBeingResolved = null)
{
failedThroughTypeCheck = false;
var originalContainingType = containingType.OriginalDefinition;
var withinType = within as NamedTypeSymbol;
var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;
switch (declaredAccessibility)
{
case Accessibility.NotApplicable:
// TODO(cyrusn): Is this the right thing to do here? Should the caller ever be
// asking about the accessibility of a symbol that has "NotApplicable" as its
// value? For now, I'm preserving the behavior of the existing code. But perhaps
// we should fail here and require the caller to not do this?
return true;
case Accessibility.Private:
// All expressions in the current submission (top-level or nested in a method or
// type) can access previous submission's private top-level members. Previous
// submissions are treated like outer classes for the current submission - the
// inner class can access private members of the outer class.
if (containingType.TypeKind == TypeKind.Submission)
{
return true;
}
// private members never accessible from outside a type.
return (object)withinType != null && IsPrivateSymbolAccessible(withinType, originalContainingType);
case Accessibility.Internal:
// An internal type is accessible if we're in the same assembly or we have
// friend access to the assembly it was defined in.
return withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly);
case Accessibility.ProtectedAndInternal:
if (!withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly))
{
// We require internal access. If we don't have it, then this symbol is
// definitely not accessible to us.
return false;
}
// We had internal access. Also have to make sure we have protected access.
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteDiagnostics, basesBeingResolved);
case Accessibility.ProtectedOrInternal:
if (withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly))
{
// If we have internal access to this symbol, then that's sufficient. no
// need to do the complicated protected case.
return true;
}
// We don't have internal access. But if we have protected access then that's
// sufficient.
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteDiagnostics, basesBeingResolved);
case Accessibility.Protected:
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteDiagnostics, basesBeingResolved);
default:
throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
}
}
// Is a protected symbol inside "originalContainingType" accessible from within "within",
// which much be a named type or an assembly.
private static bool IsProtectedSymbolAccessible(
NamedTypeSymbol withinType,
TypeSymbol throughTypeOpt,
NamedTypeSymbol originalContainingType,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
ConsList<Symbol> basesBeingResolved = null)
{
failedThroughTypeCheck = false;
// It is not an error to define protected member in a sealed Script class, it's just a
// warning. The member behaves like a private one - it is visible in all subsequent
// submissions.
if (originalContainingType.TypeKind == TypeKind.Submission)
{
return true;
}
if ((object)withinType == null)
{
// If we're not within a type, we can't access a protected symbol
return false;
}
// A protected symbol is accessible if we're (optionally nested) inside the type that it
// was defined in.
// NOTE(ericli): It is helpful to think about 'protected' as *increasing* the
// accessibility domain of a private member, rather than *decreasing* that of a public
// member. Members are naturally private; the protected, internal and public access
// modifiers all increase the accessibility domain. Since private members are accessible
// to nested types, so are protected members.
// NOTE(cyrusn): We do this check up front as it is very fast and easy to do.
if (IsNestedWithinOriginalContainingType(withinType, originalContainingType))
{
return true;
}
// Protected is really confusing. Check out 3.5.3 of the language spec "protected access
// for instance members" to see how it works. I actually got the code for this from
// LangCompiler::CheckAccessCore
{
var current = withinType.OriginalDefinition;
var originalThroughTypeOpt = (object)throughTypeOpt == null ? null : throughTypeOpt.OriginalDefinition as TypeSymbol;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (current.InheritsFromIgnoringConstruction(originalContainingType, compilation, ref useSiteDiagnostics, basesBeingResolved))
{
// NOTE(cyrusn): We're continually walking up the 'throughType's inheritance
// chain. We could compute it up front and cache it in a set. However, i
// don't want to allocate memory in this function. Also, in practice
// inheritance chains should be very short. As such, it might actually be
// slower to create and check inside the set versus just walking the
// inheritance chain.
if ((object)originalThroughTypeOpt == null ||
originalThroughTypeOpt.InheritsFromIgnoringConstruction(current, compilation, ref useSiteDiagnostics))
{
return true;
}
else
{
failedThroughTypeCheck = true;
}
}
// NOTE(cyrusn): The container of an original type is always original.
current = current.ContainingType;
}
}
return false;
}
// Is a private symbol access
private static bool IsPrivateSymbolAccessible(
Symbol within,
NamedTypeSymbol originalContainingType)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
var withinType = within as NamedTypeSymbol;
if ((object)withinType == null)
{
// If we're not within a type, we can't access a private symbol
return false;
}
// A private symbol is accessible if we're (optionally nested) inside the type that it
// was defined in.
return IsNestedWithinOriginalContainingType(withinType, originalContainingType);
}
// Is the type "withinType" nested within the original type "originalContainingType".
private static bool IsNestedWithinOriginalContainingType(
NamedTypeSymbol withinType,
NamedTypeSymbol originalContainingType)
{
Debug.Assert((object)withinType != null);
Debug.Assert((object)originalContainingType != null);
// Walk up my parent chain and see if I eventually hit the owner. If so then I'm a
// nested type of that owner and I'm allowed access to everything inside of it.
var current = withinType.OriginalDefinition;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (current.Equals(originalContainingType))
{
return true;
}
// NOTE(cyrusn): The container of an 'original' type is always original.
current = current.ContainingType;
}
return false;
}
// Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
// only with original types.
private static bool InheritsFromIgnoringConstruction(
this TypeSymbol type,
NamedTypeSymbol baseType,
CSharpCompilation compilation,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert(type.IsDefinition);
Debug.Assert(baseType.IsDefinition);
PooledHashSet<NamedTypeSymbol> visited = null;
var current = type;
bool result = false;
while ((object)current != null)
{
if (current.Equals(baseType))
{
result = true;
break;
}
// NOTE(cyrusn): The base type of an 'original' type may not be 'original'. i.e.
// "class Foo : IBar<int>". We must map it back to the 'original' when as we walk up
// the base type hierarchy.
var next = current.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, compilation, ref visited);
if ((object)next == null)
{
current = null;
}
else
{
current = (TypeSymbol)next.OriginalDefinition;
current.AddUseSiteDiagnostics(ref useSiteDiagnostics);
}
}
visited?.Free();
return result;
}
// Does the assembly has internal accessibility to "toAssembly"?
internal static bool HasInternalAccessTo(this AssemblySymbol assembly, AssemblySymbol toAssembly)
{
if (Equals(assembly, toAssembly))
{
return true;
}
if (assembly.AreInternalsVisibleToThisAssembly(toAssembly))
{
return true;
}
// all interactive assemblies are friends of each other:
if (assembly.IsInteractive && toAssembly.IsInteractive)
{
return true;
}
return false;
}
internal static ErrorCode GetProtectedMemberInSealedTypeError(NamedTypeSymbol containingType)
{
return containingType.TypeKind == TypeKind.Struct ? ErrorCode.ERR_ProtectedInStruct : ErrorCode.WRN_ProtectedInSealed;
}
}
}
| 45.630682 | 192 | 0.591251 | [
"MIT"
] | 1Crazymoney/cs2cpp | CSharpSource/Binder/Semantics/AccessCheck.cs | 24,095 | 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("MongoDB.UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoDB.UI")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4b886f1f-e0ed-43ce-bb80-aff82231bcff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.513514 | 84 | 0.745677 | [
"MIT"
] | arielcortez/WeeklyChallenge | WCH-28/MongoDBChallenge/MongoDB.UI/Properties/AssemblyInfo.cs | 1,391 | C# |
using Account.ViewModels;
using CommonMessages.MqCmds;
using Commons.DiIoc;
using Commons.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Account.Application.Services
{
public interface IAccountService : IDependency
{
public Task<WrappedResponse<AccountResponseVm>> Login(AccountInfoVm accountInfo);
Task<WrappedResponse<AccountDetailVm>> GetSelfAccount(long id);
Task<WrappedResponse<OtherAccountDetailVm>> GetOtherAccount(long id, long otherId);
Task<WrappedResponse<GetAccountBaseInfoMqResponse>> GetAccountBaseInfo(long id);
void FinishRegisterReward(long id);
Task<WrappedResponse<GetIdByPlatformMqResponse>> GetIdByPlatform(string platformAccount, int type);
}
}
| 37.227273 | 108 | 0.759463 | [
"MIT"
] | swpuzhang/CleanGameArchitecture | Services/Account/Application/Services/IAccountService.cs | 821 | 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("kRPC.Programs.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("kRPC.Programs.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("bb7b2361-2ab4-4264-8896-9d060c18955a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.108108 | 85 | 0.72633 | [
"MIT"
] | FiiZzioN/KSP-Tourist-Auto-Mission | kRPC.Programs/kRPC.Programs.Tests/Properties/AssemblyInfo.cs | 1,450 | C# |
using BlazingPizza.Client;
using BlazingPizza.Client.Services;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
namespace BlazingPizza
{
public static class TestContextExtensions
{
public static TestContext AddBlazingPizzaSupport(this TestContext context)
{
context.Services.AddSingleton<FakePizzaApi>(new FakePizzaApi());
context.Services.AddSingleton<IPizzaApi>(s => s.GetRequiredService<FakePizzaApi>());
return context;
}
}
}
| 27.8 | 96 | 0.723022 | [
"MIT"
] | egil/blazor-workshop | save-points/00-get-started/BlazingPizza.Tests/Helpers/TestContextExtensions.cs | 558 | C# |
//-----------------------------------------------------------------------
// <copyright file="LeaderDowningNodeThatIsUnreachableSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.Cluster.TestKit;
using Akka.Configuration;
using Akka.Remote.TestKit;
using FluentAssertions;
using FluentAssertions.Extensions;
using MultiNodeFactAttribute = Akka.MultiNode.TestAdapter.MultiNodeFactAttribute;
namespace Akka.Cluster.Tests.MultiNode
{
public class LeaderDowningNodeThatIsUnreachableConfig : MultiNodeConfig
{
public RoleName First { get; private set; }
public RoleName Second { get; private set; }
public RoleName Third { get; private set; }
public RoleName Fourth { get; private set; }
public LeaderDowningNodeThatIsUnreachableConfig(bool failureDetectorPuppet)
{
First = Role("first");
Second = Role("second");
Third = Role("third");
Fourth = Role("fourth");
CommonConfig = DebugConfig(false)
.WithFallback(ConfigurationFactory.ParseString(@"akka.cluster.auto-down-unreachable-after = 2s"))
.WithFallback(MultiNodeClusterSpec.ClusterConfig(failureDetectorPuppet));
}
}
public class LeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiNode : LeaderDowningNodeThatIsUnreachableSpec
{
public LeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiNode() : base(true, typeof(LeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiNode))
{
}
}
public class LeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiNode : LeaderDowningNodeThatIsUnreachableSpec
{
public LeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiNode() : base(false, typeof(LeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiNode))
{
}
}
public abstract class LeaderDowningNodeThatIsUnreachableSpec : MultiNodeClusterSpec
{
private readonly LeaderDowningNodeThatIsUnreachableConfig _config;
protected LeaderDowningNodeThatIsUnreachableSpec(bool failureDetectorPuppet, Type type)
: this(new LeaderDowningNodeThatIsUnreachableConfig(failureDetectorPuppet), type)
{
}
protected LeaderDowningNodeThatIsUnreachableSpec(LeaderDowningNodeThatIsUnreachableConfig config, Type type)
: base(config, type)
{
_config = config;
MuteMarkingAsUnreachable();
}
[MultiNodeFact]
public void LeaderDowningNodeThatIsUnreachableSpecs()
{
Leader_in_4_node_cluster_must_be_able_to_down_last_node_that_is_unreachable();
Leader_in_4_node_cluster_must_be_able_to_down_middle_node_that_is_unreachable();
}
public void Leader_in_4_node_cluster_must_be_able_to_down_last_node_that_is_unreachable()
{
AwaitClusterUp(_config.First, _config.Second, _config.Third, _config.Fourth);
var fourthAddress = GetAddress(_config.Fourth);
EnterBarrier("before-exit-fourth-node");
RunOn(() =>
{
// kill 'fourth' node
TestConductor.Exit(_config.Fourth, 0).Wait();
EnterBarrier("down-fourth-node");
// mark the node as unreachable in the failure detector
MarkNodeAsUnavailable(fourthAddress);
// --- HERE THE LEADER SHOULD DETECT FAILURE AND AUTO-DOWN THE UNREACHABLE NODE ---
AwaitMembersUp(3, ImmutableHashSet.Create(fourthAddress), 30.Seconds());
}, _config.First);
RunOn(() =>
{
EnterBarrier("down-fourth-node");
}, _config.Fourth);
RunOn(() =>
{
EnterBarrier("down-fourth-node");
AwaitMembersUp(3, ImmutableHashSet.Create(fourthAddress), 30.Seconds());
}, _config.Second, _config.Third);
EnterBarrier("await-completion-1");
}
public void Leader_in_4_node_cluster_must_be_able_to_down_middle_node_that_is_unreachable()
{
var secondAddress = GetAddress(_config.Second);
EnterBarrier("before-down-second-node");
RunOn(() =>
{
// kill 'fourth' node
TestConductor.Exit(_config.Second, 0).Wait();
EnterBarrier("down-second-node");
// mark the node as unreachable in the failure detector
MarkNodeAsUnavailable(secondAddress);
// --- HERE THE LEADER SHOULD DETECT FAILURE AND AUTO-DOWN THE UNREACHABLE NODE ---
AwaitMembersUp(2, ImmutableHashSet.Create(secondAddress), 30.Seconds());
}, _config.First);
RunOn(() =>
{
EnterBarrier("down-second-node");
}, _config.Second);
RunOn(() =>
{
EnterBarrier("down-second-node");
AwaitMembersUp(2, ImmutableHashSet.Create(secondAddress), 30.Seconds());
}, _config.Second, _config.Third);
EnterBarrier("await-completion-2");
}
}
}
| 37.95302 | 179 | 0.634129 | [
"Apache-2.0"
] | BearerPipelineTest/akka.net | src/core/Akka.Cluster.Tests.MultiNode/LeaderDowningNodeThatIsUnreachableSpec.cs | 5,657 | C# |
using System;
class E
{
static void Main()
{
var d = int.Parse(Console.ReadLine());
var n = Console.ReadLine();
var l = n.Length;
var dp = new long[l + 1, d, 2];
dp[0, 0, 0] = 1;
for (int i = 0; i < l; i++)
{
var x = n[i] - '0';
for (int j = 0; j < d; j++)
{
dp[i + 1, (j + x) % d, 0] = dp[i, j, 0];
for (int k = 0; k < 10; k++)
dp[i + 1, (j + k) % d, 1] = (dp[i + 1, (j + k) % d, 1] + (k < x ? dp[i, j, 0] : 0) + dp[i, j, 1]) % 1000000007;
}
}
Console.WriteLine(dp[l, 0, 0] + dp[l, 0, 1] - 1);
}
}
| 22.038462 | 117 | 0.401396 | [
"MIT"
] | sakapon/AtCoder-Contests | CSharp/Contests/TDPC/E.cs | 575 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace KdajBi.Core.dtoModels
{
public class dtoCompany
{
public long Id { get; set; }
public string Name { get; set; }
public dtoCompany() { }
public dtoCompany(long p_id, string p_name)
{ Id = p_id; Name = p_name; }
}
}
| 20.888889 | 51 | 0.630319 | [
"MIT"
] | twooclock/KdajBi | KdajBi.Core/dtoModels/dtoCompany.cs | 378 | C# |
using BeauData;
namespace RuleScript.Data
{
public struct RSNamedValue : ISerializedObject, ISerializedVersion
{
public string Name;
public RSValue Value;
public RSNamedValue(string inName, RSValue inValue)
{
Name = inName;
Value = inValue;
}
#region ISerializedObject
ushort ISerializedVersion.Version { get { return 1; } }
void ISerializedObject.Serialize(Serializer ioSerializer)
{
ioSerializer.Serialize("name", ref Name);
ioSerializer.Object("value", ref Value);
}
#endregion // ISerializedObject
}
} | 23.535714 | 70 | 0.60698 | [
"MIT"
] | FilamentGames/RuleScript | Assets/RuleScript/Data/Utils/RSNamedValue.cs | 659 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* 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.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
/* This class was auto-generated by the message builder generator tools. */
using Ca.Infoway.Messagebuilder;
namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue {
public interface ParticipationTargetDevice : Code {
}
}
| 36.586207 | 83 | 0.711593 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/ParticipationTargetDevice.cs | 1,061 | C# |
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace TodoListClient.Common
{
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
}
| 26.291667 | 82 | 0.659271 | [
"MIT"
] | Azure-Samples/ms-identity-dotnetcore-ca-auth-context-app | TodoListClient/Common/SessionExtensions.cs | 633 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EroNumber.Core.Wpf.Net40")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EroNumber.Core.Wpf.Net40")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请设置
//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
//例如,如果您在源文件中使用的是美国英语,
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(未在页面中找到资源时使用,
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(未在页面中找到资源时使用,
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 30.647059 | 91 | 0.660909 | [
"MIT"
] | h82258652/EroNumber.Core | EroNumber.Core/EroNumber.Core.Wpf.Net40/Properties/AssemblyInfo.cs | 2,224 | C# |
using System;
namespace brainflow
{
/// <summary>
/// BrainFlowException class to notify about errors
/// </summary>
public class BrainFlowException : Exception
{
/// <summary>
/// exit code returned from low level API
/// </summary>
public int exit_code;
public BrainFlowException (int code) : base (String.Format ("{0}:{1}", Enum.GetName (typeof (CustomExitCodes), code), code))
{
exit_code = code;
}
}
}
| 23.904762 | 132 | 0.573705 | [
"MIT"
] | BrainAlive/brainflow | csharp-package/brainflow/brainflow/brainflow_exception.cs | 504 | C# |
//************************************************************************************************
// Copyright © 2020 Steven M Cohn. All rights reserved.
//************************************************************************************************
namespace River.OneMoreAddIn.Commands
{
using Microsoft.Office.Core;
using River.OneMoreAddIn.Settings;
using System.Threading.Tasks;
internal class ManagePluginsCommand : Command
{
public ManagePluginsCommand()
{
}
public override async Task Execute(params object[] args)
{
using (var dialog = new SettingsDialog(args[0] as IRibbonUI))
{
dialog.ActivateSheet(SettingsDialog.Sheets.Plugins);
dialog.ShowDialog(owner);
}
await Task.Yield();
}
}
} | 25.655172 | 99 | 0.52957 | [
"MPL-2.0"
] | HarthTuwist/OneMore | OneMore/Commands/File/ManagePluginsCommand.cs | 747 | 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.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface IWorkbookTableRowRangeRequest.
/// </summary>
public partial interface IWorkbookTableRowRangeRequest : IBaseRequest
{
/// <summary>
/// Issues the GET request.
/// </summary>
System.Threading.Tasks.Task<WorkbookRange> 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<WorkbookRange> GetAsync(
CancellationToken cancellationToken);
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange object set with the properties to update.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookRange> PatchAsync(WorkbookRange workbookrange);
/// <summary>
/// Issues the PATCH request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange 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<WorkbookRange> PatchAsync(WorkbookRange workbookrange,
CancellationToken cancellationToken);
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange object to update.</param>
/// <returns>The task to await for async call.</returns>
System.Threading.Tasks.Task<WorkbookRange> PutAsync(WorkbookRange workbookrange);
/// <summary>
/// Issues the PUT request.
/// </summary>
/// <param name=workbookrange>The WorkbookRange 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<WorkbookRange> PutAsync(WorkbookRange workbookrange,
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>
IWorkbookTableRowRangeRequest 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>
IWorkbookTableRowRangeRequest Select(string value);
}
}
| 39.303371 | 153 | 0.603774 | [
"MIT"
] | twsouthwick/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookTableRowRangeRequest.cs | 3,498 | C# |
using System;
namespace PuertsStaticWrap
{
public static class UnityEngine_TouchScreenKeyboard_Wrap
{
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8ConstructorCallback))]
private static IntPtr Constructor(IntPtr isolate, IntPtr info, int paramLen, long data)
{
try
{
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
var argHelper3 = new Puerts.ArgumentHelper((int)data, isolate, info, 3);
var argHelper4 = new Puerts.ArgumentHelper((int)data, isolate, info, 4);
var argHelper5 = new Puerts.ArgumentHelper((int)data, isolate, info, 5);
var argHelper6 = new Puerts.ArgumentHelper((int)data, isolate, info, 6);
var argHelper7 = new Puerts.ArgumentHelper((int)data, isolate, info, 7);
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var Arg3 = argHelper3.GetBoolean(false);
var Arg4 = argHelper4.GetBoolean(false);
var Arg5 = argHelper5.GetBoolean(false);
var Arg6 = argHelper6.GetString(false);
var Arg7 = argHelper7.GetInt32(false);
var result = new UnityEngine.TouchScreenKeyboard(Arg0,Arg1,Arg2,Arg3,Arg4,Arg5,Arg6,Arg7);
return Puerts.Utils.GetObjectPtr((int)data, typeof(UnityEngine.TouchScreenKeyboard), result);
}
}
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
return IntPtr.Zero;
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void F_Open(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
if (paramLen == 8)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
var argHelper3 = new Puerts.ArgumentHelper((int)data, isolate, info, 3);
var argHelper4 = new Puerts.ArgumentHelper((int)data, isolate, info, 4);
var argHelper5 = new Puerts.ArgumentHelper((int)data, isolate, info, 5);
var argHelper6 = new Puerts.ArgumentHelper((int)data, isolate, info, 6);
var argHelper7 = new Puerts.ArgumentHelper((int)data, isolate, info, 7);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper3.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper4.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper5.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper6.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper7.IsMatch(Puerts.JsValueType.Number, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var Arg3 = argHelper3.GetBoolean(false);
var Arg4 = argHelper4.GetBoolean(false);
var Arg5 = argHelper5.GetBoolean(false);
var Arg6 = argHelper6.GetString(false);
var Arg7 = argHelper7.GetInt32(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1,Arg2,Arg3,Arg4,Arg5,Arg6,Arg7);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 7)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
var argHelper3 = new Puerts.ArgumentHelper((int)data, isolate, info, 3);
var argHelper4 = new Puerts.ArgumentHelper((int)data, isolate, info, 4);
var argHelper5 = new Puerts.ArgumentHelper((int)data, isolate, info, 5);
var argHelper6 = new Puerts.ArgumentHelper((int)data, isolate, info, 6);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper3.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper4.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper5.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper6.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var Arg3 = argHelper3.GetBoolean(false);
var Arg4 = argHelper4.GetBoolean(false);
var Arg5 = argHelper5.GetBoolean(false);
var Arg6 = argHelper6.GetString(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1,Arg2,Arg3,Arg4,Arg5,Arg6);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 6)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
var argHelper3 = new Puerts.ArgumentHelper((int)data, isolate, info, 3);
var argHelper4 = new Puerts.ArgumentHelper((int)data, isolate, info, 4);
var argHelper5 = new Puerts.ArgumentHelper((int)data, isolate, info, 5);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper3.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper4.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper5.IsMatch(Puerts.JsValueType.Boolean, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var Arg3 = argHelper3.GetBoolean(false);
var Arg4 = argHelper4.GetBoolean(false);
var Arg5 = argHelper5.GetBoolean(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1,Arg2,Arg3,Arg4,Arg5);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 5)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
var argHelper3 = new Puerts.ArgumentHelper((int)data, isolate, info, 3);
var argHelper4 = new Puerts.ArgumentHelper((int)data, isolate, info, 4);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper3.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper4.IsMatch(Puerts.JsValueType.Boolean, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var Arg3 = argHelper3.GetBoolean(false);
var Arg4 = argHelper4.GetBoolean(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1,Arg2,Arg3,Arg4);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 4)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
var argHelper3 = new Puerts.ArgumentHelper((int)data, isolate, info, 3);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.Boolean, null, false, false)
&& argHelper3.IsMatch(Puerts.JsValueType.Boolean, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var Arg3 = argHelper3.GetBoolean(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1,Arg2,Arg3);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 3)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.Boolean, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var Arg2 = argHelper2.GetBoolean(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1,Arg2);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 2)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.Number, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var Arg1 = (UnityEngine.TouchScreenKeyboardType)argHelper1.GetInt32(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0,Arg1);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
if (paramLen == 1)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.String, null, false, false))
{
var Arg0 = argHelper0.GetString(false);
var result = UnityEngine.TouchScreenKeyboard.Open(Arg0);
Puerts.ResultHelper.Set((int)data, isolate, info, result);
return;
}
}
Puerts.PuertsDLL.ThrowException(isolate, "invalid arguments to Open");
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_isSupported(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var result = UnityEngine.TouchScreenKeyboard.isSupported;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_isInPlaceEditingAllowed(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var result = UnityEngine.TouchScreenKeyboard.isInPlaceEditingAllowed;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_text(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.text;
Puerts.PuertsDLL.ReturnString(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_text(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
obj.text = argHelper.GetString(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_hideInput(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var result = UnityEngine.TouchScreenKeyboard.hideInput;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_hideInput(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
UnityEngine.TouchScreenKeyboard.hideInput = argHelper.GetBoolean(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_active(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.active;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_active(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
obj.active = argHelper.GetBoolean(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_status(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.status;
Puerts.PuertsDLL.ReturnNumber(isolate, info, (int)result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_characterLimit(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.characterLimit;
Puerts.PuertsDLL.ReturnNumber(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_characterLimit(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
obj.characterLimit = argHelper.GetInt32(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_canGetSelection(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.canGetSelection;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_canSetSelection(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.canSetSelection;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_selection(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.selection;
Puerts.ResultHelper.Set((int)data, isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_selection(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
obj.selection = argHelper.Get<UnityEngine.RangeInt>(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_type(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.type;
Puerts.PuertsDLL.ReturnNumber(isolate, info, (int)result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_targetDisplay(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var result = obj.targetDisplay;
Puerts.PuertsDLL.ReturnNumber(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_targetDisplay(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.TouchScreenKeyboard;
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
obj.targetDisplay = argHelper.GetInt32(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_area(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var result = UnityEngine.TouchScreenKeyboard.area;
Puerts.ResultHelper.Set((int)data, isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_visible(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var result = UnityEngine.TouchScreenKeyboard.visible;
Puerts.PuertsDLL.ReturnBoolean(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
public static Puerts.TypeRegisterInfo GetRegisterInfo()
{
return new Puerts.TypeRegisterInfo()
{
BlittableCopy = false,
Constructor = Constructor,
Methods = new System.Collections.Generic.Dictionary<Puerts.MethodKey, Puerts.V8FunctionCallback>()
{
{ new Puerts.MethodKey {Name = "Open", IsStatic = true}, F_Open },
},
Properties = new System.Collections.Generic.Dictionary<string, Puerts.PropertyRegisterInfo>()
{
{"isSupported", new Puerts.PropertyRegisterInfo(){ IsStatic = true, Getter = G_isSupported, Setter = null} },
{"isInPlaceEditingAllowed", new Puerts.PropertyRegisterInfo(){ IsStatic = true, Getter = G_isInPlaceEditingAllowed, Setter = null} },
{"text", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_text, Setter = S_text} },
{"hideInput", new Puerts.PropertyRegisterInfo(){ IsStatic = true, Getter = G_hideInput, Setter = S_hideInput} },
{"active", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_active, Setter = S_active} },
{"status", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_status, Setter = null} },
{"characterLimit", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_characterLimit, Setter = S_characterLimit} },
{"canGetSelection", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_canGetSelection, Setter = null} },
{"canSetSelection", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_canSetSelection, Setter = null} },
{"selection", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_selection, Setter = S_selection} },
{"type", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_type, Setter = null} },
{"targetDisplay", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_targetDisplay, Setter = S_targetDisplay} },
{"area", new Puerts.PropertyRegisterInfo(){ IsStatic = true, Getter = G_area, Setter = null} },
{"visible", new Puerts.PropertyRegisterInfo(){ IsStatic = true, Getter = G_visible, Setter = null} },
}
};
}
}
} | 48.44713 | 153 | 0.519051 | [
"MIT"
] | HFX-93/luban_examples | Projects/TypeScript_Unity_Puerts_Bin/Assets/Gen/UnityEngine_TouchScreenKeyboard_Wrap.cs | 32,074 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.trade.royalty.relation.unbind
/// </summary>
public class AlipayTradeRoyaltyRelationUnbindRequest : IAlipayRequest<AlipayTradeRoyaltyRelationUnbindResponse>
{
/// <summary>
/// 分账关系解绑
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.trade.royalty.relation.unbind";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.806452 | 115 | 0.549859 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayTradeRoyaltyRelationUnbindRequest.cs | 2,842 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Cofoundry.Domain;
using Microsoft.AspNetCore.Mvc;
namespace Cofoundry.Web.Admin
{
public class UsersModuleController : BaseAdminMvcController
{
public UsersModuleController(
IUserAreaDefinitionRepository userAreaDefinitionRepository
)
{
_userAreaDefinitionRepository = userAreaDefinitionRepository;
}
private static readonly Dictionary<string, string> EmptyTerms = new Dictionary<string, string>();
private readonly IUserAreaDefinitionRepository _userAreaDefinitionRepository;
public ActionResult Index()
{
var userArea = RouteData.DataTokens["UserArea"] as IUserAreaDefinition;
var userAreaOptions = _userAreaDefinitionRepository.GetOptionsByCode(userArea.UserAreaCode);
var options = new UsersModuleOptions()
{
UserAreaCode = userArea.UserAreaCode,
Name = userArea.Name,
AllowPasswordSignIn = userArea.AllowPasswordSignIn,
UseEmailAsUsername = userArea.UseEmailAsUsername,
ShowDisplayName = !userAreaOptions.Username.UseAsDisplayName
};
var viewPath = ViewPathFormatter.View("Users", nameof(Index));
return View(viewPath, options);
}
}
} | 35.74359 | 105 | 0.670732 | [
"MIT"
] | BearerPipelineTest/cofoundry | src/Cofoundry.Web.Admin/Admin/Modules/Users/MVC/Controllers/UsersModuleController.cs | 1,396 | C# |
using System.Collections.Generic;
namespace CleanArchitecture.SharedKernel
{
// This can be modified to BaseEntity<TId> to support multiple key types (e.g. Guid)
public abstract class BaseEntity<TId> : IDomainEventable
{
public TId Id { get; set; }
public List<BaseDomainEvent> Events { get; } = new List<BaseDomainEvent>();
}
} | 30.166667 | 88 | 0.69337 | [
"MIT"
] | miklen/CleanArchitecture | src/CleanArchitecture.SharedKernel/BaseEntity.cs | 362 | C# |
using System;
namespace CSharpEvolution.CSharp2
{
public static class NullableTypes
{
public static void ShowValue(int? a)
{
if (a.HasValue)
{
Console.WriteLine("Argument's value is: " + a);
}
else
{
Console.WriteLine("Default value: " + a.GetValueOrDefault());
}
}
}
public static class NullableTypesExamples
{
public static void Example1()
{
int? a = null; // T? is just syntactic sugar for Nullable<T>
NullableTypes.ShowValue(a);
a = 4;
NullableTypes.ShowValue(a);
}
}
}
| 22.612903 | 77 | 0.493581 | [
"MIT"
] | adolfosilva/csharp-presentation | CSharpEvolution/CSharp2/NullableTypes.cs | 703 | 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>
//------------------------------------------------------------------------------
namespace Sitecore.MediaFramework.UI.Sublayouts
{
public partial class EmbedMediaPlayer
{
/// <summary>
/// PlayerContainer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl PlayerContainer;
}
}
| 32.833333 | 85 | 0.515228 | [
"Apache-2.0"
] | KRazguliaev/pmi.sitecore.9.1.brightcove | src/Sitecore.MediaFramework/UI/Sublayouts/EmbedMediaPlayer.ascx.designer.cs | 767 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace InvoiceService.Function.Properties {
using System;
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスが ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをビルドし直します。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("InvoiceService.Function.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします
/// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 型 System.Byte[] のローカライズされたリソースを検索します。
/// </summary>
internal static byte[] Invoice {
get {
object obj = ResourceManager.GetObject("Invoice", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// 型 System.Byte[] のローカライズされたリソースを検索します。
/// </summary>
internal static byte[] Request {
get {
object obj = ResourceManager.GetObject("Request", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 38.77381 | 189 | 0.583973 | [
"MIT"
] | nuitsjp/DioDocs.FastReportBuilder | DustBox/AzureFunctions/InvoiceService.Function/InvoiceService.Function/Properties/Resources.Designer.cs | 3,977 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Azure.ServiceFabric.ManagedIdentity.Samples
{
[Route("[controller]")]
[ApiController]
public class VaultController : ControllerBase
{
[HttpGet]
public async Task<ActionResult<String>> Get()
{
// initialize a vault probe with settings read from environment
VaultProbe vaultProbe = new VaultProbe(ProbeConfig.FromEnvironment());
String result = await vaultProbe.ProbeSecretAsync()
.ConfigureAwait(false);
return result;
}
}
}
| 27.76 | 82 | 0.651297 | [
"MIT"
] | Azure-Samples/service-fabric-managed-identity | MISampleApp/MISampleWeb/Controllers/VaultController.cs | 696 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.rtc.Model.V20180111;
namespace Aliyun.Acs.rtc.Transform.V20180111
{
public class DisableMAURuleResponseUnmarshaller
{
public static DisableMAURuleResponse Unmarshall(UnmarshallerContext context)
{
DisableMAURuleResponse disableMAURuleResponse = new DisableMAURuleResponse();
disableMAURuleResponse.HttpResponse = context.HttpResponse;
disableMAURuleResponse.RequestId = context.StringValue("DisableMAURule.RequestId");
return disableMAURuleResponse;
}
}
}
| 35.7 | 86 | 0.757003 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-rtc/Rtc/Transform/V20180111/DisableMAURuleResponseUnmarshaller.cs | 1,428 | C# |
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Extensions;
using Modules.GameText.Components;
using Debug = UnityEngine.Debug;
namespace Modules.GameText.Editor
{
public static class GameTxetExcel
{
//----- params -----
public enum Mode
{
Import,
Export,
}
//----- field -----
//----- property -----
//----- method -----
public static void Open(GameTextConfig.GenerateAssetSetting setting)
{
var path = setting.GetExcelPath();
if(!File.Exists(path))
{
Debug.LogError("GameText excel file not found.");
return;
}
using (var process = new Process())
{
var processStartInfo = new ProcessStartInfo
{
FileName = path,
};
process.StartInfo = processStartInfo;
//起動.
process.Start();
}
}
public static async Task Import(ContentType contentType, bool displayConsole)
{
var config = GameTextConfig.Instance;
GameTextConfig.GenerateAssetSetting setting = null;
switch (contentType)
{
case ContentType.Embedded:
setting = config.Embedded;
break;
case ContentType.Distribution:
setting = config.Distribution;
break;
}
var result = await ExecuteProcess(setting, Mode.Import, displayConsole);
if (result.Item1 != 0)
{
Debug.LogError(result.Item2);
}
}
public static async Task Export(ContentType contentType, bool displayConsole)
{
var config = GameTextConfig.Instance;
GameTextConfig.GenerateAssetSetting setting = null;
switch (contentType)
{
case ContentType.Embedded:
setting = config.Embedded;
break;
case ContentType.Distribution:
setting = config.Distribution;
break;
}
var result = await ExecuteProcess(setting, Mode.Export, displayConsole);
if (result.Item1 != 0)
{
Debug.LogError(result.Item2);
}
}
public static bool IsExcelFileLocked(GameTextConfig.GenerateAssetSetting setting)
{
var editExcelPath = setting.GetExcelPath();
if (!File.Exists(editExcelPath)) { return false; }
return FileUtility.IsFileLocked(editExcelPath) ;
}
private static async Task<Tuple<int, string>> ExecuteProcess(GameTextConfig.GenerateAssetSetting setting, Mode mode, bool displayConsole)
{
var config = GameTextConfig.Instance;
var arguments = new StringBuilder();
arguments.AppendFormat("--workspace {0} ", setting.GetGameTextWorkspacePath());
switch (mode)
{
case Mode.Import:
arguments.Append("--mode import ");
break;
case Mode.Export:
arguments.Append("--mode export ");
break;
}
var processExecute = new ProcessExecute(config.ConverterPath, arguments.ToString())
{
Encoding = Encoding.GetEncoding("Shift_JIS"),
WorkingDirectory = setting.GetGameTextWorkspacePath(),
UseShellExecute = displayConsole,
Hide = !displayConsole,
};
var result = await processExecute.StartAsync();
return Tuple.Create(result.ExitCode, result.Error);
}
}
}
| 27.472603 | 145 | 0.514834 | [
"MIT"
] | oTAMAKOo/UniModules | Scripts/Modules/GameText/Editor/GameTxetExcel.cs | 4,017 | C# |
namespace VoteApp.Application.Interfaces.Serialization.Serializers
{
public interface IJsonSerializer
{
string Serialize<T>(T obj);
T Deserialize<T>(string text);
}
} | 24.375 | 67 | 0.687179 | [
"MIT"
] | andlekbra/dat250-gruppe5-VoteApp2 | src/Application/Interfaces/Serialization/Serializers/IJsonSerializer.cs | 197 | C# |
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
namespace WebApis
{
public class Program
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.File("../Logs/_webapis.txt")
.MinimumLevel.Debug()
.WriteTo.Console(theme: AnsiConsoleTheme.Code)
);
});
}
}
| 31.444444 | 93 | 0.501178 | [
"MIT"
] | damienbod/azureb2c-fed-azuread | WebApis/Program.cs | 1,698 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20210301
{
/// <summary>
/// Network watcher in a resource group.
/// </summary>
[AzureNativeResourceType("azure-native:network/v20210301:NetworkWatcher")]
public partial class NetworkWatcher : Pulumi.CustomResource
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the network watcher resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a NetworkWatcher resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public NetworkWatcher(string name, NetworkWatcherArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/v20210301:NetworkWatcher", name, args ?? new NetworkWatcherArgs(), MakeResourceOptions(options, ""))
{
}
private NetworkWatcher(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/v20210301:NetworkWatcher", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/v20210301:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20160901:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20161201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20170301:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20170601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20170801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20170901:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20171001:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20171101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20180101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20180201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20180401:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20180601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20180701:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20190601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20200301:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20200401:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20201101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-native:network/v20210201:NetworkWatcher"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20210201:NetworkWatcher"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing NetworkWatcher resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static NetworkWatcher Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new NetworkWatcher(name, id, options);
}
}
public sealed class NetworkWatcherArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the network watcher.
/// </summary>
[Input("networkWatcherName")]
public Input<string>? NetworkWatcherName { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public NetworkWatcherArgs()
{
}
}
}
| 55.061321 | 141 | 0.59976 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20210301/NetworkWatcher.cs | 11,673 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace TokanPages.Backend.Database.Migrations
{
public partial class AddUserIdForeignKey : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "UserId",
table: "Articles",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.CreateIndex(
name: "IX_Articles_UserId",
table: "Articles",
column: "UserId");
migrationBuilder.AddForeignKey(
name: "FK_Articles_Users",
table: "Articles",
column: "UserId",
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Articles_Users",
table: "Articles");
migrationBuilder.DropIndex(
name: "IX_Articles_UserId",
table: "Articles");
migrationBuilder.DropColumn(
name: "UserId",
table: "Articles");
}
}
}
| 30.255319 | 80 | 0.54571 | [
"MIT"
] | TomaszKandula/TokanPages | TokanPages.Backend/TokanPages.Backend.Database/Migrations/20210128144811_AddUserIdForeignKey.cs | 1,424 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Linq;
using Microsoft.Azure.Management.Batch.Models;
namespace Microsoft.Azure.Commands.Batch.Models
{
public class PSApplicationPackage
{
public string Format { get; set; }
public PackageState State { get; set; }
public string Id { get; set; }
public string Name { get; set; }
public DateTime? LastActivationTime { get; set; }
public string StorageUrl { get; set; }
public DateTime StorageUrlExpiry { get; set; }
}
} | 35.459459 | 87 | 0.595274 | [
"MIT"
] | AikoTsuruoka/azure-powershell | src/Batch/Batch/Models/PSApplicationPackage.cs | 1,278 | C# |
using Chloe.Server.Dtos;
using Chloe.Server.Services.Contracts;
using System.Web.Http;
namespace Chloe.Server.Controllers
{
[Authorize]
[RoutePrefix("api/vendor")]
public class VendorController : ApiController
{
public VendorController(IVendorService service)
{
this.service = service;
}
[Route("add")]
[HttpPost]
public IHttpActionResult Add(VendorAddOrUpdateRequestDto dto) { return Ok(this.service.AddOrUpdate(dto)); }
[Route("update")]
[HttpPut]
public IHttpActionResult Update(VendorAddOrUpdateRequestDto dto) { return Ok(this.service.AddOrUpdate(dto)); }
[Route("get")]
[AllowAnonymous]
[HttpGet]
public IHttpActionResult Get(VendorAddOrUpdateRequestDto dto) { return Ok(this.service.Get()); }
[Route("getById")]
[HttpGet]
public IHttpActionResult GetById(int id) { return Ok(this.service.GetById(id)); }
[Route("remove")]
[HttpDelete]
public IHttpActionResult Remove(int id) { return Ok(this.service.Remove(id)); }
protected readonly IVendorService service;
}
}
| 28.560976 | 118 | 0.645602 | [
"MIT"
] | QuinntyneBrown/dynamic-scheduling | Server/Controllers/VendorController.cs | 1,171 | C# |
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_Experimental_Director_FrameData : LuaObject {
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int constructor(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData o;
o=new UnityEngine.Experimental.Director.FrameData();
pushValue(l,true);
pushValue(l,o);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_updateId(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.updateId);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_time(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.time);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_lastTime(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.lastTime);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_deltaTime(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.deltaTime);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_timeScale(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.timeScale);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_dTime(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.dTime);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_dLastTime(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.dLastTime);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_dDeltaTime(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.dDeltaTime);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_dtimeScale(IntPtr l) {
try {
UnityEngine.Experimental.Director.FrameData self;
checkValueType(l,1,out self);
pushValue(l,true);
pushValue(l,self.dtimeScale);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.Experimental.Director.FrameData");
addMember(l,"updateId",get_updateId,null,true);
addMember(l,"time",get_time,null,true);
addMember(l,"lastTime",get_lastTime,null,true);
addMember(l,"deltaTime",get_deltaTime,null,true);
addMember(l,"timeScale",get_timeScale,null,true);
addMember(l,"dTime",get_dTime,null,true);
addMember(l,"dLastTime",get_dLastTime,null,true);
addMember(l,"dDeltaTime",get_dDeltaTime,null,true);
addMember(l,"dtimeScale",get_dtimeScale,null,true);
createTypeMetatable(l,constructor, typeof(UnityEngine.Experimental.Director.FrameData),typeof(System.ValueType));
}
}
| 27.56 | 116 | 0.696178 | [
"MIT"
] | zhangjie0072/Learn_FairyGUI_Slua | Assets/Slua/LuaObject/Unity/Lua_UnityEngine_Experimental_Director_FrameData.cs | 4,136 | C# |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MixERP.Net.Api.Framework;
using MixERP.Net.ApplicationState.Cache;
using MixERP.Net.Common.Extensions;
using MixERP.Net.EntityParser;
using MixERP.Net.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MixERP.Net.Schemas.Core.Data;
using MixERP.Net.Api.Core.Fakes;
using Xunit;
namespace MixERP.Net.Api.Core.Tests
{
public class TaxBaseAmountTypeTests
{
public static TaxBaseAmountTypeController Fixture()
{
TaxBaseAmountTypeController controller = new TaxBaseAmountTypeController(new TaxBaseAmountTypeRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
MixERP.Net.Entities.Core.TaxBaseAmountType taxBaseAmountType = Fixture().Get(string.Empty);
Assert.NotNull(taxBaseAmountType);
}
[Fact]
[Conditional("Debug")]
public void First()
{
MixERP.Net.Entities.Core.TaxBaseAmountType taxBaseAmountType = Fixture().GetFirst();
Assert.NotNull(taxBaseAmountType);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
MixERP.Net.Entities.Core.TaxBaseAmountType taxBaseAmountType = Fixture().GetPrevious(string.Empty);
Assert.NotNull(taxBaseAmountType);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
MixERP.Net.Entities.Core.TaxBaseAmountType taxBaseAmountType = Fixture().GetNext(string.Empty);
Assert.NotNull(taxBaseAmountType);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
MixERP.Net.Entities.Core.TaxBaseAmountType taxBaseAmountType = Fixture().GetLast();
Assert.NotNull(taxBaseAmountType);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<MixERP.Net.Entities.Core.TaxBaseAmountType> taxBaseAmountTypes = Fixture().Get(new string[] { });
Assert.NotNull(taxBaseAmountTypes);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(string.Empty, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(string.Empty);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
} | 26.421488 | 141 | 0.525493 | [
"MPL-2.0"
] | asine/mixerp | src/Libraries/Web API/Core/Tests/TaxBaseAmountTypeTests.cs | 6,394 | C# |
namespace Petstore.Models
{
using System.Linq;
public partial class Order
{
/// <summary>
/// Initializes a new instance of the Order class.
/// </summary>
public Order() { }
/// <summary>
/// Initializes a new instance of the Order class.
/// </summary>
/// <param name="status">Order Status. Possible values include:
/// 'placed', 'approved', 'delivered'</param>
public Order(long? id = default(long?), long? petId = default(long?), int? quantity = default(int?), System.DateTime? shipDate = default(System.DateTime?), string status = default(string), bool? complete = default(bool?))
{
Id = id;
PetId = petId;
Quantity = quantity;
ShipDate = shipDate;
Status = status;
Complete = complete;
}
/// <summary>
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "id")]
public long? Id { get; private set; }
/// <summary>
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "petId")]
public long? PetId { get; set; }
/// <summary>
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "quantity")]
public int? Quantity { get; set; }
/// <summary>
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "shipDate")]
public System.DateTime? ShipDate { get; set; }
/// <summary>
/// Gets or sets order Status. Possible values include: 'placed',
/// 'approved', 'delivered'
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "status")]
public string Status { get; set; }
/// <summary>
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "complete")]
public bool? Complete { get; set; }
}
}
| 31.129032 | 229 | 0.544041 | [
"MIT"
] | fhoering/autorest | Samples/petstore/CSharp/Models/Order.cs | 1,930 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.237
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace YouTubeUploader.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("YouTubeUploader.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static System.Drawing.Bitmap gdata_youtube {
get {
object obj = ResourceManager.GetObject("gdata_youtube", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 43.929577 | 182 | 0.59378 | [
"Apache-2.0"
] | michael-jia-sage/libgoogle | samples/YouTubeUploader/YouTubeUploader/Properties/Resources.Designer.cs | 3,121 | 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.Globalization;
using System.Threading;
namespace Microsoft.Build.Shared
{
/// <summary>
/// Class to wrap the saving and restoring of the culture of a threadpool thread
/// </summary>
internal static class ThreadPoolExtensions
{
/// <summary>
/// Queue a threadpool thread and set it to a certain culture.
/// </summary>
internal static bool QueueThreadPoolWorkItemWithCulture(WaitCallback callback, CultureInfo culture, CultureInfo uiCulture)
{
bool success = ThreadPool.QueueUserWorkItem(
delegate (Object state)
{
// Save the culture so at the end of the threadproc if something else reuses this thread then it will not have a culture which it was not expecting.
CultureInfo originalThreadCulture = CultureInfo.CurrentCulture;
CultureInfo originalThreadUICulture = CultureInfo.CurrentUICulture;
try
{
if (CultureInfo.CurrentCulture != culture)
{
#if FEATURE_THREAD_CULTURE
Thread.CurrentThread.CurrentCulture = culture;
#else
CultureInfo.CurrentCulture = culture;
#endif
}
if (CultureInfo.CurrentUICulture != uiCulture)
{
#if FEATURE_THREAD_CULTURE
Thread.CurrentThread.CurrentUICulture = uiCulture;
#else
CultureInfo.CurrentCulture = uiCulture;
#endif
}
callback(state);
}
finally
{
// Set the culture back to the original one so that if something else reuses this thread then it will not have a culture which it was not expecting.
if (CultureInfo.CurrentCulture != originalThreadCulture)
{
#if FEATURE_THREAD_CULTURE
Thread.CurrentThread.CurrentCulture = originalThreadCulture;
#else
CultureInfo.CurrentCulture = originalThreadCulture;
#endif
}
if (CultureInfo.CurrentUICulture != originalThreadUICulture)
{
#if FEATURE_THREAD_CULTURE
Thread.CurrentThread.CurrentUICulture = originalThreadUICulture;
#else
CultureInfo.CurrentUICulture = originalThreadUICulture;
#endif
}
}
});
return success;
}
}
}
| 37.4 | 170 | 0.568627 | [
"MIT"
] | AaronRobinsonMSFT/msbuild | src/Shared/ThreadPoolExtensions.cs | 2,807 | C# |
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using QuadTrees;
using QuadTrees.QTreePointF;
namespace Neusie.Generation.Image
{
internal class CollisionMap : ICollisionMap
{
public CollisionMap( int width, int height )
{
Width = width;
Height = height;
PointTree = new QuadTreePointF<PointEntry>( 0, 0, Width, Height );
}
private bool CheckBounds( RectangleF rect )
{
if( rect.Right >= Width || rect.Left >= Width )
{
return false;
}
if( rect.Left <= 0 || rect.Right <= 0 )
{
return false;
}
if( rect.Bottom <= 0 || rect.Top <= 0 )
{
return false;
}
if( rect.Bottom >= Height || rect.Top >= Height )
{
return false;
}
return true;
}
private bool CheckCollision( RectangleF rect )
{
rect.Inflate( 1, 1 );
var rectangles = PointTree.GetObjects( rect ).Select( r => r.Rect );
if( !CheckCollision( rect, rectangles ) )
{
return false;
}
return true;
}
private static bool CheckCollision( RectangleF rect, IEnumerable<RectangleF> rectangles )
{
foreach( var exitingRectangle in rectangles )
{
if( exitingRectangle.IntersectsWith( rect ) )
{
return false;
}
}
return true;
}
private IEnumerable<PointEntry> GetEdgePoints( RectangleF rect )
{
yield return new PointEntry( rect, new PointF( rect.Left, rect.Top ) );
yield return new PointEntry( rect, new PointF( rect.Right, rect.Top ) );
yield return new PointEntry( rect, new PointF( rect.Left, rect.Bottom ) );
yield return new PointEntry( rect, new PointF( rect.Right, rect.Bottom ) );
}
public bool Check( IEnumerable<RectangleF> rects )
{
return rects.All( rect => CheckBounds( rect ) && CheckCollision( rect ) );
}
public void Insert( IEnumerable<RectangleF> rects )
{
var rectList = rects.ToList();
PointTree.AddRange( rectList.SelectMany( GetEdgePoints ) );
}
public IEnumerable<RectangleF> Rectangles => PointTree.GetAllObjects().Select( o => o.Rect ).Distinct();
private readonly int Height;
private readonly QuadTreePointF<PointEntry> PointTree;
private readonly int Width;
private class PointEntry : IPointFQuadStorable
{
public PointEntry( RectangleF rect, PointF point )
{
Rect = rect;
Point = point;
}
/// <inheritdoc />
public PointF Point { get; }
public RectangleF Rect { get; }
}
}
} | 21.972727 | 106 | 0.658254 | [
"MIT"
] | TheSylence/Neusie | Neusie/Generation/Image/CollisionMap.cs | 2,419 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Common;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Reporting.History
{
/// <summary>
/// Reads all historic coverage files created by <see cref="HistoryReportGenerator"/> and adds the information to all classes.
/// </summary>
internal class HistoryParser
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(HistoryParser));
/// <summary>
/// The history storage.
/// </summary>
private readonly IHistoryStorage historyStorage;
/// <summary>
/// The maximum number of historic coverage files that get parsed.
/// </summary>
private readonly int maximumNumberOfHistoricCoverageFiles;
/// <summary>
/// The number reports that are parsed and processed in parallel.
/// </summary>
private readonly int numberOfReportsParsedInParallel;
/// <summary>
/// Initializes a new instance of the <see cref="HistoryParser" /> class.
/// </summary>
/// <param name="historyStorage">The history storage.</param>
/// <param name="maximumNumberOfHistoricCoverageFiles">The maximum number of historic coverage files that get parsed.</param>
/// <param name="numberOfReportsParsedInParallel">The number reports that are parsed and processed in parallel.</param>
internal HistoryParser(IHistoryStorage historyStorage, int maximumNumberOfHistoricCoverageFiles, int numberOfReportsParsedInParallel)
{
this.historyStorage = historyStorage ?? throw new ArgumentNullException(nameof(historyStorage));
this.maximumNumberOfHistoricCoverageFiles = maximumNumberOfHistoricCoverageFiles;
this.numberOfReportsParsedInParallel = numberOfReportsParsedInParallel;
}
/// <summary>
/// Reads all historic coverage files created by <see cref="HistoryReportGenerator" /> and adds the information to all classes.
/// </summary>
/// <param name="assemblies">The assemblies.</param>
/// <param name="overallHistoricCoverages">A list to which all history elements are added.</param>
internal void ApplyHistoricCoverage(IEnumerable<Assembly> assemblies, List<HistoricCoverage> overallHistoricCoverages)
{
if (assemblies == null)
{
throw new ArgumentNullException(nameof(assemblies));
}
if (overallHistoricCoverages == null)
{
throw new ArgumentNullException(nameof(overallHistoricCoverages));
}
Logger.Info(Resources.ReadingHistoricReports);
IEnumerable<string> files = null;
object locker = new object();
try
{
files = this.historyStorage.GetHistoryFilePaths()
.OrderByDescending(f => f)
.Take(this.maximumNumberOfHistoricCoverageFiles)
.Reverse()
.ToArray();
}
catch (Exception ex)
{
Logger.ErrorFormat(Resources.ErrorDuringReadingHistoricReports, ex.GetExceptionMessageForDisplay());
return;
}
var classes = assemblies.SelectMany(t => t.Classes).ToDictionary(k => this.GetFullClassName(k.Assembly.Name, k.Name), v => v);
Parallel.ForEach(
files,
new ParallelOptions { MaxDegreeOfParallelism = this.numberOfReportsParsedInParallel },
file =>
{
try
{
Logger.InfoFormat(Resources.ParseHistoricFile, file);
var document = this.LoadXDocument(file);
DateTime date = DateTime.ParseExact(document.Root.Attribute("date").Value, "yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
string tag = document.Root.Attribute("tag")?.Value;
tag = string.IsNullOrEmpty(tag) ? null : tag;
var historicCoverages = this.ParseHistoricFile(classes, document, date, tag);
lock (locker)
{
overallHistoricCoverages.AddRange(historicCoverages);
}
}
catch (Exception ex)
{
Logger.ErrorFormat(Resources.ErrorDuringReadingHistoricReport, file, ex.GetExceptionMessageForDisplay());
}
});
}
private IEnumerable<HistoricCoverage> ParseHistoricFile(IDictionary<string, Class> classes, XDocument document, DateTime date, string tag)
{
ConcurrentBag<HistoricCoverage> historicCoverages = new ConcurrentBag<HistoricCoverage>();
Parallel.ForEach(document.Root.Elements("assembly").ToArray(), assemblyElement =>
{
string assemblyName = assemblyElement.Attribute("name").Value;
foreach (var classElement in assemblyElement.Elements("class"))
{
HistoricCoverage historicCoverage = new HistoricCoverage(date, tag)
{
CoveredLines = int.Parse(classElement.Attribute("coveredlines").Value, CultureInfo.InvariantCulture),
CoverableLines = int.Parse(classElement.Attribute("coverablelines").Value, CultureInfo.InvariantCulture),
TotalLines = int.Parse(classElement.Attribute("totallines").Value, CultureInfo.InvariantCulture),
CoveredBranches = int.Parse(classElement.Attribute("coveredbranches").Value, CultureInfo.InvariantCulture),
TotalBranches = int.Parse(classElement.Attribute("totalbranches").Value, CultureInfo.InvariantCulture)
};
historicCoverages.Add(historicCoverage);
if (classes.TryGetValue(this.GetFullClassName(assemblyName, classElement.Attribute("name").Value), out var @class))
{
@class.AddHistoricCoverage(historicCoverage);
}
}
});
return historicCoverages;
}
private string GetFullClassName(string assemblyName, string className)
{
return $"{assemblyName}+{className}";
}
private XDocument LoadXDocument(string file)
{
using (var stream = this.historyStorage.LoadFile(file))
{
return XDocument.Load(stream);
}
}
}
} | 45.825806 | 152 | 0.6058 | [
"Apache-2.0"
] | 304NotModified/ReportGenerator | src/ReportGenerator.Core/Reporting/History/HistoryParser.cs | 7,103 | C# |
namespace RouteExtreme.Common
{
using System;
using System.IO;
using System.Reflection;
public static class AssemblyHelpers
{
public static string GetDirectoryForAssembyl(Assembly assembly)
{
var assemblyLocation = assembly.CodeBase;
var location = new UriBuilder(assemblyLocation);
var path = Uri.UnescapeDataString(location.Path);
var directory = Path.GetDirectoryName(path);
return directory;
}
}
}
| 26.947368 | 71 | 0.638672 | [
"MIT"
] | zhenyaracheva/RoutExtreme | RouteExtreme.Common/AssemblyHelpers.cs | 514 | C# |
namespace HareDu
{
public interface QueueDeleteCondition
{
/// <summary>
/// Prevent delete actions on the specified queue from being successful if the queue has consumers.
/// </summary>
void HasNoConsumers();
/// <summary>
/// Prevent delete actions on the specified queue from being successful if the queue contains messages.
/// </summary>
void IsEmpty();
}
} | 29.933333 | 111 | 0.603563 | [
"Apache-2.0"
] | ahives/HareDu2 | src/HareDu/QueueDeleteCondition.cs | 451 | C# |
// Copyright (c) 2022 TrakHound Inc., All Rights Reserved.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
namespace MTConnect.Devices.DataItems.Samples
{
/// <summary>
/// The measurement of the electrical potential between two points in an electrical circuit in which the current is unidirectional.
/// </summary>
public class VoltageDCDataItem : DataItem
{
public const DataItemCategory CategoryId = DataItemCategory.SAMPLE;
public const string TypeId = "VOLTAGE_DC";
public const string NameId = "voltDC";
public const string DefaultUnits = Devices.Units.VOLT;
public new const string DescriptionText = "The measurement of the electrical potential between two points in an electrical circuit in which the current is unidirectional.";
public override string TypeDescription => DescriptionText;
public override System.Version MinimumVersion => MTConnectVersions.Version16;
public enum SubTypes
{
/// <summary>
/// The measured or reported value of an observation.
/// </summary>
ACTUAL,
/// <summary>
/// Directive value including adjustments such as an offset or overrides.
/// </summary>
COMMANDED,
/// <summary>
/// Directive value without offsets and adjustments.
/// </summary>
PROGRAMMED
}
public VoltageDCDataItem()
{
Category = CategoryId;
Type = TypeId;
Units = DefaultUnits;
}
public VoltageDCDataItem(
string parentId,
SubTypes subType = SubTypes.ACTUAL
)
{
Id = CreateId(parentId, NameId, GetSubTypeId(subType));
Category = CategoryId;
Type = TypeId;
SubType = subType.ToString();
Name = NameId;
Units = DefaultUnits;
}
public override string SubTypeDescription => GetSubTypeDescription(SubType);
public static string GetSubTypeDescription(string subType)
{
var s = subType.ConvertEnum<SubTypes>();
switch (s)
{
case SubTypes.ACTUAL: return "The measured or reported value of an observation.";
case SubTypes.COMMANDED: return "Directive value including adjustments such as an offset or overrides.";
case SubTypes.PROGRAMMED: return "Directive value without offsets and adjustments.";
}
return null;
}
public static string GetSubTypeId(SubTypes subType)
{
switch (subType)
{
case SubTypes.ACTUAL: return "act";
case SubTypes.COMMANDED: return "cmd";
case SubTypes.PROGRAMMED: return "prg";
}
return null;
}
}
}
| 33.566667 | 180 | 0.591857 | [
"Apache-2.0"
] | TrakHound/MTConnect | src/MTConnect.NET-Common/Devices/DataItems/Samples/VoltageDCDataItem.cs | 3,021 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Essensoft.Paylink.Alipay.Domain;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayDataDataservicePropertyBusinesspropertyBatchqueryResponse.
/// </summary>
public class AlipayDataDataservicePropertyBusinesspropertyBatchqueryResponse : AlipayResponse
{
/// <summary>
/// 业务画像标签元信息列表
/// </summary>
[JsonPropertyName("business_propertys")]
public List<BusinessPropertyDTO> BusinessPropertys { get; set; }
}
}
| 30.105263 | 97 | 0.715035 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayDataDataservicePropertyBusinesspropertyBatchqueryResponse.cs | 596 | C# |
using AutoMapper;
using Data.DbObjects;
using Data.Entities.Identity;
using Data.Interfaces;
using Date;
using System.Threading;
using System.Threading.Tasks;
namespace Data.DataProviders
{
public class TenantDataProvider : DataProvider<Tenant>, ITenantDataProvider
{
#region Fields
private readonly ITenantDbObject _tenantDbObject;
#endregion
#region Ctor
public TenantDataProvider(ApplicationDbContext dbContext, IMapper mapper, ITenantDbObject tenantDbObject) : base(dbContext, mapper)
{
_tenantDbObject = tenantDbObject;
}
#endregion
#region Methods
public async Task<Tenant> GetTenantByUserAsync(int userId, CancellationToken cancellationToken)
{
return await _tenantDbObject.GetTenantByUserAsync(userId, cancellationToken);
}
public async Task<TDto> GetTenantByUserAsync<TDto>(int userId, CancellationToken cancellationToken) where TDto : class, IViewModel
{
var entity = await _tenantDbObject.GetTenantByUserAsync(userId, cancellationToken);
return _mapper.Map<TDto>(entity);
}
#endregion
}
} | 27.860465 | 139 | 0.69616 | [
"MIT"
] | mdfaizansarwer/SalootProject | src/Framework/Data/DataProviders/Tenant/TenantDataProvider.cs | 1,200 | C# |
namespace AdventOfCode.Year2020;
[TestClass]
public class Day18Tests
{
[DataTestMethod]
[DataRow(71, "1 + 2 * 3 + 4 * 5 + 6")]
[DataRow(51, "1 + (2 * 3) + (4 * (5 + 6))")]
[DataRow(26, "2 * 3 + (4 * 5)")]
[DataRow(437, "5 + (8 * 3 + 9 + 3 * 4 * 3)")]
[DataRow(12240, "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")]
[DataRow(13632, "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2")]
[DataRow(3, "1\n2\n")]
public void Part1(int expected, string input)
{
Assert.AreEqual(expected, new Day18(input).Part1());
}
[DataTestMethod]
[DataRow(231, "1 + 2 * 3 + 4 * 5 + 6")]
[DataRow(51, "1 + (2 * 3) + (4 * (5 + 6))")]
[DataRow(46, "2 * 3 + (4 * 5)")]
[DataRow(1445, "5 + (8 * 3 + 9 + 3 * 4 * 3)")]
[DataRow(669060, "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")]
[DataRow(23340, "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2")]
[DataRow(3, "1\n2\n")]
public void Part2(int expected, string input)
{
Assert.AreEqual(expected, new Day18(input).Part2());
}
}
| 30.5 | 68 | 0.489754 | [
"MIT"
] | sehra/advent-of-code | AdventOfCode.Tests/Year2020/Day18Tests.cs | 976 | 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\Model\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 Planner Bucket.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class PlannerBucket : Entity
{
///<summary>
/// The PlannerBucket constructor
///</summary>
public PlannerBucket()
{
this.ODataType = "microsoft.graph.plannerBucket";
}
/// <summary>
/// Gets or sets name.
/// Name of the bucket.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "name", Required = Newtonsoft.Json.Required.Default)]
public string Name { get; set; }
/// <summary>
/// Gets or sets plan id.
/// Plan ID to which the bucket belongs.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "planId", Required = Newtonsoft.Json.Required.Default)]
public string PlanId { get; set; }
/// <summary>
/// Gets or sets order hint.
/// Hint used to order items of this type in a list view. The format is defined as outlined here.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "orderHint", Required = Newtonsoft.Json.Required.Default)]
public string OrderHint { get; set; }
/// <summary>
/// Gets or sets tasks.
/// Read-only. Nullable. The collection of tasks in the bucket.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "tasks", Required = Newtonsoft.Json.Required.Default)]
public IPlannerBucketTasksCollectionPage Tasks { get; set; }
}
}
| 37.375 | 153 | 0.596572 | [
"MIT"
] | WhitWaldo/msgraph-sdk-dotnet | src/Microsoft.Graph/Models/Generated/PlannerBucket.cs | 2,392 | C# |
using System.Collections.Generic;
using System.Linq;
using Chapter06.Examples.GlobalFactory2021;
namespace Chapter06.Examples.PerformanceTraps
{
public static class InMemory
{
public static class ChoosingAClass
{
/// <summary>
/// Key difference: IEnumerable
/// </summary>
public static void Slow()
{
var db = new globalfactory2021Context();
IEnumerable<Product> products = db.Products;
var filtered = products
.Where(p => p.Name == DataSeeding.TestProduct1Name)
.ToList();
db.Dispose();
}
/// <summary>
/// Key difference: IQueryable
/// </summary>
public static void Fast()
{
var db = new globalfactory2021Context();
// IQueryable is a data structure still able to translate a C# expression to a SQL query.
// SQL is much faster for lookups than C#.
// 10 times faster.
IQueryable<Product> products = db.Products;
var filtered = products
.Where(p => p.Name == DataSeeding.TestProduct1Name)
.ToList();
db.Dispose();
}
}
public static class MethodChoice
{
/// <summary>
/// Key difference: equals
/// </summary>
public static void Slow()
{
var db = new globalfactory2021Context();
var filtered = db.Products
.Where(p => p.Name.Equals(DataSeeding.TestProduct1Name))
.ToList();
db.Dispose();
}
/// <summary>
/// Key difference: ==
/// </summary>
public static void Fast()
{
var db = new globalfactory2021Context();
// Some expressions were meant for direct C#-To-SQL translation.
// Others, like .equals, were not.
var filtered = db.Products
.Where(p => p.Name == DataSeeding.TestProduct1Name)
.ToList();
db.Dispose();
}
}
}
}
| 29.4 | 105 | 0.470663 | [
"MIT"
] | PacktWorkshops/The-C-Sharp-Workshop | Chapter06/Examples/PerformanceTraps/InMemory.cs | 2,354 | C# |
namespace WebSocketManager.Common
{
public enum MessageType
{
Text,
ClientMethodInvocation,
ConnectionEvent
}
public class Message
{
public MessageType MessageType { get; set; }
public string Data { get; set; }
}
} | 18.666667 | 52 | 0.596429 | [
"MIT"
] | Elfocrash/websocket-manager | src/WebSocketManager.Common/Message.cs | 282 | C# |
/* csvorbis
* Copyright (C) 2000 ymnk, JCraft,Inc.
*
* Written by: 2000 ymnk<ymnk@jcraft.com>
* Ported to C# from JOrbis by: Mark Crichton <crichton@gimp.org>
*
* Thanks go to the JOrbis team, for licencing the code under the
* LGPL, making my job a lot easier.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
using System;
using csogg;
using csvorbis;
namespace csvorbis
{
public class DspState
{
static float M_PI=3.1415926539f;
static int VI_TRANSFORMB=1;
static int VI_WINDOWB=1;
internal int analysisp;
internal Info vi;
internal int modebits;
float[][] pcm;
//float[][] pcmret;
int pcm_storage;
int pcm_current;
int pcm_returned;
float[] multipliers;
int envelope_storage;
int envelope_current;
int eofflag;
int lW;
int W;
int nW;
int centerW;
long granulepos;
public long sequence;
long glue_bits;
long time_bits;
long floor_bits;
long res_bits;
// local lookup storage
//!! Envelope ve=new Envelope(); // envelope
//float **window[2][2][2]; // block, leadin, leadout, type
internal float[][][][][] wnd; // block, leadin, leadout, type
//vorbis_look_transform **transform[2]; // block, type
internal Object[][] transform;
internal CodeBook[] fullbooks;
// backend lookups are tied to the mode, not the backend or naked mapping
internal Object[] mode;
// local storage, only used on the encoding side. This way the
// application does not need to worry about freeing some packets'
// memory and not others'; packet storage is always tracked.
// Cleared next call to a _dsp_ function
byte[] header;
byte[] header1;
byte[] header2;
public DspState()
{
transform=new Object[2][];
wnd=new float[2][][][][];
wnd[0]=new float[2][][][];
wnd[0][0]=new float[2][][];
wnd[0][1]=new float[2][][];
wnd[0][0][0]=new float[2][];
wnd[0][0][1]=new float[2][];
wnd[0][1][0]=new float[2][];
wnd[0][1][1]=new float[2][];
wnd[1]=new float[2][][][];
wnd[1][0]=new float[2][][];
wnd[1][1]=new float[2][][];
wnd[1][0][0]=new float[2][];
wnd[1][0][1]=new float[2][];
wnd[1][1][0]=new float[2][];
wnd[1][1][1]=new float[2][];
}
private static int ilog2(int v)
{
int ret=0;
while(v>1)
{
ret++;
v = (int)((uint)v >> 1);
}
return(ret);
}
internal static float[] window(int type, int wnd, int left, int right)
{
float[] ret=new float[wnd];
switch(type)
{
case 0:
// The 'vorbis window' (window 0) is sin(sin(x)*sin(x)*2pi)
{
int leftbegin=wnd/4-left/2;
int rightbegin=wnd-wnd/4-right/2;
for(int i=0;i<left;i++)
{
float x=(float)((i+.5)/left*M_PI/2.0);
x=(float)Math.Sin(x);
x*=x;
x*=(float)(M_PI/2.0);
x=(float)Math.Sin(x);
ret[i+leftbegin]=x;
}
for(int i=leftbegin+left;i<rightbegin;i++)
{
ret[i]=1.0f;
}
for(int i=0;i<right;i++)
{
float x=(float)((right-i-.5)/right*M_PI/2.0);
x=(float)Math.Sin(x);
x*=x;
x*=(float)(M_PI/2.0);
x=(float)Math.Sin(x);
ret[i+rightbegin]=x;
}
}
break;
default:
//free(ret);
return(null);
}
return(ret);
}
// Analysis side code, but directly related to blocking. Thus it's
// here and not in analysis.c (which is for analysis transforms only).
// The init is here because some of it is shared
int init(Info vi, bool encp)
{
//memset(v,0,sizeof(vorbis_dsp_state));
this.vi=vi;
modebits=ilog2(vi.modes);
transform[0]=new Object[VI_TRANSFORMB];
transform[1]=new Object[VI_TRANSFORMB];
// MDCT is tranform 0
transform[0][0]=new Mdct();
transform[1][0]=new Mdct();
((Mdct)transform[0][0]).init(vi.blocksizes[0]);
((Mdct)transform[1][0]).init(vi.blocksizes[1]);
wnd[0][0][0]=new float[VI_WINDOWB][];
wnd[0][0][1]=wnd[0][0][0];
wnd[0][1][0]=wnd[0][0][0];
wnd[0][1][1]=wnd[0][0][0];
wnd[1][0][0]=new float[VI_WINDOWB][];
wnd[1][0][1]=new float[VI_WINDOWB][];
wnd[1][1][0]=new float[VI_WINDOWB][];
wnd[1][1][1]=new float[VI_WINDOWB][];
for(int i=0;i<VI_WINDOWB;i++)
{
wnd[0][0][0][i]=
window(i,vi.blocksizes[0],vi.blocksizes[0]/2,vi.blocksizes[0]/2);
wnd[1][0][0][i]=
window(i,vi.blocksizes[1],vi.blocksizes[0]/2,vi.blocksizes[0]/2);
wnd[1][0][1][i]=
window(i,vi.blocksizes[1],vi.blocksizes[0]/2,vi.blocksizes[1]/2);
wnd[1][1][0][i]=
window(i,vi.blocksizes[1],vi.blocksizes[1]/2,vi.blocksizes[0]/2);
wnd[1][1][1][i]=
window(i,vi.blocksizes[1],vi.blocksizes[1]/2,vi.blocksizes[1]/2);
}
// if(encp){ // encode/decode differ here
// // finish the codebooks
// fullbooks=new CodeBook[vi.books];
// for(int i=0;i<vi.books;i++){
// fullbooks[i]=new CodeBook();
// fullbooks[i].init_encode(vi.book_param[i]);
// }
// analysisp=1;
// }
// else{
// finish the codebooks
fullbooks=new CodeBook[vi.books];
for(int i=0;i<vi.books;i++)
{
fullbooks[i]=new CodeBook();
fullbooks[i].init_decode(vi.book_param[i]);
}
// }
// initialize the storage vectors to a decent size greater than the
// minimum
pcm_storage=8192; // we'll assume later that we have
// a minimum of twice the blocksize of
// accumulated samples in analysis
pcm=new float[vi.channels][];
//pcmret=new float[vi.channels][];
{
for(int i=0;i<vi.channels;i++)
{
pcm[i]=new float[pcm_storage];
}
}
// all 1 (large block) or 0 (small block)
// explicitly set for the sake of clarity
lW=0; // previous window size
W=0; // current window size
// all vector indexes; multiples of samples_per_envelope_step
centerW=vi.blocksizes[1]/2;
pcm_current=centerW;
// initialize all the mapping/backend lookups
mode=new Object[vi.modes];
for(int i=0;i<vi.modes;i++)
{
int mapnum=vi.mode_param[i].mapping;
int maptype=vi.map_type[mapnum];
mode[i]=FuncMapping.mapping_P[maptype].look(this,vi.mode_param[i],
vi.map_param[mapnum]);
}
return(0);
}
public int synthesis_init(Info vi)
{
init(vi, false);
// Adjust centerW to allow an easier mechanism for determining output
pcm_returned=centerW;
centerW-= vi.blocksizes[W]/4+vi.blocksizes[lW]/4;
granulepos=-1;
sequence=-1;
return(0);
}
DspState(Info vi) : this()
{
init(vi, false);
// Adjust centerW to allow an easier mechanism for determining output
pcm_returned=centerW;
centerW-= vi.blocksizes[W]/4+vi.blocksizes[lW]/4;
granulepos=-1;
sequence=-1;
}
// Unike in analysis, the window is only partially applied for each
// block. The time domain envelope is not yet handled at the point of
// calling (as it relies on the previous block).
public int synthesis_blockin(Block vb)
{
// Shift out any PCM/multipliers that we returned previously
// centerW is currently the center of the last block added
if(centerW>vi.blocksizes[1]/2 && pcm_returned>8192)
{
// don't shift too much; we need to have a minimum PCM buffer of
// 1/2 long block
int shiftPCM=centerW-vi.blocksizes[1]/2;
shiftPCM=(pcm_returned<shiftPCM?pcm_returned:shiftPCM);
pcm_current-=shiftPCM;
centerW-=shiftPCM;
pcm_returned-=shiftPCM;
if(shiftPCM!=0)
{
for(int i=0;i<vi.channels;i++)
{
Array.Copy(pcm[i], shiftPCM, pcm[i], 0, pcm_current);
}
}
}
lW=W;
W=vb.W;
nW=-1;
glue_bits+=vb.glue_bits;
time_bits+=vb.time_bits;
floor_bits+=vb.floor_bits;
res_bits+=vb.res_bits;
if(sequence+1 != vb.sequence)granulepos=-1; // out of sequence; lose count
sequence=vb.sequence;
{
int sizeW=vi.blocksizes[W];
int _centerW=centerW+vi.blocksizes[lW]/4+sizeW/4;
int beginW=_centerW-sizeW/2;
int endW=beginW+sizeW;
int beginSl=0;
int endSl=0;
// Do we have enough PCM/mult storage for the block?
if(endW>pcm_storage)
{
// expand the storage
pcm_storage=endW+vi.blocksizes[1];
for(int i=0;i<vi.channels;i++)
{
float[] foo=new float[pcm_storage];
Array.Copy(pcm[i], 0, foo, 0, pcm[i].Length);
pcm[i]=foo;
}
}
// overlap/add PCM
switch(W)
{
case 0:
beginSl=0;
endSl=vi.blocksizes[0]/2;
break;
case 1:
beginSl=vi.blocksizes[1]/4-vi.blocksizes[lW]/4;
endSl=beginSl+vi.blocksizes[lW]/2;
break;
}
for(int j=0;j<vi.channels;j++)
{
int _pcm=beginW;
// the overlap/add section
int i=0;
for(i=beginSl;i<endSl;i++)
{
pcm[j][_pcm+i]+=vb.pcm[j][i];
}
// the remaining section
for(;i<sizeW;i++)
{
pcm[j][_pcm+i]=vb.pcm[j][i];
}
}
// track the frame number... This is for convenience, but also
// making sure our last packet doesn't end with added padding. If
// the last packet is partial, the number of samples we'll have to
// return will be past the vb->granulepos.
//
// This is not foolproof! It will be confused if we begin
// decoding at the last page after a seek or hole. In that case,
// we don't have a starting point to judge where the last frame
// is. For this reason, vorbisfile will always try to make sure
// it reads the last two marked pages in proper sequence
if(granulepos==-1)
{
granulepos=vb.granulepos;
}
else
{
granulepos+=(_centerW-centerW);
if(vb.granulepos!=-1 && granulepos!=vb.granulepos)
{
if(granulepos>vb.granulepos && vb.eofflag!=0)
{
// partial last frame. Strip the padding off
_centerW = _centerW - (int)(granulepos-vb.granulepos);
}// else{ Shouldn't happen *unless* the bitstream is out of
// spec. Either way, believe the bitstream }
granulepos=vb.granulepos;
}
}
// Update, cleanup
centerW=_centerW;
pcm_current=endW;
if(vb.eofflag!=0)eofflag=1;
}
return(0);
}
// pcm==NULL indicates we just want the pending samples, no more
public int synthesis_pcmout(float[][][] _pcm, int[] index)
{
if(pcm_returned<centerW)
{
if(_pcm!=null)
{
for(int i=0;i<vi.channels;i++)
{
// pcmret[i]=pcm[i]+v.pcm_returned;
//!!!!!!!!
index[i]=pcm_returned;
}
_pcm[0]=pcm;
}
return(centerW-pcm_returned);
}
return(0);
}
public int synthesis_read(int bytes)
{
if(bytes!=0 && pcm_returned+bytes>centerW)return(-1);
pcm_returned+=bytes;
return(0);
}
public void clear()
{
}
}
} | 25.34382 | 79 | 0.614382 | [
"MIT"
] | Alternity156/SongBrowser | AudicaMod/csvorbis/DspState.cs | 11,278 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20200301.Inputs
{
/// <summary>
/// IP configuration for virtual network gateway.
/// </summary>
public sealed class VirtualNetworkGatewayIPConfigurationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The private IP address allocation method.
/// </summary>
[Input("privateIPAllocationMethod")]
public InputUnion<string, Pulumi.AzureNative.Network.V20200301.IPAllocationMethod>? PrivateIPAllocationMethod { get; set; }
/// <summary>
/// The reference to the public IP resource.
/// </summary>
[Input("publicIPAddress")]
public Input<Inputs.SubResourceArgs>? PublicIPAddress { get; set; }
/// <summary>
/// The reference to the subnet resource.
/// </summary>
[Input("subnet")]
public Input<Inputs.SubResourceArgs>? Subnet { get; set; }
public VirtualNetworkGatewayIPConfigurationArgs()
{
}
}
}
| 31.773585 | 131 | 0.619952 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200301/Inputs/VirtualNetworkGatewayIPConfigurationArgs.cs | 1,684 | C# |
using BEPUphysics.CollisionShapes.ConvexShapes;
using BEPUutilities;
using BEPUphysics.Settings;
using RigidTransform = BEPUutilities.RigidTransform;
namespace BEPUphysics.CollisionTests.CollisionAlgorithms.GJK
{
///<summary>
/// Helper class containing various tests based on GJK.
///</summary>
public static class GJKToolbox
{
/// <summary>
/// Maximum number of iterations the GJK algorithm will do. If the iterations exceed this number, the system will immediately quit and return whatever information it has at the time.
/// </summary>
public static int MaximumGJKIterations = 15;
/// <summary>
/// Defines how many iterations are required to consider a GJK attempt to be 'probably stuck' and proceed with protective measures.
/// </summary>
public static int HighGJKIterations = 8;
///<summary>
/// Tests if the pair is intersecting.
///</summary>
///<param name="shapeA">First shape of the pair.</param>
///<param name="shapeB">Second shape of the pair.</param>
///<param name="transformA">Transform to apply to the first shape.</param>
///<param name="transformB">Transform to apply to the second shape.</param>
///<returns>Whether or not the shapes are intersecting.</returns>
public static bool AreShapesIntersecting(ConvexShape shapeA, ConvexShape shapeB, ref RigidTransform transformA, ref RigidTransform transformB)
{
//Zero isn't a very good guess! But it's a cheap guess.
System.Numerics.Vector3 separatingAxis = Toolbox.ZeroVector;
return AreShapesIntersecting(shapeA, shapeB, ref transformA, ref transformB, ref separatingAxis);
}
///<summary>
/// Tests if the pair is intersecting.
///</summary>
///<param name="shapeA">First shape of the pair.</param>
///<param name="shapeB">Second shape of the pair.</param>
///<param name="transformA">Transform to apply to the first shape.</param>
///<param name="transformB">Transform to apply to the second shape.</param>
///<param name="localSeparatingAxis">Warmstartable separating axis used by the method to quickly early-out if possible. Updated to the latest separating axis after each run.</param>
///<returns>Whether or not the objects were intersecting.</returns>
public static bool AreShapesIntersecting(ConvexShape shapeA, ConvexShape shapeB, ref RigidTransform transformA, ref RigidTransform transformB,
ref System.Numerics.Vector3 localSeparatingAxis)
{
RigidTransform localtransformB;
MinkowskiToolbox.GetLocalTransform(ref transformA, ref transformB, out localtransformB);
//Warm start the simplex.
var simplex = new SimpleSimplex();
System.Numerics.Vector3 extremePoint;
MinkowskiToolbox.GetLocalMinkowskiExtremePoint(shapeA, shapeB, ref localSeparatingAxis, ref localtransformB, out extremePoint);
simplex.AddNewSimplexPoint(ref extremePoint);
System.Numerics.Vector3 closestPoint;
int count = 0;
while (count++ < MaximumGJKIterations)
{
if (simplex.GetPointClosestToOrigin(out closestPoint) || //Also reduces the simplex.
closestPoint.LengthSquared() <= simplex.GetErrorTolerance() * Toolbox.BigEpsilon)
{
//Intersecting, or so close to it that it will be difficult/expensive to figure out the separation.
return true;
}
//Use the closest point as a direction.
System.Numerics.Vector3 direction;
Vector3Ex.Negate(ref closestPoint, out direction);
MinkowskiToolbox.GetLocalMinkowskiExtremePoint(shapeA, shapeB, ref direction, ref localtransformB, out extremePoint);
//Since this is a boolean test, we don't need to refine the simplex if it becomes apparent that we cannot reach the origin.
//If the most extreme point at any given time does not go past the origin, then we can quit immediately.
float dot;
Vector3Ex.Dot(ref extremePoint, ref closestPoint, out dot); //extreme point dotted against the direction pointing backwards towards the CSO.
if (dot > 0)
{
// If it's positive, that means that the direction pointing towards the origin produced an extreme point 'in front of' the origin, eliminating the possibility of any intersection.
localSeparatingAxis = direction;
return false;
}
simplex.AddNewSimplexPoint(ref extremePoint);
}
return false;
}
///<summary>
/// Gets the closest points between the shapes.
///</summary>
///<param name="shapeA">First shape of the pair.</param>
///<param name="shapeB">Second shape of the pair.</param>
///<param name="transformA">Transform to apply to the first shape.</param>
///<param name="transformB">Transform to apply to the second shape.</param>
///<param name="closestPointA">Closest point on the first shape to the second shape.</param>
///<param name="closestPointB">Closest point on the second shape to the first shape.</param>
///<returns>Whether or not the objects were intersecting. If they are intersecting, then the closest points cannot be identified.</returns>
public static bool GetClosestPoints(ConvexShape shapeA, ConvexShape shapeB, ref RigidTransform transformA, ref RigidTransform transformB,
out System.Numerics.Vector3 closestPointA, out System.Numerics.Vector3 closestPointB)
{
//The cached simplex stores locations that are local to the shapes. A fairly decent initial state is between the centroids of the objects.
//In local space, the centroids are at the origins.
RigidTransform localtransformB;
MinkowskiToolbox.GetLocalTransform(ref transformA, ref transformB, out localtransformB);
var simplex = new CachedSimplex {State = SimplexState.Point};
// new CachedSimplex(shapeA, shapeB, ref localtransformB);
bool toReturn = GetClosestPoints(shapeA, shapeB, ref localtransformB, ref simplex, out closestPointA, out closestPointB);
RigidTransform.Transform(ref closestPointA, ref transformA, out closestPointA);
RigidTransform.Transform(ref closestPointB, ref transformA, out closestPointB);
return toReturn;
}
///<summary>
/// Gets the closest points between the shapes.
///</summary>
///<param name="shapeA">First shape of the pair.</param>
///<param name="shapeB">Second shape of the pair.</param>
///<param name="transformA">Transform to apply to the first shape.</param>
///<param name="transformB">Transform to apply to the second shape.</param>
/// <param name="cachedSimplex">Simplex from a previous updated used to warmstart the current attempt. Updated after each run.</param>
///<param name="closestPointA">Closest point on the first shape to the second shape.</param>
///<param name="closestPointB">Closest point on the second shape to the first shape.</param>
///<returns>Whether or not the objects were intersecting. If they are intersecting, then the closest points cannot be identified.</returns>
public static bool GetClosestPoints(ConvexShape shapeA, ConvexShape shapeB, ref RigidTransform transformA, ref RigidTransform transformB,
ref CachedSimplex cachedSimplex, out System.Numerics.Vector3 closestPointA, out System.Numerics.Vector3 closestPointB)
{
RigidTransform localtransformB;
MinkowskiToolbox.GetLocalTransform(ref transformA, ref transformB, out localtransformB);
bool toReturn = GetClosestPoints(shapeA, shapeB, ref localtransformB, ref cachedSimplex, out closestPointA, out closestPointB);
RigidTransform.Transform(ref closestPointA, ref transformA, out closestPointA);
RigidTransform.Transform(ref closestPointB, ref transformA, out closestPointB);
return toReturn;
}
private static bool GetClosestPoints(ConvexShape shapeA, ConvexShape shapeB, ref RigidTransform localTransformB,
ref CachedSimplex cachedSimplex, out System.Numerics.Vector3 localClosestPointA, out System.Numerics.Vector3 localClosestPointB)
{
var simplex = new PairSimplex(ref cachedSimplex, ref localTransformB);
System.Numerics.Vector3 closestPoint;
int count = 0;
while (true)
{
if (simplex.GetPointClosestToOrigin(out closestPoint) || //Also reduces the simplex and computes barycentric coordinates if necessary.
closestPoint.LengthSquared() <= Toolbox.Epsilon * simplex.errorTolerance)
{
//Intersecting.
localClosestPointA = Toolbox.ZeroVector;
localClosestPointB = Toolbox.ZeroVector;
simplex.UpdateCachedSimplex(ref cachedSimplex);
return true;
}
if (++count > MaximumGJKIterations)
break; //Must break BEFORE a new vertex is added if we're over the iteration limit. This guarantees final simplex is not a tetrahedron.
if (simplex.GetNewSimplexPoint(shapeA, shapeB, count, ref closestPoint))
{
//No progress towards origin, not intersecting.
break;
}
}
//Compute closest points from the contributing simplexes and barycentric coordinates
simplex.GetClosestPoints(out localClosestPointA, out localClosestPointB);
//simplex.VerifyContributions();
//if (Vector3Ex.Distance(localClosestPointA - localClosestPointB, closestPoint) > .00001f)
// Debug.WriteLine("break.");
simplex.UpdateCachedSimplex(ref cachedSimplex);
return false;
}
//TODO: Consider changing the termination epsilons on these casts. Epsilon * Modifier is okay, but there might be better options.
///<summary>
/// Tests a ray against a convex shape.
///</summary>
///<param name="ray">Ray to test against the shape.</param>
///<param name="shape">Shape to test.</param>
///<param name="shapeTransform">Transform to apply to the shape for the test.</param>
///<param name="maximumLength">Maximum length of the ray in units of the ray direction's length.</param>
///<param name="hit">Hit data of the ray cast, if any.</param>
///<returns>Whether or not the ray hit the shape.</returns>
public static bool RayCast(Ray ray, ConvexShape shape, ref RigidTransform shapeTransform, float maximumLength,
out RayHit hit)
{
//Transform the ray into the object's local space.
Vector3Ex.Subtract(ref ray.Position, ref shapeTransform.Position, out ray.Position);
System.Numerics.Quaternion conjugate;
QuaternionEx.Conjugate(ref shapeTransform.Orientation, out conjugate);
QuaternionEx.Transform(ref ray.Position, ref conjugate, out ray.Position);
QuaternionEx.Transform(ref ray.Direction, ref conjugate, out ray.Direction);
System.Numerics.Vector3 extremePointToRayOrigin, extremePoint;
hit.T = 0;
hit.Location = ray.Position;
hit.Normal = Toolbox.ZeroVector;
System.Numerics.Vector3 closestOffset = hit.Location;
RaySimplex simplex = new RaySimplex();
float vw, closestPointDotDirection;
int count = 0;
//This epsilon has a significant impact on performance and accuracy. Changing it to use BigEpsilon instead increases speed by around 30-40% usually, but jigging is more evident.
while (closestOffset.LengthSquared() >= Toolbox.Epsilon * simplex.GetErrorTolerance(ref ray.Position))
{
if (++count > MaximumGJKIterations)
{
//It's taken too long to find a hit. Numerical problems are probable; quit.
hit = new RayHit();
return false;
}
shape.GetLocalExtremePoint(closestOffset, out extremePoint);
Vector3Ex.Subtract(ref hit.Location, ref extremePoint, out extremePointToRayOrigin);
Vector3Ex.Dot(ref closestOffset, ref extremePointToRayOrigin, out vw);
//If the closest offset and the extreme point->ray origin direction point the same way,
//then we might be able to conservatively advance the point towards the surface.
if (vw > 0)
{
Vector3Ex.Dot(ref closestOffset, ref ray.Direction, out closestPointDotDirection);
if (closestPointDotDirection >= 0)
{
hit = new RayHit();
return false;
}
hit.T = hit.T - vw / closestPointDotDirection;
if (hit.T > maximumLength)
{
//If we've gone beyond where the ray can reach, there's obviously no hit.
hit = new RayHit();
return false;
}
//Shift the ray up.
Vector3Ex.Multiply(ref ray.Direction, hit.T, out hit.Location);
Vector3Ex.Add(ref hit.Location, ref ray.Position, out hit.Location);
hit.Normal = closestOffset;
}
RaySimplex shiftedSimplex;
simplex.AddNewSimplexPoint(ref extremePoint, ref hit.Location, out shiftedSimplex);
//Compute the offset from the simplex surface to the origin.
shiftedSimplex.GetPointClosestToOrigin(ref simplex, out closestOffset);
}
//Transform the hit data into world space.
QuaternionEx.Transform(ref hit.Normal, ref shapeTransform.Orientation, out hit.Normal);
QuaternionEx.Transform(ref hit.Location, ref shapeTransform.Orientation, out hit.Location);
Vector3Ex.Add(ref hit.Location, ref shapeTransform.Position, out hit.Location);
return true;
}
///<summary>
/// Sweeps a shape against another shape using a given sweep vector.
///</summary>
///<param name="sweptShape">Shape to sweep.</param>
///<param name="target">Shape being swept against.</param>
///<param name="sweep">Sweep vector for the sweptShape.</param>
///<param name="startingSweptTransform">Starting transform of the sweptShape.</param>
///<param name="targetTransform">Transform to apply to the target shape.</param>
///<param name="hit">Hit data of the sweep test, if any.</param>
///<returns>Whether or not the swept shape hit the other shape.</returns>
public static bool ConvexCast(ConvexShape sweptShape, ConvexShape target, ref System.Numerics.Vector3 sweep, ref RigidTransform startingSweptTransform, ref RigidTransform targetTransform,
out RayHit hit)
{
return ConvexCast(sweptShape, target, ref sweep, ref Toolbox.ZeroVector, ref startingSweptTransform, ref targetTransform, out hit);
}
///<summary>
/// Sweeps two shapes against another.
///</summary>
///<param name="shapeA">First shape being swept.</param>
///<param name="shapeB">Second shape being swept.</param>
///<param name="sweepA">Sweep vector for the first shape.</param>
///<param name="sweepB">Sweep vector for the second shape.</param>
///<param name="transformA">Transform to apply to the first shape.</param>
///<param name="transformB">Transform to apply to the second shape.</param>
///<param name="hit">Hit data of the sweep test, if any.</param>
///<returns>Whether or not the swept shapes hit each other..</returns>
public static bool ConvexCast(ConvexShape shapeA, ConvexShape shapeB, ref System.Numerics.Vector3 sweepA, ref System.Numerics.Vector3 sweepB, ref RigidTransform transformA, ref RigidTransform transformB,
out RayHit hit)
{
//Put the velocity into shapeA's local space.
System.Numerics.Vector3 velocityWorld;
Vector3Ex.Subtract(ref sweepB, ref sweepA, out velocityWorld);
System.Numerics.Quaternion conjugateOrientationA;
QuaternionEx.Conjugate(ref transformA.Orientation, out conjugateOrientationA);
System.Numerics.Vector3 rayDirection;
QuaternionEx.Transform(ref velocityWorld, ref conjugateOrientationA, out rayDirection);
//Transform b into a's local space.
RigidTransform localTransformB;
QuaternionEx.Concatenate(ref transformB.Orientation, ref conjugateOrientationA, out localTransformB.Orientation);
Vector3Ex.Subtract(ref transformB.Position, ref transformA.Position, out localTransformB.Position);
QuaternionEx.Transform(ref localTransformB.Position, ref conjugateOrientationA, out localTransformB.Position);
System.Numerics.Vector3 w, p;
hit.T = 0;
hit.Location = System.Numerics.Vector3.Zero; //The ray starts at the origin.
hit.Normal = Toolbox.ZeroVector;
System.Numerics.Vector3 v = hit.Location;
RaySimplex simplex = new RaySimplex();
float vw, vdir;
int count = 0;
do
{
if (++count > MaximumGJKIterations)
{
//It's taken too long to find a hit. Numerical problems are probable; quit.
hit = new RayHit();
return false;
}
MinkowskiToolbox.GetLocalMinkowskiExtremePoint(shapeA, shapeB, ref v, ref localTransformB, out p);
Vector3Ex.Subtract(ref hit.Location, ref p, out w);
Vector3Ex.Dot(ref v, ref w, out vw);
if (vw > 0)
{
Vector3Ex.Dot(ref v, ref rayDirection, out vdir);
if (vdir >= 0)
{
hit = new RayHit();
return false;
}
hit.T = hit.T - vw / vdir;
if (hit.T > 1)
{
//If we've gone beyond where the ray can reach, there's obviously no hit.
hit = new RayHit();
return false;
}
//Shift the ray up.
Vector3Ex.Multiply(ref rayDirection, hit.T, out hit.Location);
//The ray origin is the origin! Don't need to add any ray position.
hit.Normal = v;
}
RaySimplex shiftedSimplex;
simplex.AddNewSimplexPoint(ref p, ref hit.Location, out shiftedSimplex);
shiftedSimplex.GetPointClosestToOrigin(ref simplex, out v);
//Could measure the progress of the ray. If it's too little, could early out.
//Not used by default since it's biased towards precision over performance.
} while (v.LengthSquared() >= Toolbox.Epsilon * simplex.GetErrorTolerance(ref Toolbox.ZeroVector));
//This epsilon has a significant impact on performance and accuracy. Changing it to use BigEpsilon instead increases speed by around 30-40% usually, but jigging is more evident.
//Transform the hit data into world space.
QuaternionEx.Transform(ref hit.Normal, ref transformA.Orientation, out hit.Normal);
Vector3Ex.Multiply(ref velocityWorld, hit.T, out hit.Location);
Vector3Ex.Add(ref hit.Location, ref transformA.Position, out hit.Location);
return true;
}
///<summary>
/// Casts a fat (sphere expanded) ray against the shape.
///</summary>
///<param name="ray">Ray to test against the shape.</param>
///<param name="radius">Radius of the ray.</param>
///<param name="shape">Shape to test against.</param>
///<param name="shapeTransform">Transform to apply to the shape for the test.</param>
///<param name="maximumLength">Maximum length of the ray in units of the ray direction's length.</param>
///<param name="hit">Hit data of the sphere cast, if any.</param>
///<returns>Whether or not the sphere cast hit the shape.</returns>
public static bool SphereCast(Ray ray, float radius, ConvexShape shape, ref RigidTransform shapeTransform, float maximumLength,
out RayHit hit)
{
//Transform the ray into the object's local space.
Vector3Ex.Subtract(ref ray.Position, ref shapeTransform.Position, out ray.Position);
System.Numerics.Quaternion conjugate;
QuaternionEx.Conjugate(ref shapeTransform.Orientation, out conjugate);
QuaternionEx.Transform(ref ray.Position, ref conjugate, out ray.Position);
QuaternionEx.Transform(ref ray.Direction, ref conjugate, out ray.Direction);
System.Numerics.Vector3 w, p;
hit.T = 0;
hit.Location = ray.Position;
hit.Normal = Toolbox.ZeroVector;
System.Numerics.Vector3 v = hit.Location;
RaySimplex simplex = new RaySimplex();
float vw, vdir;
int count = 0;
//This epsilon has a significant impact on performance and accuracy. Changing it to use BigEpsilon instead increases speed by around 30-40% usually, but jigging is more evident.
while (v.LengthSquared() >= Toolbox.Epsilon * simplex.GetErrorTolerance(ref ray.Position))
{
if (++count > MaximumGJKIterations)
{
//It's taken too long to find a hit. Numerical problems are probable; quit.
hit = new RayHit();
return false;
}
shape.GetLocalExtremePointWithoutMargin(ref v, out p);
System.Numerics.Vector3 contribution;
MinkowskiToolbox.ExpandMinkowskiSum(shape.collisionMargin, radius, ref v, out contribution);
Vector3Ex.Add(ref p, ref contribution, out p);
Vector3Ex.Subtract(ref hit.Location, ref p, out w);
Vector3Ex.Dot(ref v, ref w, out vw);
if (vw > 0)
{
Vector3Ex.Dot(ref v, ref ray.Direction, out vdir);
hit.T = hit.T - vw / vdir;
if (vdir >= 0)
{
//We would have to back up!
return false;
}
if (hit.T > maximumLength)
{
//If we've gone beyond where the ray can reach, there's obviously no hit.
return false;
}
//Shift the ray up.
Vector3Ex.Multiply(ref ray.Direction, hit.T, out hit.Location);
Vector3Ex.Add(ref hit.Location, ref ray.Position, out hit.Location);
hit.Normal = v;
}
RaySimplex shiftedSimplex;
simplex.AddNewSimplexPoint(ref p, ref hit.Location, out shiftedSimplex);
shiftedSimplex.GetPointClosestToOrigin(ref simplex, out v);
}
//Transform the hit data into world space.
QuaternionEx.Transform(ref hit.Normal, ref shapeTransform.Orientation, out hit.Normal);
QuaternionEx.Transform(ref hit.Location, ref shapeTransform.Orientation, out hit.Location);
Vector3Ex.Add(ref hit.Location, ref shapeTransform.Position, out hit.Location);
return true;
}
///<summary>
/// Casts a fat (sphere expanded) ray against the shape. If the raycast appears to be stuck in the shape, the cast will be attempted
/// with a smaller ray (scaled by the MotionSettings.CoreShapeScaling each time).
///</summary>
///<param name="ray">Ray to test against the shape.</param>
///<param name="radius">Radius of the ray.</param>
///<param name="target">Shape to test against.</param>
///<param name="shapeTransform">Transform to apply to the shape for the test.</param>
///<param name="maximumLength">Maximum length of the ray in units of the ray direction's length.</param>
///<param name="hit">Hit data of the sphere cast, if any.</param>
///<returns>Whether or not the sphere cast hit the shape.</returns>
public static bool CCDSphereCast(Ray ray, float radius, ConvexShape target, ref RigidTransform shapeTransform, float maximumLength,
out RayHit hit)
{
int iterations = 0;
while (true)
{
if (GJKToolbox.SphereCast(ray, radius, target, ref shapeTransform, maximumLength, out hit) &&
hit.T > 0)
{
//The ray cast isn't embedded in the shape, and it's less than maximum length away!
return true;
}
if (hit.T > maximumLength || hit.T < 0)
return false; //Failure showed it was too far, or behind.
radius *= MotionSettings.CoreShapeScaling;
iterations++;
if (iterations > 3) //Limit could be configurable.
{
//It's iterated too much, let's just do a last ditch attempt using a raycast and hope that can help.
return GJKToolbox.RayCast(ray, target, ref shapeTransform, maximumLength, out hit) && hit.T > 0;
}
}
}
}
}
| 53.809619 | 211 | 0.606234 | [
"MIT"
] | Ramobo/ge | src/BEPU/BEPUphysics/CollisionTests/CollisionAlgorithms/GJK/GJKToolbox.cs | 26,853 | C# |
using Cocos2D;
namespace tests
{
public class SpriteDemo : CCLayer
{
private string s_pPathB1 = "Images/b1";
private string s_pPathB2 = "Images/b2";
private string s_pPathF1 = "Images/f1";
private string s_pPathF2 = "Images/f2";
private string s_pPathR1 = "Images/r1";
private string s_pPathR2 = "Images/r2";
public virtual string title()
{
return "ProgressActionsTest";
}
public virtual string subtitle()
{
return "";
}
public override void OnEnter()
{
base.OnEnter();
CCSize s = CCDirector.SharedDirector.WinSize;
CCLabelTTF label = new CCLabelTTF(title(), "arial", 18);
AddChild(label, 1);
label.Position = new CCPoint(s.Width / 2, s.Height - 50);
string strSubtitle = subtitle();
if (strSubtitle != null)
{
CCLabelTTF l = new CCLabelTTF(strSubtitle, "arial", 22);
AddChild(l, 1);
l.Position = new CCPoint(s.Width / 2, s.Height - 80);
}
CCMenuItemImage item1 = new CCMenuItemImage(s_pPathB1, s_pPathB2, backCallback);
CCMenuItemImage item2 = new CCMenuItemImage(s_pPathR1, s_pPathR2, restartCallback);
CCMenuItemImage item3 = new CCMenuItemImage(s_pPathF1, s_pPathF2, nextCallback);
CCMenu menu = new CCMenu(item1, item2, item3);
menu.Position = new CCPoint(0, 0);
item1.Position = new CCPoint(s.Width / 2 - 100, 30);
item2.Position = new CCPoint(s.Width / 2, 30);
item3.Position = new CCPoint(s.Width / 2 + 100, 30);
AddChild(menu, 1);
CCLayerColor background = new CCLayerColor(new CCColor4B(255,0,0,255));
AddChild(background, -10);
}
public void restartCallback(object pSender)
{
CCScene s = new ProgressActionsTestScene();
s.AddChild(ProgressActionsTestScene.restartAction());
CCDirector.SharedDirector.ReplaceScene(s);
//s->release();
}
public void nextCallback(object pSender)
{
CCScene s = new ProgressActionsTestScene();
s.AddChild(ProgressActionsTestScene.nextAction());
CCDirector.SharedDirector.ReplaceScene(s);
//s->release();
}
public void backCallback(object pSender)
{
CCScene s = new ProgressActionsTestScene();
s.AddChild(ProgressActionsTestScene.backAction());
CCDirector.SharedDirector.ReplaceScene(s);
//s->release();
}
}
} | 32.416667 | 95 | 0.568858 | [
"MIT"
] | Karunp/cocos2d-xna | tests/tests/classes/tests/ActionsProgressTest/SpriteDemo.cs | 2,723 | C# |
using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Abp.Extensions;
using ABD.ADSearches.Dto;
using ABD.Domain.Dtos;
namespace ABD
{
public static class ADQueryBuilder
{
private static ADSearchInput SearchInput;
public static ADQueries GetADSearchQueries(ADSearchInput input)
{
SearchInput = input;
var queries = new ADQueries();
try
{
var agencyQuery = BuildSQL(true);
queries.AgencyQuery = agencyQuery;
queries.ADCountQuery = GetRecordCountQuery(agencyQuery);
var sqlQuery = BuildSQL(false);
queries.SQLQuery = sqlQuery.Trim().Replace("SELECT * FROM AgencyDB",
"SELECT * FROM ContactsDB INNER JOIN AgencyDB ON ContactsDB.ACCOUNTID = AgencyDB.ACCOUNTID");
queries.ADContactsCountQuery = GetContactsCountQuery(sqlQuery,
"SELECT count(ContactsDB.Account) FROM ContactsDB INNER JOIN AgencyDB ON ContactsDB.ACCOUNTID = AgencyDB.ACCOUNTID");
queries.ADEmailCountQuery = GetEmailContactsCountQuery(sqlQuery,
"SELECT count(ContactsDB.Account) FROM ContactsDB INNER JOIN AgencyDB ON ContactsDB.ACCOUNTID = AgencyDB.ACCOUNTID");
return queries;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public static string GetAdNamesQuery(string query)
{
query = query.Replace("SELECT * FROM AgencyDB", "SELECT AgencyDB.ACCOUNT,AgencyDB.State FROM AGENCYDB ");
query = query.Replace("SELECT * FROM ContactsDB INNER JOIN AgencyDB ON ContactsDB.ACCOUNTID = AgencyDB.ACCOUNTID", "SELECT AgencyDB.ACCOUNT,AgencyDB.State FROM AGENCYDB ");
query = query + " ORDER BY AgencyDB.ACCOUNT";
return query;
}
public static string GetAdAnalyzeQuery(AnalyzeInput input)
{
string firstValue = input.FirstValue;
string secondValue = input.SecondValue;
var strQuery = input.AgencyQuery;
string selectStatement = "";
string strNewQuery = "";
if (((firstValue != "") && (secondValue == "")))
{
selectStatement = firstValue;
}
if (((firstValue == "") && (secondValue != "")))
{
selectStatement = secondValue;
}
if (((firstValue != "") && (secondValue != "")))
{
selectStatement = (firstValue + ("," + secondValue));
}
string strSicColumn = "";
if ((selectStatement != ""))
{
selectStatement = selectStatement.Replace("POSTALCODE", "POSTALCODE AS ZIPCODE");
var groupStatement = selectStatement;
groupStatement = groupStatement.Replace("POSTALCODE AS ZIPCODE", "POSTALCODE");
if ((selectStatement.IndexOf("(SICCODE,1,2)") > -1))
{
selectStatement = selectStatement.Replace("(SICCODE,1,2)", "(SICCODE,1,2) as [Two_Digit_SIC] ");
strSicColumn = "Two_Digit_SIC";
}
else if ((selectStatement.IndexOf("(SICCODE,1,4)") > -1))
{
selectStatement = selectStatement.Replace("(SICCODE,1,4)", "(SICCODE,1,4) as [Four_Digit_SIC] ");
strSicColumn = "Four_Digit_SIC";
}
else if ((selectStatement.IndexOf("(SICCODE,1,6)") > -1))
{
selectStatement = selectStatement.Replace("(SICCODE,1,6)", "(SICCODE,1,6) as [Six_Digit_SIC] ");
strSicColumn = "Six_Digit_SIC";
}
else if ((selectStatement.IndexOf("SICCODE") > -1))
{
selectStatement = selectStatement.Replace("SICCODE", "SICCODE as [Eight_Digit_SIC] ");
strSicColumn = "Eight_Digit_SIC";
}
if ((selectStatement.IndexOf("SICCODE") > -1))
{
var strReplaceby = (selectStatement + ",Count(*) as Records, Description FROM AgencyDB INNER JOIN TargetSectorsDB ON AgencyDB.ACCOUNTID = TargetSectorsDB.ACCOUNTID ");
strNewQuery = strQuery.Replace("* FROM AgencyDB ", strReplaceby);
}
else
{
strNewQuery = strQuery.Replace("* ", (selectStatement + ",Count(*) as Records "));
}
if ((input.FirstValue.Contains("SIC") || input.SecondValue.Contains("SIC")))
{
if (!string.IsNullOrEmpty(input.SicCodes))
{
strNewQuery = (strNewQuery + ("And"
+ (BuildSICQuery(input.SicCodes) + (" GROUP BY "
+ (groupStatement + ", Description" + (" ORDER BY " + groupStatement + ", Description"))))));
}
else
{
strNewQuery = (strNewQuery + (" GROUP BY "
+ (groupStatement + ", Description" + (" ORDER BY " + groupStatement + ", Description"))));
}
}
else
{
strNewQuery = (strNewQuery + (" GROUP BY "
+ (groupStatement + (" ORDER BY " + groupStatement))));
}
}
return strNewQuery;
}
private static string GetEmailContactsCountQuery(string strQueryAgency, string strQuery)
{
strQueryAgency = strQueryAgency.Replace("*", "Count(Account)");
strQuery = strQueryAgency.Replace("SELECT Count(Account) FROM AgencyDB", strQuery);
strQuery = (strQuery + " AND NOT ContactsDB.CEMAIL IS NULL");
return strQuery;
}
private static string GetContactsCountQuery(string strQueryAgency, string strQuery)
{
strQueryAgency = strQueryAgency.Replace("*", "Count(Account)");
strQuery = strQueryAgency.Replace("SELECT Count(Account) FROM AgencyDB", strQuery);
return strQuery;
}
private static string GetRecordCountQuery(string strQuery)
{
strQuery = strQuery.Replace("*", "Count(Account)");
return strQuery;
}
private static string BuildSQL(bool Agency)
{
var test = SearchInput.QueryName;
StringBuilder StMain = new StringBuilder();
StringBuilder StQry = new StringBuilder();
string Str;
StMain.Append("SELECT * FROM AgencyDB ");
// Get the Type Query (Agency,National Broker ect...)
Str = "";
Str = GetTypeQuery();
AppendCondition(ref Str, ref StQry);
// Get the Additional Query Premium Volume & Employee Size
Str = GetAdditionalQuery();
AppendCondition(ref Str, ref StQry);
// Get the AgencyManagement Query
Str = GetAgencyManagementQuery();
AppendCondition(ref Str, ref StQry);
//search by company name search
Str = GetCompanySearchQuery();
AppendCondition(ref Str, ref StQry);
// Get the Country Query
Str = GetCountryQuery();
AppendCondition(ref Str, ref StQry);
// Get the State Query
Str = GetGeographicQuery();
AppendCondition(ref Str, ref StQry);
// Get the Contacts Title Search Query
if (!Agency)
{
Str = GetTitleSearchQuery();
AppendCondition(ref Str, ref StQry);
// Get the Contacts Lines Search Query
Str = GetLinesSearchQuery();
AppendCondition(ref Str, ref StQry);
}
// Get the Companylines Query
Str = GetCompaniesQuery();
AppendCondition(ref Str, ref StQry);
// Get the SpecialAffiliations Query
Str = GetAffiliationsQuery();
AppendCondition(ref Str, ref StQry);
// Get the TargetSector(SICCODES) Query
Str = BuildSICQuery(SearchInput.SICCodes);
AppendCondition(ref Str, ref StQry);
StMain.Append(StQry.ToString());
return StMain.ToString();
}
private static void AppendCondition(ref string Str, ref StringBuilder StQry)
{
if ((Str.Trim() != ""))
{
if (string.IsNullOrEmpty(StQry.ToString()))
{
StQry.Append((" WHERE " + Str));
}
else
{
StQry.Append((" AND " + Str));
}
Str = "";
}
}
private static string GetGeographicQuery()
{
StringBuilder stqry = new StringBuilder();
string strStates = GetStatesQuery();
string strExcludeStates = GetExcludeStatesQuery();
if (((strStates != "") && (strExcludeStates != "")))
{
strStates = (" ("
+ (strStates + (" AND "
+ (strExcludeStates + " ) "))));
}
else if (((strStates == "")
&& (strExcludeStates != "")))
{
strStates = strExcludeStates;
}
string strCounties = GetCOUNTIESQuery();
string strExcludeCounties = GetExcludeCountiesQuery();
if (((strCounties != "") && (strExcludeCounties != "")))
{
if ((strStates == ""))
{
strCounties = (" (("
+ (strCounties + (" OR "
+ (strExcludeCounties + " ) "))));
}
else
{
strCounties = (" AND (("
+ (strCounties + (" OR "
+ (strExcludeCounties + " ) "))));
}
}
else if (((strCounties == "")
&& (strExcludeCounties != "")))
{
strCounties = (" AND (" + strExcludeCounties);
}
else if (((strCounties != "")
&& (strExcludeCounties == "")))
{
if ((strStates == ""))
{
strCounties = (" ( " + strCounties);
}
else
{
strCounties = (" OR ( " + strCounties);
}
}
string strZips = GetZipQuery();
string strExcludeZips = GetExcludeZipQuery();
if (((strZips != "") && (strExcludeZips != "")))
{
if ((strCounties != ""))
{
strZips = (" OR ("
+ (strZips + (" AND "
+ (strExcludeZips + " ) "))));
}
else
{
strZips = (" AND ( ("
+ (strZips + (" AND "
+ (strExcludeZips + " ) "))));
}
}
else if (((strZips == "")
&& (strExcludeZips != "")))
{
if ((strCounties != ""))
{
strZips = (" AND " + strExcludeZips);
}
else
{
strZips = (" AND ( " + strExcludeZips);
}
}
else if (((strZips != "")
&& (strExcludeZips == "")))
{
if ((strCounties != ""))
{
strZips = (" OR " + strZips);
}
else
{
strZips = (" And ( " + strZips);
}
}
string strMSAs = GetMSAQuery();
string strExcludeMSAs = GetExcludeMSAQuery();
if (((strMSAs != "")
&& (strExcludeMSAs != "")))
{
if (((strCounties == "")
&& (strZips == "")))
{
strMSAs = (" AND ( ("
+ (strMSAs + (" AND "
+ (strExcludeMSAs + " ) "))));
}
else
{
strMSAs = (" OR ("
+ (strMSAs + (" AND "
+ (strExcludeMSAs + " ) "))));
}
}
else if (((strMSAs == "")
&& (strExcludeMSAs != "")))
{
if (((strCounties == "")
&& (strZips == "")))
{
strMSAs = (" AND ( " + strExcludeMSAs);
}
else
{
strMSAs = (" AND " + strExcludeMSAs);
}
}
else if (((strMSAs != "")
&& (strExcludeMSAs == "")))
{
if (((strCounties == "")
&& (strZips == "")))
{
strMSAs = (" AND ( " + strMSAs);
}
else
{
strMSAs = (" OR " + strMSAs);
}
}
if ((strStates != ""))
{
stqry.Append(strStates);
}
if ((strCounties != ""))
{
stqry.Append(strCounties);
}
if ((strZips != ""))
{
stqry.Append(strZips);
}
if ((strMSAs != ""))
{
stqry.Append(strMSAs);
}
// Closing Parenthesis (Because of OR Conditions)
if (((strCounties != "")
|| ((strZips != "")
|| (strMSAs != ""))))
{
stqry.Append(" )");
}
return stqry.ToString();
}
private static string GetExcludeMSAQuery()
{
if (!string.IsNullOrEmpty(SearchInput.ExcludeMSA))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.ExcludeMSA.Trim(), "AgencyDB.MSA", "AND", "<>", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
return "";
}
private static string GetMSAQuery()
{
if (!string.IsNullOrEmpty(SearchInput.MSA))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.MSA, "AgencyDB.MSA", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("("
+ (stb.ToString() + ")"));
}
else
{
return "";
}
}
else
{
return "";
}
}
private static void BuildZipSubquery(string strList, string condition, string operators, ref StringBuilder stb)
{
string[] strArray = strList.Split(",");
int i;
string sValue;
for (i = 0; (i <= (strArray.Length - 1)); i++)
{
sValue = "";
sValue = strArray[i];
if ((stb.ToString().Trim() == ""))
{
if ((sValue.Length > 3))
{
stb.Append(("AGENCYDB.POSTALCODE " + operators + " like \'"
+ (sValue + "%\'")));
}
else if ((sValue.Length == 3))
{
stb.Append(("AGENCYDB.POSTALCODE " + operators + " like \'"
+ (sValue + "%\'")));
}
}
else if ((sValue.Length > 3))
{
stb.Append((" " + condition + " AGENCYDB.POSTALCODE " + operators + " like \'"
+ (sValue + "%\'")));
}
else if ((sValue.Length == 3))
{
stb.Append((" " + condition + " AGENCYDB.POSTALCODE " + operators + " like \'"
+ (sValue + "%\'")));
}
}
}
private static string GetExcludeZipQuery()
{
if (!string.IsNullOrEmpty(SearchInput.ExcludeZip))
{
StringBuilder stb = new StringBuilder();
BuildZipSubquery(SearchInput.ExcludeZip.Trim(), "AND", "NOT", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
return "";
}
private static string GetZipQuery()
{
if (!string.IsNullOrEmpty(SearchInput.Zip))
{
StringBuilder stb = new StringBuilder();
BuildZipSubquery(SearchInput.Zip.Trim(), "OR", string.Empty, ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
return "";
}
private static string GetExcludeCountiesQuery()
{
if (!string.IsNullOrEmpty(SearchInput.ExcludeCountyIds))
{
if (!string.IsNullOrEmpty(SearchInput.CountyIDs))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.IncludeCountyIds, "AgencyDB.COUNTYCODE", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
else
{
string strList = "";
strList = SearchInput.ExcludeCountyIds;
string[] strExcludeArray = strList.Split(",");
int i;
string sValue;
StringBuilder stb = new StringBuilder();
for (i = 0; (i <= (strExcludeArray.Length - 1)); i++)
{
sValue = "";
sValue = strExcludeArray[i];
if ((stb.ToString().Trim() == ""))
{
stb.Append(("AgencyDB.COUNTYCODE <>\'" + (sValue + "\'")));
}
else
{
stb.Append((" AND AgencyDB.COUNTYCODE <>\'" + (sValue + "\'")));
}
}
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
}
return "";
}
public static string GetAllExcludecounties(string excludeCountyIds)
{
StringBuilder stb = new StringBuilder();
string ST2ExcludeCountyIDS = "";
string strquery = "SELECT STRING_AGG(CountyCode, \', \') FROM RS_Counties WHERE (State IN ";
if (!string.IsNullOrEmpty(excludeCountyIds))
{
string strListstate = "";
strListstate = excludeCountyIds;
string strvalue = "";
string[] strExcludeArray = strListstate.Split(",");
for (int i = 0; (i <= (strExcludeArray.Length - 1)); i++)
{
strvalue = ("\'"
+ (strExcludeArray[i].Substring(0, 2) + ("\'" + ("," + strvalue))));
}
stb.Append("(" + strvalue.Trim(',') + "" + "))");
string strexcludecounty = "";
strexcludecounty = excludeCountyIds;
string[] strExcludeCounties = strexcludecounty.Split(",");
for (int i = 0; (i <= (strExcludeCounties.Length - 1)); i++)
{
if ((stb.ToString().Trim() == ""))
{
stb.Append((" AND (" + ("COUNTYCODE <>\'"
+ (strExcludeCounties[i] + ("\'" + ")")))));
}
else
{
stb.Append((" AND (" + ("COUNTYCODE <>\'"
+ (strExcludeCounties[i] + ("\'" + ")")))));
}
}
strquery = (strquery + stb.ToString());
return strquery;
}
return "";
}
private static string GetCOUNTIESQuery()
{
if (!string.IsNullOrEmpty(SearchInput.CountyIDs))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.CountyIDs, "AgencyDB.COUNTYCODE", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("("
+ (stb.ToString() + ")"));
}
}
return "";
}
private static string GetExcludeStatesQuery()
{
if (!string.IsNullOrEmpty(SearchInput.ExcludeState))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.ExcludeState, "AgencyDB.STATE", "AND", "<>", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
return "";
}
private static string GetStatesQuery()
{
if (!string.IsNullOrEmpty(SearchInput.State))
{
string strList = "";
ArrayList arrLStates = new ArrayList();
int i;
if ((!string.IsNullOrEmpty(SearchInput.CountyIDs)) && (!string.IsNullOrEmpty(SearchInput.ExcludeCountyIds)))
{
return "";
}
else
{
if (!string.IsNullOrEmpty(SearchInput.CountyIDs))
{
strList = SearchInput.CountyIDs;
string[] strStatesSelected = strList.Split(",");
try
{
for (i = 0; (i <= (strStatesSelected.Length - 1)); i++)
{
if ((arrLStates.Contains(strStatesSelected[i].Substring(0, 2)) == false))
{
arrLStates.Add(strStatesSelected[i].Substring(0, 2));
}
}
}
catch (Exception ex)
{
throw;
}
}
strList = SearchInput.State;
string[] strArray = strList.Split(",");
string sValue;
StringBuilder stb = new StringBuilder();
for (i = 0; (i <= (strArray.Length - 1)); i++)
{
sValue = "";
sValue = strArray[i];
if ((arrLStates.Contains(sValue) == false))
{
if ((stb.ToString().Trim() == ""))
{
stb.Append(("AgencyDB.STATE=\'"
+ (sValue + "\'")));
}
else
{
stb.Append((" OR AgencyDB.STATE=\'"
+ (sValue + "\'")));
}
}
}
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
}
return "";
}
private static string GetCountryQuery()
{
if (!string.IsNullOrEmpty(SearchInput.Country))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.Country, "AgencyDB.COUNTRY", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
return ("(" + (stb.ToString() + ")"));
}
}
return "";
}
private static string GetCompanySearchQuery()
{
StringBuilder strBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(SearchInput.CompanyName))
{
string strCompanyName = SearchInput.CompanyName;
if ((SearchInput.CompanyNameType.ToUpper().Trim() == "CONTAINS"))
{
if (strBuilder.ToString() == "")
{
strBuilder.Append(("AgencyDB.ACCOUNT LIKE \'%"
+ (strCompanyName + "%\'")));
}
}
else if (SearchInput.CompanyNameType.ToUpper().Trim() == "BEGINS")
{
if ((strBuilder.ToString().Trim() == ""))
{
strBuilder.Append(("AgencyDB.ACCOUNT LIKE \'"
+ (strCompanyName + "%\'")));
}
}
}
return strBuilder.ToString();
}
private static string GetAgencyManagementQuery()
{
if (!string.IsNullOrEmpty(SearchInput.AgencyManagement))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.AgencyManagement, "AgencyDB.AGENCYMANAGEMENT", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
if (SearchInput.AgencyMgntCriteria.Trim() == "INCLUDE")
{
return ("(" + (stb.ToString() + ")"));
}
else if (SearchInput.AgencyMgntCriteria.Trim() == "EXCLUDE")
{
return ("(NOT (" + (stb.ToString() + "))"));
}
}
}
return "";
}
private static string GetCompaniesQuery()
{
if (!string.IsNullOrEmpty(SearchInput.CompanyLines))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.CompanyLines.Trim(), "ClinesDB.COMPANYLINE", "OR", "=", ref stb);
StringBuilder StFinal = new StringBuilder();
if ((stb.ToString() != ""))
{
StFinal.Append("(AgencyDB.ACCOUNTID IN (SELECT ACCOUNTID FROM ClinesDB WHERE ");
//StFinal.Append((stb.ToString() + "))"));
if (SearchInput.CarrierManageCrieteria.Trim() == "INCLUDE")
{
return StFinal.Append("(" + stb.ToString() + ")))").ToString();
}
else if (SearchInput.CarrierManageCrieteria.Trim() == "EXCLUDE")
{
return StFinal.Append("NOT (" + stb.ToString() + ")))").ToString();
}
return StFinal.ToString();
}
else
{
return StFinal.ToString();
//done with me
}
}
return "";
}
private static string GetAdditionalQuery()
{
StringBuilder St = new StringBuilder();
string sValue1;
string sValue2;
string sValue3;
string strCondition1;
string strCondition2;
strCondition1 = SearchInput.PEmpCriteria;
strCondition2 = SearchInput.RevenueCriteria;
sValue1 = GetVolumeQuery(SearchInput.PVolume, "AgencyDB.PREMIUMVOLUME");
sValue2 = GetVolumeQuery(SearchInput.RevenueValue, "AgencyDB.REVENUE");
sValue3 = GetEmployeeSizeQuery();
if (((sValue1 != "") && ((sValue2 != "") && (sValue3 != ""))))
{
// 123
St.Append(("(("
+ (sValue1 + (") "
+ (strCondition1 + (" ( "
+ (sValue2 + (") "
+ (strCondition2 + (" ("
+ (sValue3 + "))")))))))))));
}
else if (((sValue1 != "")
&& ((sValue2 != "")
&& (sValue3 == ""))))
{
// 12
St.Append(("(("
+ (sValue1 + (") "
+ (strCondition1 + (" ( "
+ (sValue2 + "))")))))));
}
else if ((sValue1 == "") && (sValue2 != "") && (sValue3 != ""))
{
// 23
St.Append("((" + sValue2 + ") " + strCondition2 + " ( " + sValue3 + "))");
}
else if (((sValue1 != "")
&& ((sValue2 == "")
&& (sValue3 != ""))))
{
// 13
St.Append("((" + sValue1 + ") " + strCondition1 + " ( " + sValue3 + "))");
}
else if (((sValue1 != "")
&& ((sValue2 == "")
&& (sValue3 == ""))))
{
// 1
St.Append(("("
+ (sValue1 + ")")));
}
else if (((sValue1 == "")
&& ((sValue2 != "")
&& (sValue3 == ""))))
{
// 2
St.Append(("("
+ (sValue2 + ")")));
}
else if (((sValue1 == "")
&& ((sValue2 == "")
&& (sValue3 != ""))))
{
// 3
St.Append(("("
+ (sValue3 + ")")));
}
return St.ToString();
}
private static string GetEmployeeSizeQuery()
{
if (!string.IsNullOrEmpty(SearchInput.EmpSize))
{
var st1 = '-';
string strEMPSize = SearchInput.EmpSize;
string[] strEMP = strEMPSize.Split(st1);
string strEMPTO = "";
string strEMPFROM = "";
int i;
for (i = 0; (i <= (strEMP.Length - 1)); i++)
{
if ((i == 0))
{
strEMPFROM = strEMP[i];
}
if ((i == 1))
{
strEMPTO = strEMP[i];
}
}
StringBuilder St = new StringBuilder();
St.Append("AgencyDB.EMPLOYEES ");
if (((strEMPFROM.Trim() != "") && (strEMPTO.Trim() != "")))
{
// From and To
St.Append("BETWEEN ");
St.Append(strEMPFROM);
St.Append(" AND ");
St.Append(strEMPTO);
return St.ToString();
}
else if (((strEMPTO.Trim() == "")
&& (strEMPFROM.Trim() != "")))
{
// >=From
St.Append((">=" + strEMPFROM));
return St.ToString();
}
else
{
return "";
}
}
else
{
return "";
}
}
private static string GetTypeQuery()
{
if (!string.IsNullOrEmpty(SearchInput.TypeField))
{
string st1;
st1 = ",";
string strTypeField = SearchInput.TypeField;
string[] strArray = strTypeField.Split(st1);
int i;
string sValue;
StringBuilder St = new StringBuilder();
for (i = 0; i <= strArray.Length - 1; i++)
{
sValue = "";
sValue = strArray[i];
if (SearchInput.TypeCriteria == "CONTAINS")
{
if (string.IsNullOrEmpty(St.ToString()))
{
St.Append("AgencyDB.TYPE LIKE \'%" + sValue + "%\'");
}
else
{
St.Append(" OR AgencyDB.TYPE LIKE \'%" + sValue + "%\'");
}
}
else if ((SearchInput.TypeCriteria == "EXACT MATCH"))
{
if (string.IsNullOrEmpty(St.ToString()))
{
St.Append("AgencyDB.TYPE = \'" + sValue + "\'");
}
else
{
St.Append(" OR AgencyDB.TYPE = \'" + sValue + "\'");
}
}
else if ((SearchInput.TypeCriteria == "STARTS WITH"))
{
if (string.IsNullOrEmpty(St.ToString()))
{
St.Append("AgencyDB.TYPE LIKE \'" + sValue + "%\'");
}
else
{
St.Append(" OR AgencyDB.TYPE LIKE \'" + sValue + "%\'");
}
}
}
if (SearchInput.isRetail == true)
{
St.Append(" and AgencyDB.TYPE not in (select Name from CompanyTypes where IsWholesale = 1 and(IsRetail = 0 or IsRetail is null))");
}
else if (SearchInput.isWholesale == true)
{
St.Append(" and AgencyDB.TYPE not in (select Name from CompanyTypes where IsRetail = 1 and(IsWholesale = 0 or IsWholesale is null))");
}
string strTypeQuery = St.ToString();
if ((strTypeQuery.Trim() != ""))
{
return ("(" + (strTypeQuery + ")"));
}
else
{
return "";
}
}
else
{
return "";
}
}
private static string GetVolumeQuery(string value, string table)
{
if (!string.IsNullOrEmpty(value))
{
var st1 = '-';
string strVolume = value;
string[] strValues = strVolume.Split(st1);
string strvTo = "";
string strvFrom = "";
int i;
for (i = 0; (i <= (strValues.Length - 1)); i++)
{
var amount = (double.Parse(strValues[i]) * 1000000).ToString();
if ((i == 0))
{
strvFrom = amount;
}
if ((i == 1))
{
strvTo = amount;
}
}
StringBuilder St = new StringBuilder();
St.Append(table + " ");
double vFrom = 0;
double vTo = 0;
if (((strvFrom.Trim() != "") && (strvTo.Trim() != "")))
{
vFrom = double.Parse(strvFrom);
vTo = double.Parse(strvTo);
if (((vFrom > 0) && (vTo <= 0)))
{
St.Append((">=" + vFrom));
return St.ToString();
}
else if (((vTo > 0) && (vFrom <= 0)))
{
St.Append(("<=" + vTo));
}
else
{
St.Append("BETWEEN ");
St.Append(vFrom);
St.Append(" AND ");
St.Append(vTo);
}
return St.ToString();
}
else if (((strvTo.Trim() == "") && (strvFrom.Trim() != "")))
{
// >=vFrom
vFrom = double.Parse(strvFrom);
St.Append((">=" + vFrom));
return St.ToString();
}
else
{
return "";
}
}
else
{
return "";
}
}
private static string GetTitleSearchQuery()
{
if (!string.IsNullOrEmpty(SearchInput.TitleSearch))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.TitleSearch, "ContactsDB.TITLESEARCH", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
if (SearchInput.TitleSearchCriteria.Trim() == "INCLUDE")
{
return ("(" + (stb.ToString() + ")"));
}
else if (SearchInput.TitleSearchCriteria.Trim() == "EXCLUDE")
{
return ("(NOT (" + (stb.ToString() + "))"));
}
}
}
return "";
}
private static string GetLinesSearchQuery()
{
if (!string.IsNullOrEmpty(SearchInput.LinesSearch))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.LinesSearch, "ContactsDB.LINESEARCH", "OR", "=", ref stb);
if ((stb.ToString().Trim() != ""))
{
if (SearchInput.LinesSearchCriteria.Trim() == "INCLUDE")
{
return ("(" + (stb.ToString() + ")"));
}
else if (SearchInput.LinesSearchCriteria.Trim() == "EXCLUDE")
{
return ("(NOT (" + (stb.ToString() + "))"));
}
}
}
return "";
}
private static string GetAffiliationsQuery()
{
if (!string.IsNullOrEmpty(SearchInput.Affiliations))
{
StringBuilder stb = new StringBuilder();
SubqueryBuilder(SearchInput.Affiliations, "SPECIALAFFILIATION", "OR", "=", ref stb);
StringBuilder StFinal = new StringBuilder();
if ((stb.ToString() != ""))
{
StFinal.Append("(AgencyDB.ACCOUNTID IN (SELECT ACCOUNTID FROM SplAffDB WHERE ");
StFinal.Append((stb.ToString() + "))"));
return StFinal.ToString();
}
}
return "";
}
private static string BuildSICQuery(string sicCodes)
{
StringBuilder Sb = new StringBuilder();
if (!string.IsNullOrEmpty(sicCodes))
{
string strList = sicCodes;
string[] stArray = strList.Split(",");
int i;
string sValue = "";
for (i = 0; (i <= (stArray.Length - 1)); i++)
{
sValue = "";
sValue = stArray[i];
if ((sValue.Trim() != ""))
{
if ((Sb.ToString() == ""))
{
if (((sValue.Trim() == "A")
|| ((sValue.Trim() == "B")
|| ((sValue.Trim() == "C")
|| ((sValue.Trim() == "D")
|| ((sValue.Trim() == "E")
|| ((sValue.Trim() == "F")
|| ((sValue.Trim() == "G")
|| ((sValue.Trim() == "H")
|| ((sValue.Trim() == "I")
|| ((sValue.Trim() == "J")
|| (sValue.Trim() == "K"))))))))))))
{
Sb.Append(GetMainClassNumbers(sValue));
}
else
{
Sb.Append((" SICCODE LIKE \'" + (sValue.Trim() + "%\'")));
}
}
else if (((sValue.Trim() == "A")
|| ((sValue.Trim() == "B")
|| ((sValue.Trim() == "C")
|| ((sValue.Trim() == "D")
|| ((sValue.Trim() == "E")
|| ((sValue.Trim() == "F")
|| ((sValue.Trim() == "G")
|| ((sValue.Trim() == "H")
|| ((sValue.Trim() == "I")
|| ((sValue.Trim() == "J")
|| (sValue.Trim() == "K"))))))))))))
{
Sb.Append((" OR " + GetMainClassNumbers(sValue)));
}
else
{
Sb.Append((" OR SICCODE LIKE \'" + (sValue.Trim() + "%\'")));
}
}
}
}
if ((Sb.ToString().Trim() != ""))
{
string strMain = "(AgencyDB.ACCOUNTID IN (SELECT ACCOUNTID FROM TargetSectorsDB WHERE ";
strMain = (strMain
+ (Sb.ToString() + "))"));
return strMain;
}
else
{
return "";
}
}
private static string GetMainClassNumbers(string strClass)
{
if ((strClass == "A"))
{
return " SICCODE LIKE \'01%\' OR SICCODE LIKE \'02%\' OR SICCODE LIKE \'07%\' OR SICCODE LIKE \'08%\' OR SICCODE LIKE" +
" \'09%\'";
}
else if ((strClass == "B"))
{
return " SICCODE LIKE \'10%\' OR SICCODE LIKE \'12%\' OR SICCODE LIKE \'13%\' OR SICCODE LIKE \'14%\'";
}
else if ((strClass == "C"))
{
return " SICCODE LIKE \'15%\' OR SICCODE LIKE \'16%\' OR SICCODE LIKE \'17%\' OR SICCODE LIKE \'18%\' OR SICCODE LIKE" +
" \'19%\'";
}
else if ((strClass == "D"))
{
return @" SICCODE LIKE '20%' OR SICCODE LIKE '21%' OR SICCODE LIKE '22%' OR SICCODE LIKE '23%' OR SICCODE LIKE '24%' OR SICCODE LIKE '25%' OR SICCODE LIKE '26%' OR SICCODE LIKE '27%' OR SICCODE LIKE '28%' OR SICCODE LIKE '29%' OR SICCODE LIKE'30%' OR SICCODE LIKE '31%' OR SICCODE LIKE '32%' OR SICCODE LIKE '33%' OR SICCODE LIKE '34%' OR SICCODE LIKE '35%' OR SICCODE LIKE '36%' OR SICCODE LIKE '37%' OR SICCODE LIKE '38%' OR SICCODE LIKE '39%'";
}
else if ((strClass == "E"))
{
return " SICCODE LIKE \'40%\' OR SICCODE LIKE \'41%\' OR SICCODE LIKE \'42%\' OR SICCODE LIKE \'43%\' OR SICCODE LIKE" +
" \'44%\' OR SICCODE LIKE \'45%\' OR SICCODE LIKE \'46%\' OR SICCODE LIKE \'47%\' OR SICCODE LIKE \'48%\' OR SI" +
"CCODE LIKE \'49%\'";
}
else if ((strClass == "F"))
{
return " SICCODE LIKE \'50%\' OR SICCODE LIKE \'51%\'";
}
else if ((strClass == "G"))
{
return " SICCODE LIKE \'52%\' OR SICCODE LIKE \'53%\' OR SICCODE LIKE \'54%\' OR SICCODE LIKE \'55%\' OR SICCODE LIKE" +
" \'56%\' OR SICCODE LIKE \'57%\' OR SICCODE LIKE \'58%\' OR SICCODE LIKE \'59%\'";
}
else if ((strClass == "H"))
{
return " SICCODE LIKE \'60%\' OR SICCODE LIKE \'61%\' OR SICCODE LIKE \'62%\' OR SICCODE LIKE \'63%\' OR SICCODE LIKE" +
" \'64%\' OR SICCODE LIKE \'65%\' OR SICCODE LIKE \'66%\' OR SICCODE LIKE \'67%\'";
}
else if ((strClass == "I"))
{
return @" SICCODE LIKE '70%' OR SICCODE LIKE '71%' OR SICCODE LIKE '72%' OR SICCODE LIKE '73%' OR SICCODE LIKE '74%' OR SICCODE LIKE '75%' OR SICCODE LIKE '76%' OR SICCODE LIKE '77%' OR SICCODE LIKE '78%' OR SICCODE LIKE '79%' OR SICCODE LIKE '80%' OR SICCODE LIKE '81%' OR SICCODE LIKE '82%' OR SICCODE LIKE '83%' OR SICCODE LIKE '84%' OR SICCODE LIKE '85%' OR SICCODE LIKE '86%' OR SICCODE LIKE '87%' OR SICCODE LIKE '88%' OR SICCODE LIKE '89%' OR SICCODE LIKE '90%'";
}
else if ((strClass == "J"))
{
return " SICCODE LIKE \'91%\' OR SICCODE LIKE \'92%\' OR SICCODE LIKE \'93%\' OR SICCODE LIKE \'94%\' OR SICCODE LIKE" +
" \'95%\' OR SICCODE LIKE \'96%\' OR SICCODE LIKE \'97%\' OR SICCODE LIKE \'98%\'";
}
else if ((strClass == "K"))
{
return " SICCODE LIKE \'99%\'";
}
else
{
return "";
}
}
private static void SubqueryBuilder(string strList, string columnName, string condition, string operators, ref StringBuilder stb)
{
string[] strArray = strList.Split(",");
int i;
string sValue;
for (i = 0; (i <= (strArray.Length - 1)); i++)
{
sValue = "";
sValue = strArray[i];
if ((stb.ToString().Trim() == ""))
{
stb.Append(columnName + operators + "\'" + sValue.Trim() + "\'");
}
else
{
stb.Append(" " + condition + " " + columnName + operators + "\'" + sValue.Trim() + "\'");
}
}
}
}
}
| 36.846978 | 486 | 0.379244 | [
"MIT"
] | aansadiqul/New | aspnet-core/src/ABD.Application/QueryBuilder/ADQueryBuilder.cs | 48,161 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPages.Data;
using RazorPages.Infrastrucutre;
using RazorPages.Models;
namespace RazorPages.Pages.BookList
{
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _db;
private readonly IBookRepository _booksRepo;
[TempData]
public string Message { get; set; }
public CreateModel(ApplicationDbContext db, IBookRepository booksRepo)
{
_db = db;
_booksRepo = booksRepo;
}
[BindProperty]
public Book Book { get; set; }
public void OnGetAcync()
{
}
[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
await _booksRepo.AddBooks(Book);
Message = "Dodano pomyślnie";
return RedirectToPage("Index");
}
}
} | 22.215686 | 78 | 0.610768 | [
"MIT"
] | Fudalii/MVC_Net_Core | RAZOR_pages/RazorPages/RazorPages/Pages/BookList/Create.cshtml.cs | 1,136 | C# |
// ReSharper disable All
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web.Http;
using MixERP.Net.Schemas.Transactions.Data;
using MixERP.Net.EntityParser;
using MixERP.Net.Framework.Extensions;
using PetaPoco;
using CustomField = PetaPoco.CustomField;
namespace MixERP.Net.Api.Transactions.Fakes
{
public class RoutineRepository : IRoutineRepository
{
public long Count()
{
return 1;
}
public IEnumerable<MixERP.Net.Entities.Transactions.Routine> GetAll()
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public IEnumerable<dynamic> Export()
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public MixERP.Net.Entities.Transactions.Routine Get(int routineId)
{
return new MixERP.Net.Entities.Transactions.Routine();
}
public IEnumerable<MixERP.Net.Entities.Transactions.Routine> Get([FromUri] int[] routineIds)
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public IEnumerable<MixERP.Net.Entities.Transactions.Routine> GetPaginatedResult()
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public IEnumerable<MixERP.Net.Entities.Transactions.Routine> GetPaginatedResult(long pageNumber)
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public long CountWhere(List<EntityParser.Filter> filters)
{
return 1;
}
public IEnumerable<MixERP.Net.Entities.Transactions.Routine> GetWhere(long pageNumber, List<EntityParser.Filter> filters)
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public long CountFiltered(string filterName)
{
return 1;
}
public List<EntityParser.Filter> GetFilters(string catalog, string filterName)
{
return Enumerable.Repeat(new EntityParser.Filter(), 1).ToList();
}
public IEnumerable<MixERP.Net.Entities.Transactions.Routine> GetFiltered(long pageNumber, string filterName)
{
return Enumerable.Repeat(new MixERP.Net.Entities.Transactions.Routine(), 1);
}
public IEnumerable<DisplayField> GetDisplayFields()
{
return Enumerable.Repeat(new DisplayField(), 1);
}
public IEnumerable<PetaPoco.CustomField> GetCustomFields()
{
return Enumerable.Repeat(new CustomField(), 1);
}
public IEnumerable<PetaPoco.CustomField> GetCustomFields(string resourceId)
{
return Enumerable.Repeat(new CustomField(), 1);
}
public object AddOrEdit(dynamic routine, List<EntityParser.CustomField> customFields)
{
return true;
}
public void Update(dynamic routine, int routineId)
{
if (routineId > 0)
{
return;
}
throw new ArgumentException("routineId is null.");
}
public object Add(dynamic routine)
{
return true;
}
public List<object> BulkImport(List<ExpandoObject> routines)
{
return Enumerable.Repeat(new object(), 1).ToList();
}
public void Delete(int routineId)
{
if (routineId > 0)
{
return;
}
throw new ArgumentException("routineId is null.");
}
}
} | 29.155039 | 129 | 0.613401 | [
"MPL-2.0"
] | asine/mixerp | src/Libraries/Web API/Transactions/Fakes/RoutineRepository.cs | 3,761 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace EveryplayEditor.XCodeEditor
{
public class PBXBuildPhase : PBXObject
{
protected const string FILES_KEY = "files";
public PBXBuildPhase() : base()
{
internalNewlines = true;
}
public PBXBuildPhase(string guid, PBXDictionary dictionary) : base(guid, dictionary)
{
internalNewlines = true;
}
public bool AddBuildFile(PBXBuildFile file)
{
if (!ContainsKey(FILES_KEY))
{
this.Add(FILES_KEY, new PBXList());
}
((PBXList) _data[FILES_KEY]).Add(file.guid);
return true;
}
public void RemoveBuildFile(string id)
{
if (!ContainsKey(FILES_KEY))
{
this.Add(FILES_KEY, new PBXList());
return;
}
((PBXList) _data[FILES_KEY]).Remove(id);
}
public bool HasBuildFile(string id)
{
if (!ContainsKey(FILES_KEY))
{
this.Add(FILES_KEY, new PBXList());
return false;
}
if (!IsGuid(id))
{
return false;
}
return ((PBXList) _data[FILES_KEY]).Contains(id);
}
}
public class PBXFrameworksBuildPhase : PBXBuildPhase
{
public PBXFrameworksBuildPhase(string guid, PBXDictionary dictionary) : base(guid, dictionary)
{
}
}
public class PBXResourcesBuildPhase : PBXBuildPhase
{
public PBXResourcesBuildPhase(string guid, PBXDictionary dictionary) : base(guid, dictionary)
{
}
}
public class PBXShellScriptBuildPhase : PBXBuildPhase
{
public PBXShellScriptBuildPhase(string guid, PBXDictionary dictionary) : base(guid, dictionary)
{
}
}
public class PBXSourcesBuildPhase : PBXBuildPhase
{
public PBXSourcesBuildPhase(string guid, PBXDictionary dictionary) : base(guid, dictionary)
{
}
}
public class PBXCopyFilesBuildPhase : PBXBuildPhase
{
public PBXCopyFilesBuildPhase(string guid, PBXDictionary dictionary) : base(guid, dictionary)
{
}
}
}
| 21.621053 | 99 | 0.642648 | [
"Apache-2.0"
] | 408794550/871AR | Assets/Editor/Everyplay/XCodeEditor/PBXBuildPhase.cs | 2,054 | C# |
namespace MCAdmin
{
partial class frmProperties
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lblIP = new System.Windows.Forms.Label();
this.lblPort = new System.Windows.Forms.Label();
this.tbPort = new System.Windows.Forms.TextBox();
this.tbLevel = new System.Windows.Forms.TextBox();
this.lblLevel = new System.Windows.Forms.Label();
this.tbPreview = new System.Windows.Forms.TextBox();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.btnCancel = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.ttBase = new System.Windows.Forms.ToolTip(this.components);
this.cbIP = new System.Windows.Forms.ComboBox();
this.lblIntPort = new System.Windows.Forms.Label();
this.tbIntPort = new System.Windows.Forms.TextBox();
this.lblXmxXms = new System.Windows.Forms.Label();
this.numMemory = new System.Windows.Forms.NumericUpDown();
this.lblRecMem = new System.Windows.Forms.Label();
this.cbOnline = new System.Windows.Forms.CheckBox();
this.lblDefRank = new System.Windows.Forms.Label();
this.cbDefRank = new System.Windows.Forms.ComboBox();
this.lblASPrefix = new System.Windows.Forms.Label();
this.numAS = new System.Windows.Forms.NumericUpDown();
this.lblASSuffix = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.numBackup = new System.Windows.Forms.NumericUpDown();
this.lblBackup = new System.Windows.Forms.Label();
this.cbRCONEnable = new System.Windows.Forms.CheckBox();
this.tbRCONPort = new System.Windows.Forms.TextBox();
this.lblRCONPort = new System.Windows.Forms.Label();
this.tbRCONPass = new System.Windows.Forms.TextBox();
this.lblRCONPass = new System.Windows.Forms.Label();
this.btnAutoDetect = new System.Windows.Forms.Button();
this.numMaxPlayers = new System.Windows.Forms.NumericUpDown();
this.lblMaxPlayers = new System.Windows.Forms.Label();
this.lblSrvName = new System.Windows.Forms.Label();
this.tbSrvName = new System.Windows.Forms.TextBox();
this.cbMonsters = new System.Windows.Forms.CheckBox();
this.cbHellworld = new System.Windows.Forms.CheckBox();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numMemory)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numAS)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numBackup)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxPlayers)).BeginInit();
this.SuspendLayout();
//
// lblIP
//
this.lblIP.AutoSize = true;
this.lblIP.Location = new System.Drawing.Point(9, 9);
this.lblIP.Name = "lblIP";
this.lblIP.Size = new System.Drawing.Size(20, 13);
this.lblIP.TabIndex = 0;
this.lblIP.Text = "IP:";
//
// lblPort
//
this.lblPort.AutoSize = true;
this.lblPort.Location = new System.Drawing.Point(9, 35);
this.lblPort.Name = "lblPort";
this.lblPort.Size = new System.Drawing.Size(29, 13);
this.lblPort.TabIndex = 1;
this.lblPort.Text = "Port:";
//
// tbPort
//
this.tbPort.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbPort.Location = new System.Drawing.Point(86, 32);
this.tbPort.Name = "tbPort";
this.tbPort.Size = new System.Drawing.Size(172, 20);
this.tbPort.TabIndex = 2;
this.tbPort.TextChanged += new System.EventHandler(this.event_RefreshPreview);
this.tbPort.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numericStuff_KeyPress);
//
// tbLevel
//
this.tbLevel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbLevel.Location = new System.Drawing.Point(86, 84);
this.tbLevel.Name = "tbLevel";
this.tbLevel.Size = new System.Drawing.Size(361, 20);
this.tbLevel.TabIndex = 4;
this.tbLevel.TextChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblLevel
//
this.lblLevel.AutoSize = true;
this.lblLevel.Location = new System.Drawing.Point(9, 87);
this.lblLevel.Name = "lblLevel";
this.lblLevel.Size = new System.Drawing.Size(65, 13);
this.lblLevel.TabIndex = 5;
this.lblLevel.Text = "Level name:";
//
// tbPreview
//
this.tbPreview.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbPreview.BackColor = System.Drawing.Color.White;
this.tbPreview.Location = new System.Drawing.Point(9, 312);
this.tbPreview.Multiline = true;
this.tbPreview.Name = "tbPreview";
this.tbPreview.ReadOnly = true;
this.tbPreview.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.tbPreview.Size = new System.Drawing.Size(435, 131);
this.tbPreview.TabIndex = 6;
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(12, 449);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.btnCancel);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.btnSave);
this.splitContainer1.Size = new System.Drawing.Size(435, 35);
this.splitContainer1.SplitterDistance = 215;
this.splitContainer1.TabIndex = 9;
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.Location = new System.Drawing.Point(3, 3);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(209, 27);
this.btnCancel.TabIndex = 9;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnSave
//
this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnSave.Location = new System.Drawing.Point(5, 3);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(208, 27);
this.btnSave.TabIndex = 8;
this.btnSave.Text = "Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// ttBase
//
this.ttBase.IsBalloon = true;
//
// cbIP
//
this.cbIP.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbIP.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbIP.FormattingEnabled = true;
this.cbIP.Location = new System.Drawing.Point(86, 5);
this.cbIP.Name = "cbIP";
this.cbIP.Size = new System.Drawing.Size(277, 21);
this.cbIP.TabIndex = 10;
this.cbIP.TextChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblIntPort
//
this.lblIntPort.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblIntPort.AutoSize = true;
this.lblIntPort.Location = new System.Drawing.Point(264, 35);
this.lblIntPort.Name = "lblIntPort";
this.lblIntPort.Size = new System.Drawing.Size(47, 13);
this.lblIntPort.TabIndex = 11;
this.lblIntPort.Text = "Int. Port:";
//
// tbIntPort
//
this.tbIntPort.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.tbIntPort.Location = new System.Drawing.Point(317, 32);
this.tbIntPort.Name = "tbIntPort";
this.tbIntPort.Size = new System.Drawing.Size(130, 20);
this.tbIntPort.TabIndex = 12;
this.tbIntPort.TextChanged += new System.EventHandler(this.event_RefreshPreview);
this.tbIntPort.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numericStuff_KeyPress);
//
// lblXmxXms
//
this.lblXmxXms.AutoSize = true;
this.lblXmxXms.Location = new System.Drawing.Point(6, 165);
this.lblXmxXms.Name = "lblXmxXms";
this.lblXmxXms.Size = new System.Drawing.Size(128, 13);
this.lblXmxXms.TabIndex = 13;
this.lblXmxXms.Text = "Assigned memory (in MB):";
//
// numMemory
//
this.numMemory.Location = new System.Drawing.Point(140, 163);
this.numMemory.Maximum = new decimal(new int[] {
4096,
0,
0,
0});
this.numMemory.Minimum = new decimal(new int[] {
512,
0,
0,
0});
this.numMemory.Name = "numMemory";
this.numMemory.Size = new System.Drawing.Size(90, 20);
this.numMemory.TabIndex = 14;
this.numMemory.Value = new decimal(new int[] {
1024,
0,
0,
0});
this.numMemory.ValueChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblRecMem
//
this.lblRecMem.AutoSize = true;
this.lblRecMem.Location = new System.Drawing.Point(236, 165);
this.lblRecMem.Name = "lblRecMem";
this.lblRecMem.Size = new System.Drawing.Size(153, 13);
this.lblRecMem.TabIndex = 15;
this.lblRecMem.Text = "(Recommended: min. 1024MB)";
//
// cbOnline
//
this.cbOnline.AutoSize = true;
this.cbOnline.Location = new System.Drawing.Point(6, 241);
this.cbOnline.Name = "cbOnline";
this.cbOnline.Size = new System.Drawing.Size(158, 17);
this.cbOnline.TabIndex = 16;
this.cbOnline.Text = "Run in online (secure) mode";
this.cbOnline.UseVisualStyleBackColor = true;
this.cbOnline.CheckedChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblDefRank
//
this.lblDefRank.AutoSize = true;
this.lblDefRank.Location = new System.Drawing.Point(9, 113);
this.lblDefRank.Name = "lblDefRank";
this.lblDefRank.Size = new System.Drawing.Size(68, 13);
this.lblDefRank.TabIndex = 17;
this.lblDefRank.Text = "Default rank:";
//
// cbDefRank
//
this.cbDefRank.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbDefRank.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDefRank.FormattingEnabled = true;
this.cbDefRank.Location = new System.Drawing.Point(86, 110);
this.cbDefRank.Name = "cbDefRank";
this.cbDefRank.Size = new System.Drawing.Size(361, 21);
this.cbDefRank.TabIndex = 18;
this.cbDefRank.SelectedIndexChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblASPrefix
//
this.lblASPrefix.AutoSize = true;
this.lblASPrefix.Location = new System.Drawing.Point(6, 191);
this.lblASPrefix.Name = "lblASPrefix";
this.lblASPrefix.Size = new System.Drawing.Size(81, 13);
this.lblASPrefix.TabIndex = 19;
this.lblASPrefix.Text = "Autosave every";
//
// numAS
//
this.numAS.Location = new System.Drawing.Point(93, 189);
this.numAS.Maximum = new decimal(new int[] {
4096,
0,
0,
0});
this.numAS.Name = "numAS";
this.numAS.Size = new System.Drawing.Size(87, 20);
this.numAS.TabIndex = 20;
this.numAS.ValueChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblASSuffix
//
this.lblASSuffix.AutoSize = true;
this.lblASSuffix.Location = new System.Drawing.Point(186, 191);
this.lblASSuffix.Name = "lblASSuffix";
this.lblASSuffix.Size = new System.Drawing.Size(109, 13);
this.lblASSuffix.TabIndex = 21;
this.lblASSuffix.Text = "minutes (0 to disable).";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(186, 217);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 13);
this.label1.TabIndex = 24;
this.label1.Text = "minutes (0 to disable).";
//
// numBackup
//
this.numBackup.Location = new System.Drawing.Point(93, 215);
this.numBackup.Maximum = new decimal(new int[] {
4096,
0,
0,
0});
this.numBackup.Name = "numBackup";
this.numBackup.Size = new System.Drawing.Size(87, 20);
this.numBackup.TabIndex = 23;
this.numBackup.ValueChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblBackup
//
this.lblBackup.AutoSize = true;
this.lblBackup.Location = new System.Drawing.Point(6, 217);
this.lblBackup.Name = "lblBackup";
this.lblBackup.Size = new System.Drawing.Size(73, 13);
this.lblBackup.TabIndex = 22;
this.lblBackup.Text = "Backup every";
//
// cbRCONEnable
//
this.cbRCONEnable.AutoSize = true;
this.cbRCONEnable.Location = new System.Drawing.Point(6, 266);
this.cbRCONEnable.Name = "cbRCONEnable";
this.cbRCONEnable.Size = new System.Drawing.Size(131, 17);
this.cbRCONEnable.TabIndex = 25;
this.cbRCONEnable.Text = "Enable source RCON:";
this.cbRCONEnable.UseVisualStyleBackColor = true;
this.cbRCONEnable.CheckedChanged += new System.EventHandler(this.cbRCONEnable_CheckedChanged);
//
// tbRCONPort
//
this.tbRCONPort.Location = new System.Drawing.Point(178, 263);
this.tbRCONPort.Name = "tbRCONPort";
this.tbRCONPort.Size = new System.Drawing.Size(80, 20);
this.tbRCONPort.TabIndex = 26;
this.tbRCONPort.TextChanged += new System.EventHandler(this.event_RefreshPreview);
this.tbRCONPort.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.numericStuff_KeyPress);
//
// lblRCONPort
//
this.lblRCONPort.AutoSize = true;
this.lblRCONPort.Location = new System.Drawing.Point(143, 267);
this.lblRCONPort.Name = "lblRCONPort";
this.lblRCONPort.Size = new System.Drawing.Size(29, 13);
this.lblRCONPort.TabIndex = 27;
this.lblRCONPort.Text = "Port:";
//
// tbRCONPass
//
this.tbRCONPass.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbRCONPass.Location = new System.Drawing.Point(303, 263);
this.tbRCONPass.Name = "tbRCONPass";
this.tbRCONPass.Size = new System.Drawing.Size(138, 20);
this.tbRCONPass.TabIndex = 28;
this.tbRCONPass.TextChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblRCONPass
//
this.lblRCONPass.AutoSize = true;
this.lblRCONPass.Location = new System.Drawing.Point(264, 266);
this.lblRCONPass.Name = "lblRCONPass";
this.lblRCONPass.Size = new System.Drawing.Size(33, 13);
this.lblRCONPass.TabIndex = 29;
this.lblRCONPass.Text = "Pass:";
//
// btnAutoDetect
//
this.btnAutoDetect.Location = new System.Drawing.Point(369, 5);
this.btnAutoDetect.Name = "btnAutoDetect";
this.btnAutoDetect.Size = new System.Drawing.Size(78, 21);
this.btnAutoDetect.TabIndex = 30;
this.btnAutoDetect.Text = "Auto-detect";
this.btnAutoDetect.UseVisualStyleBackColor = true;
this.btnAutoDetect.Click += new System.EventHandler(this.btnAutoDetect_Click);
//
// numMaxPlayers
//
this.numMaxPlayers.Location = new System.Drawing.Point(86, 137);
this.numMaxPlayers.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.numMaxPlayers.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numMaxPlayers.Name = "numMaxPlayers";
this.numMaxPlayers.Size = new System.Drawing.Size(90, 20);
this.numMaxPlayers.TabIndex = 32;
this.numMaxPlayers.Value = new decimal(new int[] {
20,
0,
0,
0});
this.numMaxPlayers.ValueChanged += new System.EventHandler(this.event_RefreshPreview);
//
// lblMaxPlayers
//
this.lblMaxPlayers.AutoSize = true;
this.lblMaxPlayers.Location = new System.Drawing.Point(6, 139);
this.lblMaxPlayers.Name = "lblMaxPlayers";
this.lblMaxPlayers.Size = new System.Drawing.Size(70, 13);
this.lblMaxPlayers.TabIndex = 31;
this.lblMaxPlayers.Text = "Max. Players:";
//
// lblSrvName
//
this.lblSrvName.AutoSize = true;
this.lblSrvName.Location = new System.Drawing.Point(9, 61);
this.lblSrvName.Name = "lblSrvName";
this.lblSrvName.Size = new System.Drawing.Size(70, 13);
this.lblSrvName.TabIndex = 34;
this.lblSrvName.Text = "Server name:";
//
// tbSrvName
//
this.tbSrvName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbSrvName.Location = new System.Drawing.Point(86, 58);
this.tbSrvName.Name = "tbSrvName";
this.tbSrvName.Size = new System.Drawing.Size(361, 20);
this.tbSrvName.TabIndex = 33;
this.tbSrvName.TextChanged += new System.EventHandler(this.event_RefreshPreview);
//
// cbMonsters
//
this.cbMonsters.AutoSize = true;
this.cbMonsters.Location = new System.Drawing.Point(6, 289);
this.cbMonsters.Name = "cbMonsters";
this.cbMonsters.Size = new System.Drawing.Size(104, 17);
this.cbMonsters.TabIndex = 35;
this.cbMonsters.Text = "Enable monsters";
this.cbMonsters.UseVisualStyleBackColor = true;
this.cbMonsters.CheckedChanged += new System.EventHandler(this.event_RefreshPreview);
//
// cbHellworld
//
this.cbHellworld.AutoSize = true;
this.cbHellworld.Location = new System.Drawing.Point(116, 289);
this.cbHellworld.Name = "cbHellworld";
this.cbHellworld.Size = new System.Drawing.Size(160, 17);
this.cbHellworld.TabIndex = 36;
this.cbHellworld.Text = "Use The Nether World (Hell)";
this.cbHellworld.UseVisualStyleBackColor = true;
this.cbHellworld.CheckedChanged += new System.EventHandler(this.event_RefreshPreview);
//
// frmProperties
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(459, 496);
this.Controls.Add(this.cbHellworld);
this.Controls.Add(this.cbMonsters);
this.Controls.Add(this.lblSrvName);
this.Controls.Add(this.tbSrvName);
this.Controls.Add(this.numMaxPlayers);
this.Controls.Add(this.lblMaxPlayers);
this.Controls.Add(this.btnAutoDetect);
this.Controls.Add(this.lblRCONPass);
this.Controls.Add(this.tbRCONPass);
this.Controls.Add(this.lblRCONPort);
this.Controls.Add(this.tbRCONPort);
this.Controls.Add(this.cbRCONEnable);
this.Controls.Add(this.label1);
this.Controls.Add(this.numBackup);
this.Controls.Add(this.lblBackup);
this.Controls.Add(this.lblASSuffix);
this.Controls.Add(this.numAS);
this.Controls.Add(this.lblASPrefix);
this.Controls.Add(this.cbDefRank);
this.Controls.Add(this.lblDefRank);
this.Controls.Add(this.cbOnline);
this.Controls.Add(this.lblRecMem);
this.Controls.Add(this.numMemory);
this.Controls.Add(this.lblXmxXms);
this.Controls.Add(this.tbIntPort);
this.Controls.Add(this.lblIntPort);
this.Controls.Add(this.cbIP);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.tbPreview);
this.Controls.Add(this.lblLevel);
this.Controls.Add(this.tbLevel);
this.Controls.Add(this.tbPort);
this.Controls.Add(this.lblPort);
this.Controls.Add(this.lblIP);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Name = "frmProperties";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Server Properties";
this.Load += new System.EventHandler(this.frmProperties_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numMemory)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numAS)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numBackup)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numMaxPlayers)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblIP;
private System.Windows.Forms.Label lblPort;
private System.Windows.Forms.TextBox tbPort;
private System.Windows.Forms.TextBox tbLevel;
private System.Windows.Forms.Label lblLevel;
private System.Windows.Forms.TextBox tbPreview;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.ToolTip ttBase;
private System.Windows.Forms.ComboBox cbIP;
private System.Windows.Forms.Label lblIntPort;
private System.Windows.Forms.TextBox tbIntPort;
private System.Windows.Forms.Label lblXmxXms;
private System.Windows.Forms.NumericUpDown numMemory;
private System.Windows.Forms.Label lblRecMem;
private System.Windows.Forms.CheckBox cbOnline;
private System.Windows.Forms.Label lblDefRank;
private System.Windows.Forms.ComboBox cbDefRank;
private System.Windows.Forms.Label lblASPrefix;
private System.Windows.Forms.NumericUpDown numAS;
private System.Windows.Forms.Label lblASSuffix;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numBackup;
private System.Windows.Forms.Label lblBackup;
private System.Windows.Forms.CheckBox cbRCONEnable;
private System.Windows.Forms.TextBox tbRCONPort;
private System.Windows.Forms.Label lblRCONPort;
private System.Windows.Forms.TextBox tbRCONPass;
private System.Windows.Forms.Label lblRCONPass;
private System.Windows.Forms.Button btnAutoDetect;
private System.Windows.Forms.NumericUpDown numMaxPlayers;
private System.Windows.Forms.Label lblMaxPlayers;
private System.Windows.Forms.Label lblSrvName;
private System.Windows.Forms.TextBox tbSrvName;
private System.Windows.Forms.CheckBox cbMonsters;
private System.Windows.Forms.CheckBox cbHellworld;
}
} | 49.989691 | 164 | 0.576511 | [
"BSD-3-Clause"
] | astory/MCAdmin | MCAdmin/frmProperties.Designer.cs | 29,096 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlazorComponent
{
public static class DatePickerHeaderAbstractProviderExtensitions
{
public static ComponentAbstractProvider ApplyDatePickerHeaderDefault(this ComponentAbstractProvider abstractProvider)
{
return abstractProvider
.Apply(typeof(BDatePickerHeaderHeader<>), typeof(BDatePickerHeaderHeader<IDatePickerHeader>))
.Apply(typeof(BDatePickerHeaderBtn<>), typeof(BDatePickerHeaderBtn<IDatePickerHeader>));
}
}
}
| 33.052632 | 125 | 0.742038 | [
"MIT"
] | BlazorComponent/BlazorComponent | src/Component/BlazorComponent/Components/DatePicker/DatePickerHeader/DatePickerHeaderAbstractProviderExtensitions.cs | 630 | C# |
using System;
using System.Runtime.InteropServices;
namespace Meziantou.Framework.Win32.Natives
{
[ComImport(),
Guid(IIDGuid.IFileSaveDialog),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileSaveDialog : IFileDialog
{
[PreserveSig]
new int Show([In] IntPtr parent);
void SetFileTypes([In] uint cFileTypes, [In] ref COMDLG_FILTERSPEC rgFilterSpec);
new void SetFileTypeIndex([In] uint iFileType);
new void GetFileTypeIndex(out uint piFileType);
new void Advise([In, MarshalAs(UnmanagedType.Interface)] IFileDialogEvents pfde, out uint pdwCookie);
new void Unadvise([In] uint dwCookie);
new void SetOptions([In] FOS fos);
new void GetOptions(out FOS pfos);
new void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
new void SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
new void GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
new void GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
new void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
new void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
new void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
new void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
new void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
new void GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
//void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, FileDialogCustomPlace fdcp);
void AddPlace(); // incomplete signature
new void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
new void Close([MarshalAs(UnmanagedType.Error)] int hr);
new void SetClientGuid([In] ref Guid guid);
new void ClearClientData();
new void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
void SetSaveAsItem([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
void SetProperties([In, MarshalAs(UnmanagedType.Interface)] IntPtr pStore);
void SetCollectedProperties([In, MarshalAs(UnmanagedType.Interface)] IntPtr pList, [In] int fAppendDefault);
void GetProperties([MarshalAs(UnmanagedType.Interface)] out IntPtr ppStore);
void ApplyProperties([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In, MarshalAs(UnmanagedType.Interface)] IntPtr pStore, [In, ComAliasName("ShellObjects.wireHWND")] ref IntPtr hwnd, [In, MarshalAs(UnmanagedType.Interface)] IntPtr pSink);
}
}
| 61.955556 | 258 | 0.729197 | [
"MIT"
] | DomLatr/Meziantou.Framework | src/Meziantou.Framework.Win32.Dialogs/Natives/IFileSaveDialog.cs | 2,790 | C# |
// (c) Copyright HutongGames, LLC 2010-2021. All rights reserved.
// NOTE: The new Input System and legacy Input Manager can both be enabled in a project.
// This action was developed for the old input manager, so we will use it if its available.
// If only the new input system is available we will try to use that instead,
// but there might be subtle differences in the behaviour in the new system!
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
#define NEW_INPUT_SYSTEM_ONLY
#endif
using UnityEngine;
#if NEW_INPUT_SYSTEM_ONLY
using UnityEngine.InputSystem;
#endif
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.Input)]
[Tooltip("Gets the X Position of the mouse and stores it in a Float Variable.")]
public class GetMouseX : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("Store in a float variable.")]
public FsmFloat storeResult;
[Tooltip("Normalized coordinates are in the range 0 to 1 (0 = left, 1 = right). Otherwise the coordinate is in pixels. " +
"Normalized coordinates are useful for resolution independent functions.")]
public bool normalize;
[Tooltip("Repeat every frame.")]
public bool everyFrame;
public override void Reset()
{
storeResult = null;
normalize = true;
everyFrame = true;
}
public override void OnEnter()
{
DoGetMouseX();
if (!everyFrame)
{
Finish();
}
}
public override void OnUpdate()
{
DoGetMouseX();
}
private void DoGetMouseX()
{
if (storeResult != null)
{
#if NEW_INPUT_SYSTEM_ONLY
if (Mouse.current == null) return;
var xPos = Mouse.current.position.ReadValue().x;
#else
var xPos = Input.mousePosition.x;
#endif
if (normalize)
{
xPos /= Screen.width;
}
storeResult.Value = xPos;
}
}
#if UNITY_EDITOR
public override string AutoName()
{
return ActionHelpers.AutoName(this, storeResult);
}
#endif
}
}
| 24.197802 | 130 | 0.621253 | [
"MIT"
] | euphoriaer/Roguelike-fantasy | Project/ARMRP-unity/Assets/ThirdParty/PlayMaker/Actions/Input/GetMouseX.cs | 2,202 | C# |
using _03BarracksFactory.Contracts;
namespace _03BarracksFactory.Core.Commands
{
public class Report : Command
{
public Report(string[] data, IRepository repository, IUnitFactory factory)
: base(data, repository, factory)
{
}
public override string Execute()
{
string output = base.Repository.Statistics;
return output;
}
}
} | 23.555556 | 82 | 0.606132 | [
"MIT"
] | SonicTheCat/CSharp-OOP-Advanced | 08.Reflection And Attributes - Exercise/04.BarrackWarsTheCommandsStrikeBack/Core/Commands/Report.cs | 426 | C# |
using System;
using ImGuiNET;
using Microsoft.Xna.Framework.Graphics;
using Num = System.Numerics;
namespace Nez.ImGuiTools
{
class CoreWindow
{
string[] _textureFilters;
float[] _frameRateArray = new float[100];
int _frameRateArrayIndex = 0;
public CoreWindow()
{
_textureFilters = Enum.GetNames( typeof( TextureFilter ) );
}
public void show( ref bool isOpen )
{
if( !isOpen )
return;
ImGui.SetNextWindowPos( new Num.Vector2( Screen.width - 300, Screen.height - 240 ), ImGuiCond.FirstUseEver );
ImGui.SetNextWindowSize( new Num.Vector2( 300, 240 ), ImGuiCond.FirstUseEver );
ImGui.Begin( "Nez Core", ref isOpen );
drawSettings();
ImGui.End();
}
void drawSettings()
{
_frameRateArray[_frameRateArrayIndex] = ImGui.GetIO().Framerate;
_frameRateArrayIndex = ( _frameRateArrayIndex + 1 ) % _frameRateArray.Length;
ImGui.PlotLines( "##hidelabel", ref _frameRateArray[0], _frameRateArray.Length, _frameRateArrayIndex, $"FPS: {ImGui.GetIO().Framerate:0}", 0, 60, new Num.Vector2( ImGui.GetContentRegionAvail().X, 50 ) );
NezImGui.SmallVerticalSpace();
if( ImGui.CollapsingHeader( "Core Settings", ImGuiTreeNodeFlags.DefaultOpen ) )
{
ImGui.Checkbox( "exitOnEscapeKeypress", ref Core.exitOnEscapeKeypress );
ImGui.Checkbox( "pauseOnFocusLost", ref Core.pauseOnFocusLost );
ImGui.Checkbox( "debugRenderEnabled", ref Core.debugRenderEnabled );
}
if( ImGui.CollapsingHeader( "Core.defaultSamplerState", ImGuiTreeNodeFlags.DefaultOpen ) )
{
#if !FNA
ImGui.PushStyleVar( ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f );
NezImGui.DisableNextWidget();
#endif
var currentTextureFilter = (int)Core.defaultSamplerState.Filter;
if( ImGui.Combo( "Filter", ref currentTextureFilter, _textureFilters, _textureFilters.Length ) )
Core.defaultSamplerState.Filter = (TextureFilter)Enum.Parse( typeof( TextureFilter ), _textureFilters[currentTextureFilter] );
#if !FNA
ImGui.PopStyleVar();
#endif
}
}
}
}
| 37.104478 | 215 | 0.586484 | [
"MIT"
] | AlmostBearded/monogame-platformer | Platformer/Nez/Nez.ImGui/Inspectors/CoreWindow.cs | 2,486 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Brobot.Models.Economy;
using Discord.WebSocket;
using RestSharp;
namespace Brobot.Helpers
{
public class EconomyHelper
{
public static void DepositEconomy(ulong discordId, string discriminator, string username, ulong coins, string url)
{
try
{
var client = new RestClient(url+ "/api/v1/economy/createupdateuser");
var request = new RestRequest(Method.POST);
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
EconomyRequest economyRequest = new EconomyRequest();
economyRequest.discordID = discordId;
economyRequest.discriminator = discriminator;
economyRequest.username = username;
request.AddJsonBody(economyRequest);
IRestResponse response = client.Post(request);
Console.WriteLine(response.Content); //for logging purposes
if (response.StatusCode == HttpStatusCode.OK)
{
//deposit endpoint
var client2 = new RestClient(url+ "/api/v1/economy/depositcoins");
var request2 = new RestRequest(Method.POST);
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
DepositRequest deposit = new DepositRequest();
deposit.discordId = discordId;
deposit.coins = coins;
request2.AddJsonBody(deposit);
IRestResponse response2 = client2.Post(request2);
Console.WriteLine(response2.Content); //for logging purposes
}
else
{
Console.WriteLine("There has been an error in doing this. please check NOW");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
| 34.215385 | 133 | 0.578687 | [
"MIT"
] | DavCam05/Brobot | Helpers/EconomyHelper.cs | 2,226 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.