content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Input;
using Screna;
namespace Captura.Models
{
public class FileRecentItem : NotifyPropertyChanged, IRecentItem
{
public string FileName { get; }
public RecentFileType FileType { get; }
public FileRecentItem(string FileName, RecentFileType FileType, bool IsSaving = false)
{
this.FileName = FileName;
this.FileType = FileType;
this.IsSaving = IsSaving;
Display = Path.GetFileName(FileName);
ClickCommand = new DelegateCommand(() => ServiceProvider.LaunchFile(new ProcessStartInfo(FileName)));
RemoveCommand = new DelegateCommand(() => RemoveRequested?.Invoke());
var icons = ServiceProvider.Get<IIconSet>();
var loc = ServiceProvider.Get<LanguageManager>();
var windowService = ServiceProvider.Get<IMainWindow>();
Icon = GetIcon(FileType, icons);
IconColor = GetColor(FileType);
var list = new List<RecentAction>
{
new RecentAction(loc.CopyPath, icons.Clipboard, () => this.FileName.WriteToClipboard())
};
switch (FileType)
{
case RecentFileType.Image:
list.Add(new RecentAction(loc.CopyToClipboard, icons.Clipboard, OnCopyToClipboardExecute));
list.Add(new RecentAction(loc.UploadToImgur, icons.Upload, OnUploadToImgurExecute));
list.Add(new RecentAction(loc.Edit, icons.Pencil, () => windowService.EditImage(FileName)));
list.Add(new RecentAction(loc.Crop, icons.Crop, () => windowService.CropImage(FileName)));
break;
case RecentFileType.Audio:
case RecentFileType.Video:
list.Add(new RecentAction(loc.Trim, icons.Trim, () => windowService.TrimMedia(FileName)));
break;
}
list.Add(new RecentAction(loc.Delete, icons.Delete, OnDelete));
Actions = list;
}
async void OnUploadToImgurExecute()
{
if (!File.Exists(FileName))
{
ServiceProvider.MessageProvider.ShowError("File not Found");
return;
}
var img = (Bitmap)Image.FromFile(FileName);
await img.UploadToImgur();
}
void OnCopyToClipboardExecute()
{
if (!File.Exists(FileName))
{
ServiceProvider.MessageProvider.ShowError("File not Found");
return;
}
try
{
var img = (Bitmap)Image.FromFile(FileName);
img.WriteToClipboard();
}
catch (Exception e)
{
ServiceProvider.MessageProvider.ShowException(e, "Copy to Clipboard failed");
}
}
void OnDelete()
{
if (!ServiceProvider.MessageProvider.ShowYesNo($"Are you sure you want to Delete: {FileName}?", "Confirm Deletion"))
return;
try
{
File.Delete(FileName);
}
catch (Exception e)
{
ServiceProvider.MessageProvider.ShowException(e, $"Could not Delete: {FileName}");
return;
}
// Remove from List
RemoveRequested?.Invoke();
}
static string GetIcon(RecentFileType ItemType, IIconSet Icons)
{
switch (ItemType)
{
case RecentFileType.Audio:
return Icons.Music;
case RecentFileType.Image:
return Icons.Image;
case RecentFileType.Video:
return Icons.Video;
}
return null;
}
static string GetColor(RecentFileType ItemType)
{
switch (ItemType)
{
case RecentFileType.Audio:
return "DodgerBlue";
case RecentFileType.Image:
return "YellowGreen";
case RecentFileType.Video:
return "OrangeRed";
}
return null;
}
public string Display { get; }
public string Icon { get; }
public string IconColor { get; }
bool _saving;
public bool IsSaving
{
get => _saving;
private set
{
_saving = value;
OnPropertyChanged();
}
}
public void Saved()
{
IsSaving = false;
}
public event Action RemoveRequested;
public ICommand ClickCommand { get; }
public ICommand RemoveCommand { get; }
public IEnumerable<RecentAction> Actions { get; }
}
}
| 28.240223 | 128 | 0.525816 |
[
"MIT"
] |
ClsTe/CapturaKorean
|
src/Captura.Core/Models/Recents/FileRecentItem.cs
| 5,057 |
C#
|
using System;
public class StartUp
{
static void Main()
{
var carInfo = Console.ReadLine().Split();
Vehicle car = new Car(double.Parse(carInfo[1]), double.Parse(carInfo[2]), double.Parse(carInfo[3]));
var truckInfo = Console.ReadLine().Split();
Vehicle truck = new Truck(double.Parse(truckInfo[1]), double.Parse(truckInfo[2]), double.Parse(truckInfo[3]));
var busInfo = Console.ReadLine().Split();
Vehicle bus = new Bus(double.Parse(busInfo[1]), double.Parse(busInfo[2]), double.Parse(busInfo[3]));
var countOfCommands = int.Parse(Console.ReadLine());
for (int i = 0; i < countOfCommands; i++)
{
var commandArgs = Console.ReadLine().Split();
var command = commandArgs[0];
var typeOfVehicle = commandArgs[1];
var givenParam = double.Parse(commandArgs[2]);
Vehicle vehicleToOperate;
if (typeOfVehicle == "Car")
vehicleToOperate = car;
else if (typeOfVehicle == "Truck")
vehicleToOperate = truck;
else
vehicleToOperate = bus;
try
{
switch (command)
{
case "Drive":
vehicleToOperate.Drive(givenParam);
Console.WriteLine($"{vehicleToOperate.GetType().Name} travelled {givenParam} km");
break;
case "DriveEmpty":
((Bus)vehicleToOperate).DriveEmpty(givenParam);
Console.WriteLine($"{vehicleToOperate.GetType().Name} travelled {givenParam} km");
break;
case "Refuel":
vehicleToOperate.Refuel(givenParam);
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.WriteLine(car);
Console.WriteLine(truck);
Console.WriteLine(bus);
}
}
| 33.903226 | 118 | 0.50999 |
[
"MIT"
] |
spiderbait90/Step-By-Step-In-C-Sharp
|
C# Fundamentals/OOP Basic/Polymorphism/Vehicles/StartUp.cs
| 2,104 |
C#
|
namespace WmcSoft.Configuration
{
public class CheckpointA : CheckpointBase
{
public CheckpointA(string name) : base(name)
{
}
protected override bool DoVerify(int level)
{
return true;
}
}
}
| 17.733333 | 52 | 0.552632 |
[
"MIT"
] |
vjacquet/WmcSoft
|
WmcSoft.Configuration.Tests/Configuration/CheckpointA.cs
| 268 |
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using BDTest.Attributes;
using Humanizer;
using Newtonsoft.Json;
namespace BDTest.Test
{
public class TestDetails : BuildableTest
{
private readonly string _callerMember;
public string CallerFile { get; }
public string TestId { get; }
public IEnumerable<string> Parameters { get; set; }
internal int StepCount { get; set; }
internal TestDetails(string callerMember, string callerFile, Guid guid, string testId)
{
TestDetails = this;
Guid = guid;
_callerMember = callerMember;
CallerFile = callerFile;
TestId = testId;
SetStoryText();
SetScenarioText();
StepCount = 1;
}
[JsonConstructor]
private TestDetails()
{
}
private void SetStoryText()
{
var classStoryAttribute =
FindStoryAttribute();
if (classStoryAttribute == null)
{
StoryText = null;
return;
}
StoryText = new StoryText(classStoryAttribute.GetStoryText());
}
private static StoryAttribute FindStoryAttribute()
{
if (new StackTrace().GetFrames()
.FirstOrDefault(frame =>
frame.GetMethod()?.DeclaringType
?.GetCustomAttribute(typeof(StoryAttribute), true) is StoryAttribute)?.GetMethod()?.DeclaringType
?.GetCustomAttribute(typeof(StoryAttribute), true) is StoryAttribute classStoryAttribute)
{
return classStoryAttribute;
}
return null;
}
private void SetScenarioText()
{
var stackFrames = new StackTrace().GetFrames();
var stepAttributeFrame = stackFrames.FirstOrDefault(it => GetScenarioTextAttribute(it) != null);
if (stepAttributeFrame != null)
{
SetParameters(stepAttributeFrame);
ScenarioText = new ScenarioText($"{GetScenarioTextAttribute(stepAttributeFrame)}");
return;
}
var callingFrame = stackFrames.FirstOrDefault(it => it.GetMethod().Name == _callerMember);
if (callingFrame != null)
{
SetParameters(callingFrame);
ScenarioText = new ScenarioText($"{callingFrame.GetMethod().Name.Humanize()}");
return;
}
ScenarioText = new ScenarioText("No Scenario Text found (Use attribute [ScenarioText\"...\")] on your tests");
}
private void SetParameters(StackFrame callingFrame)
{
Parameters = callingFrame?.GetMethod()?.GetParameters().Select(it => it.Name);
}
private static string GetScenarioTextAttribute(StackFrame it)
{
return GetScenarioTextAttribute(it.GetMethod());
}
private static string GetScenarioTextAttribute(ICustomAttributeProvider it)
{
return ((ScenarioTextAttribute)(it.GetCustomAttributes(typeof(ScenarioTextAttribute), true) ??
new string[] { }).FirstOrDefault())?.Text;
}
public Guid GetGuid()
{
return Guid;
}
}
}
| 31.225225 | 122 | 0.568956 |
[
"Apache-2.0"
] |
afscrome/BDTest
|
BDTest/Test/TestDetails.cs
| 3,468 |
C#
|
using Xunit;
using Zpp.DbCache;
namespace Master40.XUnitTest.Zpp.Unit_Tests.Provider
{
public class TestProductionOrder : AbstractTest
{
public TestProductionOrder()
{
}
/**
* Verifies, that
* -
*/
[Fact(Skip = "Not implemented yet.")]
public void TestCreateProductionOrder()
{
IDbMasterDataCache dbMasterDataCache = new DbMasterDataCache(ProductionDomainContext);
IDbTransactionData dbTransactionData =
new DbTransactionData(ProductionDomainContext, dbMasterDataCache);
// TODO
Assert.True(false);
}
/**
* Verifies, that
* -
*/
[Fact(Skip = "Not implemented yet.")]
public void TestCreateProductionOrderBoms()
{
IDbMasterDataCache dbMasterDataCache = new DbMasterDataCache(ProductionDomainContext);
IDbTransactionData dbTransactionData =
new DbTransactionData(ProductionDomainContext, dbMasterDataCache);
// TODO
Assert.True(false);
}
}
}
| 26.733333 | 98 | 0.557772 |
[
"Apache-2.0"
] |
LennertBerkhan/ng-erp-4.0
|
Master40.XUnitTest/Zpp/Unit_Tests/Provider/TestProductionOrder.cs
| 1,203 |
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using Remotion.Linq.Parsing.ExpressionTreeVisitors;
using Restful.Linq;
using Restful.Data.MySql.CommandBuilders;
using Restful.Data.MySql.Common;
using Restful.Data.MySql.Visitors;
namespace Restful.Data.MySql.Linq
{
public class MySqlInsertProvider : IInsertProvider
{
private readonly ISessionProvider sessionProvider;
public MySqlInsertProvider( ISessionProvider sessionProvider )
{
this.sessionProvider = sessionProvider;
}
public IInsertable CreateInsert( Type elementType )
{
return (IInsertable)Activator.CreateInstance( typeof( MySqlInsertable<> ).MakeGenericType( elementType ), new object[] { this, elementType } );
}
public int Execute( Type elementType, IDictionary<MemberExpression, object> properties )
{
MySqlInsertCommandBuilder insertBuilder = new MySqlInsertCommandBuilder( elementType.Name );
foreach( var item in properties )
{
insertBuilder.AddColumn( item.Key.Member.Name, item.Value );
}
this.sessionProvider.ExecutedCommandBuilder = insertBuilder;
return this.sessionProvider.ExecuteNonQuery( insertBuilder );
}
public IInsertable<T> CreateInsert<T>()
{
return new MySqlInsertable<T>( this );
}
public int Execute<T>( IDictionary<MemberExpression, object> properties )
{
return this.Execute( typeof( T ), properties );
}
}
}
| 30.759259 | 155 | 0.669476 |
[
"Apache-2.0"
] |
linli8/Restful
|
src/Restful/Restful.Data.MySql/Linq/MySqlInsertProvider.cs
| 1,663 |
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("03. Mixed Phones")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. Mixed Phones")]
[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("b8aa2fd1-185b-40b9-9ef3-49b779d7bc55")]
// 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.837838 | 84 | 0.745 |
[
"Apache-2.0"
] |
Warglaive/DictionariesMoreTraining
|
Dicts/03. Mixed Phones/Properties/AssemblyInfo.cs
| 1,403 |
C#
|
using Adyen.Model.AdditionalData;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using Adyen.Model.ApplicationInformation;
using Adyen.Util;
namespace Adyen.Model.Binlookup
{
[DataContract]
public partial class DSPublicKeyDetail
{
}
}
| 18.222222 | 43 | 0.734756 |
[
"MIT"
] |
Ganesh-Chavan/adyen-dotnet-api-library
|
Adyen/Model/Binlookup/DSPublicKeyDetail.cs
| 330 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderSetSignature
{
private const string TestDynamicAssemblyName = "TestDynamicAssembly";
private const string TestDynamicModuleName = "TestDynamicModule";
private const string TestDynamicTypeName = "TestDynamicType";
private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
private const TypeAttributes TestTypeAttributes = TypeAttributes.Abstract;
private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual;
private const int MinStringLength = 1;
private const int MaxStringLength = 128;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private TypeBuilder GetTestTypeBuilder()
{
AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
assemblyName, TestAssemblyBuilderAccess);
ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName);
return moduleBuilder.DefineType(TestDynamicTypeName, TestTypeAttributes);
}
[Fact]
public void TestGenericMethodWithSingleGenericParameterSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
builder.SetSignature(desiredReturnType.AsType(), null, null, null, null, null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithMultipleGenericParameters()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T", "U" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[1];
builder.SetSignature(desiredReturnType.AsType(), null, null, null, null, null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithReturnTypeRequiredModifiersSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
builder.SetSignature(desiredReturnType.AsType(), null, null, null, null, null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithReturnTypeRequiredAndOptionalModifiersSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
null,
null,
null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithReturnTypeOptionalModifiersSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
null,
null,
null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithParameterTypesSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = new Type[] { typeof(int) };
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
null,
null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithMultipleParametersSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T", "U" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = new Type[] { typeof(int), typeParameters[1].AsType() };
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
null,
null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithParameterTypeRequiredModifierSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = new Type[] { typeof(int) };
Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][];
for (int i = 0; i < desiredParamType.Length; ++i)
{
parameterTypeRequiredCustomModifiers[i] = null;
}
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
parameterTypeRequiredCustomModifiers,
null);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithParameterTypeRequiredAndOptionModifierSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = new Type[] { typeof(int) };
Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][];
Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][];
for (int i = 0; i < desiredParamType.Length; ++i)
{
parameterTypeRequiredCustomModifiers[i] = null;
parameterTypeOptionalCustomModifiers[i] = null;
}
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
parameterTypeRequiredCustomModifiers,
parameterTypeOptionalCustomModifiers);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestGenericMethodWithParameterTypeOptionalModifierSet()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = new Type[] { typeof(int) };
Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][];
for (int i = 0; i < desiredParamType.Length; ++i)
{
parameterTypeOptionalCustomModifiers[i] = null;
}
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
null,
parameterTypeOptionalCustomModifiers);
VerifyMethodSignature(typeBuilder, builder, desiredReturnType.AsType());
}
[Fact]
public void TestWithNonGenericMethod()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
Type[] parameterTypes = new Type[] { typeof(string), typeof(object) };
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes,
typeof(void),
parameterTypes);
string[] parameterNames = new string[parameterTypes.Length];
for (int i = 0; i < parameterNames.Length; ++i)
{
parameterNames[i] = "P" + i.ToString();
builder.DefineParameter(i + 1, ParameterAttributes.In, parameterNames[i]);
}
Type desiredReturnType = typeof(void);
Type[] desiredParamType = new Type[] { typeof(int) };
Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][];
Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][];
for (int i = 0; i < desiredParamType.Length; ++i)
{
parameterTypeRequiredCustomModifiers[i] = null;
parameterTypeOptionalCustomModifiers[i] = null;
}
builder.SetSignature(
desiredReturnType,
null,
null,
desiredParamType,
parameterTypeRequiredCustomModifiers,
parameterTypeOptionalCustomModifiers);
}
[Fact]
public void TestWithNullOnParameters()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
builder.SetSignature(null, null, null, null, null, null);
VerifyMethodSignature(typeBuilder, builder, null);
}
[Fact]
public void TestWithNullOnReturnTypeWithModifiersSetToWrongTypes()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
builder.SetSignature(
null,
null,
null,
null,
null,
null);
VerifyMethodSignature(typeBuilder, builder, null);
}
[Fact]
public void TestWithNullOnReturnTypeWithModifiersSetCorrectly()
{
string methodName = null;
int arraySize = 0;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
arraySize = _generator.GetByte();
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = null;
Type[][] parameterTypeRequiredCustomModifiers = new Type[arraySize][];
Type[][] parameterTypeOptionalCustomModifiers = new Type[arraySize][];
for (int i = 0; i < arraySize; ++i)
{
parameterTypeRequiredCustomModifiers[i] = null;
parameterTypeOptionalCustomModifiers[i] = null;
}
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
parameterTypeRequiredCustomModifiers,
parameterTypeOptionalCustomModifiers);
}
[Fact]
public void TestWithNullOnReturnTypeModifiers()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
TestMethodAttributes);
string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParameters =
builder.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder desiredReturnType = typeParameters[0];
Type[] desiredParamType = new Type[] { typeof(void) };
Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][];
Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][];
for (int i = 0; i < desiredParamType.Length; ++i)
{
parameterTypeRequiredCustomModifiers[i] = null;
parameterTypeOptionalCustomModifiers[i] = null;
}
builder.SetSignature(
desiredReturnType.AsType(),
null,
null,
desiredParamType,
parameterTypeRequiredCustomModifiers,
parameterTypeOptionalCustomModifiers);
}
private void VerifyMethodSignature(TypeBuilder typeBuilder, MethodBuilder builder, Type desiredReturnType)
{
Type ret = typeBuilder.CreateTypeInfo().AsType();
MethodInfo methodInfo = builder.GetBaseDefinition();
Type actualReturnType = methodInfo.ReturnType;
if (desiredReturnType == null)
Assert.Null(actualReturnType);
if (desiredReturnType != null)
{
Assert.NotNull(actualReturnType);
Assert.Equal(desiredReturnType.Name, actualReturnType.Name);
Assert.True(actualReturnType.Equals(desiredReturnType));
}
}
}
}
| 40.36887 | 141 | 0.617599 |
[
"MIT"
] |
Priya91/corefx-1
|
src/System.Reflection.Emit/tests/MethodBuilder/MethodBuilderSetSignature.cs
| 18,933 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
namespace RhinoInside.Revit.External.DB.Extensions
{
public static class BuiltInParameterExtension
{
private static readonly SortedSet<BuiltInParameter> builtInParameters =
new SortedSet<BuiltInParameter>
(
Enum.GetValues(typeof(BuiltInParameter)).
Cast<BuiltInParameter>().Where( x => x != BuiltInParameter.INVALID)
);
/// <summary>
/// Set of valid <see cref="Autodesk.Revit.DB.BuiltInParameter"/> enum values.
/// </summary>
public static IReadOnlyCollection<BuiltInParameter> BuiltInParameters => builtInParameters;
/// <summary>
/// Checks if a <see cref="Autodesk.Revit.DB.BuiltInParameter"/> is valid.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsValid(this BuiltInParameter value)
{
if (-2000000 < (int) value && (int) value < -1000000)
return builtInParameters.Contains(value);
return false;
}
/// <summary>
/// Internal Dictionary that maps <see cref="BuiltInParameter"/> by name.
/// Results are implicitly orderd by value in the <see cref="BuiltInParameter"/> enum.
/// </summary>
internal static readonly IReadOnlyDictionary<string, BuiltInParameter[]> BuiltInParameterMap =
Enum.GetValues(typeof(BuiltInParameter)).
Cast<BuiltInParameter>().
Where
(
x =>
{
try { return !string.IsNullOrEmpty(LabelUtils.GetLabelFor(x)); }
catch { return false; }
}
).
GroupBy(x => LabelUtils.GetLabelFor(x)).
ToDictionary(x => x.Key, x=> x.ToArray());
/// <summary>
/// <see cref="Autodesk.Revit.DB.BuiltInParameter"/> has duplicate values.
/// This method returns the string representatiopn of the most generic form.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToStringGeneric(this BuiltInParameter value)
{
switch (value)
{
case BuiltInParameter.GENERIC_THICKNESS: return "GENERIC_THICKNESS";
case BuiltInParameter.GENERIC_WIDTH: return "GENERIC_WIDTH";
case BuiltInParameter.GENERIC_HEIGHT: return "GENERIC_HEIGHT";
case BuiltInParameter.GENERIC_DEPTH: return "GENERIC_DEPTH";
case BuiltInParameter.GENERIC_FINISH: return "GENERIC_FINISH";
case BuiltInParameter.GENERIC_CONSTRUCTION_TYPE: return "GENERIC_CONSTRUCTION_TYPE";
case BuiltInParameter.FIRE_RATING: return "FIRE_RATING";
case BuiltInParameter.ALL_MODEL_COST: return "ALL_MODEL_COST";
case BuiltInParameter.ALL_MODEL_MARK: return "ALL_MODEL_MARK";
case BuiltInParameter.ALL_MODEL_FAMILY_NAME: return "ALL_MODEL_FAMILY_NAME";
case BuiltInParameter.ALL_MODEL_TYPE_NAME: return "ALL_MODEL_TYPE_NAME";
case BuiltInParameter.ALL_MODEL_TYPE_MARK: return "ALL_MODEL_TYPE_MARK";
}
return value.ToString();
}
}
public static class ParameterTypeExtension
{
public static StorageType ToStorageType(this ParameterType parameterType)
{
switch (parameterType)
{
case ParameterType.Invalid:
return StorageType.None;
case ParameterType.Text:
case ParameterType.MultilineText:
case ParameterType.URL:
return StorageType.String;
case ParameterType.YesNo:
case ParameterType.Integer:
case ParameterType.LoadClassification:
return StorageType.Integer;
case ParameterType.Material:
case ParameterType.FamilyType:
case ParameterType.Image:
return StorageType.ElementId;
case ParameterType.Number:
default:
return StorageType.Double;
}
}
}
public static class ParameterExtension
{
public static bool ResetValue(this Parameter parameter)
{
if (!parameter.HasValue)
return true;
#if REVIT_2020
if (parameter.IsShared && (parameter.Definition as ExternalDefinition).HideWhenNoValue)
return parameter.ClearValue();
#endif
switch (parameter.StorageType)
{
case StorageType.Integer: return parameter.AsInteger() == 0 || parameter.Set(0);
case StorageType.Double: return parameter.AsDouble() == 0.0 || parameter.Set(0.0);
case StorageType.String: return parameter.AsString() == string.Empty || parameter.Set(string.Empty);
case StorageType.ElementId: return parameter.AsElementId() == ElementId.InvalidElementId || parameter.Set(ElementId.InvalidElementId);
}
return false;
}
}
}
| 36.856061 | 142 | 0.650565 |
[
"MIT"
] |
Super-create/rhino.inside-rev
|
src/RhinoInside.Revit/External/DB/Extensions/Parameter.cs
| 4,865 |
C#
|
using UnityEngine;
using System.Collections;
public class RepeatTexture : MonoBehaviour {
void Start () {
GetComponent<Renderer>().material.mainTextureScale = new Vector2(100, 100);
}
}
| 20.6 | 83 | 0.699029 |
[
"MIT"
] |
Tagglink/Target
|
Assets/Scripts/RepeatTexture.cs
| 208 |
C#
|
using System;
using System.Collections.Generic;
using LibCommon;
using LibCommon.Structs.WebRequest.AKStreamKeeper;
using LibCommon.Structs.WebResponse.AKStreamKeeper;
namespace LibZLMediaKitMediaServer
{
public class KeeperWebApi
{
private string _accessKey;
private string _baseUrl;
private int _httpClientTimeout;
private string _ipAddress;
private ushort _webApiPort;
public KeeperWebApi(string ipAddress, ushort webApiPort, string accessKey, int httpClientTimeoutSec = 5)
{
_ipAddress = ipAddress;
_webApiPort = webApiPort;
_accessKey = accessKey;
_baseUrl = $"http://{_ipAddress}:{_webApiPort}";
_httpClientTimeout = httpClientTimeoutSec * 1000;
}
public string IpAddress
{
get => _ipAddress;
set => _ipAddress = value;
}
public ushort WebApiPort
{
get => _webApiPort;
set => _webApiPort = value;
}
public string AccessKey
{
get => _accessKey;
set => _accessKey = value;
}
public int HttpClientTimeout
{
get => _httpClientTimeout;
set => _httpClientTimeout = value;
}
/// <summary>
/// 获取AKStreamKeeper的版本标识
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public string GetAKStreamKeeperVersion(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/GetAKStreamKeeperVersion";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
return httpRet;
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 获取运行状态
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public ResKeeperCheckMediaServerRunning CheckMediaServerRunning(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/CheckMediaServerRunning";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
int pid = 0;
var ret = int.TryParse(httpRet, out pid);
if (ret && pid > 0)
{
var result = new ResKeeperCheckMediaServerRunning()
{
IsRunning = true,
Pid = pid,
};
return result;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 释放被使用过的rtp端口,以防止段时间内同样的端口被重复使用
/// </summary>
/// <param name="port"></param>
/// <param name="rs"></param>
/// <returns></returns>
public bool ReleaseRtpPort(ushort port, out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/ReleaseRtpPort?port={port}";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return false;
}
bool isOk = false;
var ret = bool.TryParse(httpRet, out isOk);
if (ret)
{
return isOk;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// 热加载配置文件
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public bool ReloadMediaServer(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/ReloadMediaServer";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return false;
}
bool isOk = false;
var ret = bool.TryParse(httpRet, out isOk);
if (ret)
{
return isOk;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// 重启流媒体服务器
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public ResKeeperRestartMediaServer RestartMediaServer(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/RestartMediaServer";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
int pid = 0;
var ret = int.TryParse(httpRet, out pid);
if (ret && pid > 0)
{
var result = new ResKeeperRestartMediaServer()
{
IsRunning = true,
Pid = pid,
};
return result;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 关闭流媒体服务器
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public bool ShutdownMediaServer(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/ShutdownMediaServer";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return false;
}
bool isOk = false;
var ret = bool.TryParse(httpRet, out isOk);
if (ret)
{
return isOk;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// 启动流媒体服务器
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public ResKeeperStartMediaServer StartMediaServer(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/StartMediaServer";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
int pid = 0;
var ret = int.TryParse(httpRet, out pid);
if (ret && pid > 0)
{
var result = new ResKeeperStartMediaServer()
{
IsRunning = true,
Pid = pid,
};
return result;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 清理空目录
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public bool CleanUpEmptyDir(out ResponseStruct rs, string? filePath = "")
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/CleanUpEmptyDir";
url += !string.IsNullOrEmpty(filePath) ? "?filePath=" + filePath : "";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return false;
}
bool isOk = false;
var ret = bool.TryParse(httpRet, out isOk);
if (ret)
{
return isOk;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// 批量删除文件
/// </summary>
/// <param name="rs"></param>
/// <param name="req"></param>
/// <returns>未能正常删除的文件列表</returns>
public ResKeeperDeleteFileList DeleteFileList(out ResponseStruct rs, List<string> req)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/DeleteFileList";
try
{
string reqData = JsonHelper.ToJson(req);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpPostRequest(url, headers, reqData, "utf-8", _httpClientTimeout * 12);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
var resKeeperDeleteFileList = JsonHelper.FromJson<ResKeeperDeleteFileList>(httpRet);
if (resKeeperDeleteFileList != null)
{
return resKeeperDeleteFileList;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
return null;
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 文件是否存在
/// </summary>
/// <param name="rs"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public bool FileExists(out ResponseStruct rs, string filePath)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/FileExists?filePath={filePath}";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return false;
}
bool isOk = false;
var ret = bool.TryParse(httpRet, out isOk);
if (ret)
{
return isOk;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// Keeper的健康情况
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public bool KeeperHealth(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/WebApiHealth";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet) && httpRet.Trim().ToUpper().Equals("OK"))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="rs"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public bool DeleteFile(out ResponseStruct rs, string filePath)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/DeleteFile?filePath={filePath}";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return false;
}
bool isOk = false;
var ret = bool.TryParse(httpRet, out isOk);
if (ret)
{
return isOk;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return false;
}
/// <summary>
/// 获取一个可用的rtp端口(偶数端口)
/// </summary>
/// <param name="rs"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public ushort GuessAnRtpPort(out ResponseStruct rs, ushort? min = 0, ushort? max = 0)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/ApiService/GuessAnRtpPort";
url += (min != null && min > 0) ? "?min=" + min : "";
if (url.Contains('?'))
{
url += (max != null && max > 0) ? "&max=" + max : "";
}
else
{
url += (max != null && max > 0) ? "?max=" + max : "";
}
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return 0;
}
ushort port = 0;
var ret = ushort.TryParse(httpRet, out port);
if (ret)
{
return port;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return 0;
}
/// <summary>
/// 获取裁剪合并任务积压列表
/// </summary>
/// <param name="rs"></param>
/// <returns></returns>
public ResKeeperCutMergeTaskStatusResponseList GetBacklogTaskList(out ResponseStruct rs)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/CutMergeService/GetBacklogTaskList";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
var reslist = JsonHelper.FromJson<ResKeeperCutMergeTaskStatusResponseList>(httpRet);
if (reslist != null)
{
return reslist;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
return null;
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 获取裁剪合并任务状态
/// </summary>
/// <param name="rs"></param>
/// <param name="taskId"></param>
/// <returns></returns>
public ResKeeperCutMergeTaskStatusResponse GetMergeTaskStatus(out ResponseStruct rs, string taskId)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/CutMergeService/GetMergeTaskStatus?taskId={taskId}";
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpGetRequest(url, headers, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
var resCutMergeTaskStatusResponse =
JsonHelper.FromJson<ResKeeperCutMergeTaskStatusResponse>(httpRet);
if (resCutMergeTaskStatusResponse != null)
{
return resCutMergeTaskStatusResponse;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
return null;
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
/// <summary>
/// 添加一个裁剪合并任务
/// </summary>
/// <param name="rs"></param>
/// <param name="reqKeeper"></param>
/// <returns></returns>
public ResKeeperCutMergeTaskResponse AddCutOrMergeTask(out ResponseStruct rs, ReqKeeperCutMergeTask reqKeeper)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.None,
Message = ErrorMessage.ErrorDic![ErrorNumber.None],
};
string url = $"{_baseUrl}/CutMergeService/AddCutOrMergeTask";
try
{
string reqData = JsonHelper.ToJson(reqKeeper);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("AccessKey", _accessKey);
var httpRet = NetHelper.HttpPostRequest(url, headers, reqData, "utf-8", _httpClientTimeout);
if (!string.IsNullOrEmpty(httpRet))
{
if (UtilsHelper.HttpClientResponseIsNetWorkError(httpRet))
{
rs = new ResponseStruct()
{
Code = ErrorNumber.Sys_HttpClientTimeout,
Message = ErrorMessage.ErrorDic![ErrorNumber.Sys_HttpClientTimeout],
};
return null;
}
var resCutMergeTaskResponse = JsonHelper.FromJson<ResKeeperCutMergeTaskResponse>(httpRet);
if (resCutMergeTaskResponse != null)
{
return resCutMergeTaskResponse;
}
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
ExceptMessage = httpRet,
ExceptStackTrace = "",
};
}
else
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiDataExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiDataExcept],
};
}
}
catch (Exception ex)
{
rs = new ResponseStruct()
{
Code = ErrorNumber.MediaServer_WebApiExcept,
Message = ErrorMessage.ErrorDic![ErrorNumber.MediaServer_WebApiExcept],
ExceptMessage = ex.Message,
ExceptStackTrace = ex.StackTrace,
};
}
return null;
}
}
}
| 37.501764 | 118 | 0.447551 |
[
"MIT"
] |
soon14/AKStream
|
LibZLMediaKitMediaServer/KeeperWebApi.cs
| 42,837 |
C#
|
using System;
using RabbitMQ.Client;
namespace MyLab.RabbitClient.Connection
{
class BackgroundRabbitConnectionProvider : IRabbitConnectionProvider
{
private readonly IBackgroundRabbitConnectionManager _connectionManager;
public BackgroundRabbitConnectionProvider(IBackgroundRabbitConnectionManager connectionManager)
{
_connectionManager = connectionManager;
_connectionManager.Connected += (sender, args) => OnReconnected();
}
public event EventHandler Reconnected;
public IConnection Provide()
{
var resultConnection = _connectionManager.ProvideConnection();
return resultConnection ?? throw new RabbitNotConnectedException();
}
protected virtual void OnReconnected()
{
Reconnected?.Invoke(this, EventArgs.Empty);
}
}
}
| 28.709677 | 103 | 0.685393 |
[
"MIT"
] |
mylab-tools/rabbit-client
|
src/MyLab.RabbitClient/Connection/BackgroundRabbitConnectionProvider.cs
| 892 |
C#
|
namespace BlepClick.Events
{
public enum AciEventType : byte
{
DeviceStarted = 0x81,
Echo = 0x82,
CommandResponse = 0x84,
Connected = 0x85,
Disconnected = 0x86,
BondStatus = 0x87,
PipeStatus = 0x88,
TimingEvent = 0x89,
DataCredit = 0x8A,
DataReceived = 0x8C,
PipeError = 0x8D,
DisplayKey = 0x8E
}
public static class AciEventTypeExtensions
{
public static string GetName(this AciEventType eventType)
{
switch (eventType)
{
case AciEventType.BondStatus:
return "BondStatus";
case AciEventType.CommandResponse:
return "CommandResponse";
case AciEventType.Connected:
return "Connected";
case AciEventType.DataCredit:
return "DataCredit";
case AciEventType.DataReceived:
return "DataReceived";
case AciEventType.DeviceStarted:
return "DeviceStarted";
case AciEventType.Disconnected:
return "Disconnected";
case AciEventType.Echo:
return "Echo";
case AciEventType.PipeError:
return "PipeError";
case AciEventType.PipeStatus:
return "PipeStatus";
case AciEventType.TimingEvent:
return "TimingEvent";
default:
return eventType.ToString();
}
}
}
}
| 25.630769 | 65 | 0.497599 |
[
"Apache-2.0",
"MIT"
] |
bauland/TinyClrLib
|
Modules/Mikro Click/Bluetooth LE Module/Events/AciEventType.cs
| 1,668 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ServerSessionService
{
private NetServer netServer;
public ServerSessionService()
{
// Server Start
netServer = new NetServer();
netServer.Start(7777, 0);
}
public NetServer GetNetServer()
{
return netServer;
}
public void OnPlayerConnected(int clientId)
{
LogManager.Singleton.WriteLog("[ServerManager] On Player Connected. clientId=" + clientId);
//TODO: Validation Logic
//Broadcast Newly joined player's sessionID
netServer.SendMessage(clientId, NetPacket.GeneratePacketIdTimestamp(), PacketType.CONNECT, "" + clientId);
}
public void OnPlayerDisconnected(int clientId)
{
//// Remote disconnected player from playerpool
//Destroy(playerPool[clientId]);
//Destroy(gameObjectPool[clientId]);
////
//playerPool.Remove(clientId);
//gameObjectPool.Remove(clientId);
////
///
ServerManager.Singleton.serverPlayService.HandlePlayerDisconnect(clientId);
GameModel.PlayerObject playerObject = new GameModel.PlayerObject(clientId, "Player[" + clientId + "]", 0, 0, false);
string message = JsonUtility.ToJson(playerObject);
netServer.Broadcast(NetPacket.GeneratePacketIdTimestamp(), PacketType.DISCONNECT, message);
LogManager.Singleton.WriteLog("[ServerManager] Player[" + clientId + "] disconnected");
}
public NetMessageQueue GetMessageQueue()
{
return netServer.netMessageQueue;
}
public NetMessage PopMessage()
{
return netServer.netMessageQueue.PopMessage();
}
}
| 27.444444 | 124 | 0.667438 |
[
"MIT"
] |
jinspark-lab/MultiplayChasingGame
|
Assets/Scripts/GameServer/GameLogic/ServerSessionService.cs
| 1,729 |
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 Schema Extension.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class SchemaExtension : Entity
{
/// <summary>
/// Gets or sets description.
/// Description for the schema extension.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "description", Required = Newtonsoft.Json.Required.Default)]
public string Description { get; set; }
/// <summary>
/// Gets or sets target types.
/// Set of Microsoft Graph types (that can support extensions) that the schema extension can be applied to. Select from contact, device, event, group, message, organization, post, or user.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "targetTypes", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<string> TargetTypes { get; set; }
/// <summary>
/// Gets or sets properties.
/// The collection of property names and types that make up the schema extension definition.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "properties", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<ExtensionSchemaProperty> Properties { get; set; }
/// <summary>
/// Gets or sets status.
/// The lifecycle state of the schema extension. Possible states are InDevelopment, Available, and Deprecated. Automatically set to InDevelopment on creation. Schema extensions provides more information on the possible state transitions and behaviors.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "status", Required = Newtonsoft.Json.Required.Default)]
public string Status { get; set; }
/// <summary>
/// Gets or sets owner.
/// The appId of the application that is the owner of the schema extension. This property can be supplied on creation, to set the owner. If not supplied, then the calling application's appId will be set as the owner. In either case, the signed-in user must be the owner of the application. Once set, this property is read-only and cannot be changed.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "owner", Required = Newtonsoft.Json.Required.Default)]
public string Owner { get; set; }
}
}
| 51.444444 | 358 | 0.652268 |
[
"MIT"
] |
gurry/msgraph-beta-sdk-dotnet
|
src/Microsoft.Graph/Models/Generated/SchemaExtension.cs
| 3,241 |
C#
|
// Copyright (c) Cragon. All rights reserved.
namespace GameCloud.Unity.Common
{
using System;
using System.Collections.Generic;
using System.Text;
public class Action1 : BehaviorComponent
{
//---------------------------------------------------------------------
private Func<BehaviorTree, object[], BehaviorReturnCode> mAction;
private object[] mListParam;
//---------------------------------------------------------------------
public Action1(BehaviorTree bt, Func<BehaviorTree, object[], BehaviorReturnCode> action, params object[] list_param)
: base(bt)
{
mAction = action;
mListParam = list_param;
}
//---------------------------------------------------------------------
public override BehaviorReturnCode Behave()
{
try
{
switch (mAction.Invoke(mBehaviorTree, mListParam))
{
case BehaviorReturnCode.Success:
ReturnCode = BehaviorReturnCode.Success;
return ReturnCode;
case BehaviorReturnCode.Failure:
ReturnCode = BehaviorReturnCode.Failure;
return ReturnCode;
case BehaviorReturnCode.Running:
ReturnCode = BehaviorReturnCode.Running;
return ReturnCode;
default:
ReturnCode = BehaviorReturnCode.Failure;
return ReturnCode;
}
}
catch (Exception e)
{
EbLog.Error(e.ToString());
ReturnCode = BehaviorReturnCode.Failure;
return ReturnCode;
}
}
}
}
| 34.792453 | 124 | 0.449566 |
[
"MIT"
] |
BOBO41/CasinosClient
|
_Backup/BehaviorTree/Actions/Action1.cs
| 1,846 |
C#
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ManagementGroups
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// EntitiesOperations operations.
/// </summary>
internal partial class EntitiesOperations : IServiceOperations<ManagementGroupsAPIClient>, IEntitiesOperations
{
/// <summary>
/// Initializes a new instance of the EntitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal EntitiesOperations(ManagementGroupsAPIClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ManagementGroupsAPIClient
/// </summary>
public ManagementGroupsAPIClient Client { get; private set; }
/// <summary>
/// List all entities (Management Groups, Subscriptions, etc.) for the
/// authenticated user.
///
/// </summary>
/// <param name='groupName'>
/// A filter which allows the call to be filtered for a specific group.
/// </param>
/// <param name='cacheControl'>
/// Indicates that the request shouldn't utilize any caches.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<EntityInfo>>> ListWithHttpMessagesAsync(string groupName = default(string), string cacheControl = "no-cache", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("groupName", groupName);
tracingParameters.Add("cacheControl", cacheControl);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Management/getEntities").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (Client.Skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", System.Uri.EscapeDataString(Client.Skiptoken)));
}
if (groupName != null)
{
_queryParameters.Add(string.Format("groupName={0}", System.Uri.EscapeDataString(groupName)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (cacheControl != null)
{
if (_httpRequest.Headers.Contains("Cache-Control"))
{
_httpRequest.Headers.Remove("Cache-Control");
}
_httpRequest.Headers.TryAddWithoutValidation("Cache-Control", cacheControl);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<EntityInfo>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<EntityInfo>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List all entities (Management Groups, Subscriptions, etc.) for the
/// authenticated user.
///
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cacheControl'>
/// Indicates that the request shouldn't utilize any caches.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<EntityInfo>>> ListNextWithHttpMessagesAsync(string nextPageLink, string cacheControl = "no-cache", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cacheControl", cacheControl);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (cacheControl != null)
{
if (_httpRequest.Headers.Contains("Cache-Control"))
{
_httpRequest.Headers.Remove("Cache-Control");
}
_httpRequest.Headers.TryAddWithoutValidation("Cache-Control", cacheControl);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<EntityInfo>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<EntityInfo>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 43.37355 | 285 | 0.558094 |
[
"MIT"
] |
alexeldeib/azure-sdk-for-net
|
src/SDKs/ManagementGroups/Management.ManagementGroups/Generated/EntitiesOperations.cs
| 18,694 |
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Creatures")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Creatures")]
[assembly: System.Reflection.AssemblyTitleAttribute("Creatures")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.708333 | 80 | 0.645855 |
[
"MIT"
] |
aawadall/Game-Off-2018
|
code/Creatures/obj/Debug/netstandard2.0/Creatures.AssemblyInfo.cs
| 977 |
C#
|
using System;
using System.Collections.Generic;
namespace BikeStore.Models
{
public partial class Categories
{
public Categories()
{
Products = new HashSet<Products>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Products> Products { get; set; }
}
}
| 20.421053 | 67 | 0.60567 |
[
"MIT"
] |
jo3l17/CodiGo3
|
Backend/Semana14/BikeStore/BikeStore/BikeStore/Models/Categories.cs
| 390 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public interface IMultiPercolateRequest : IFixedIndexTypePath<MultiPercolateRequestParameters>
{
IList<IPercolateOperation> Percolations { get; set; }
}
internal static class MultiPercolatePathInfo
{
public static void Update(ElasticsearchPathInfo<MultiPercolateRequestParameters> pathInfo, IMultiPercolateRequest request)
{
pathInfo.HttpMethod = PathInfoHttpMethod.POST;
}
}
public partial class MultiPercolateRequest : FixedIndexTypePathBase<MultiPercolateRequestParameters>, IMultiPercolateRequest
{
public IList<IPercolateOperation> Percolations { get; set; }
protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<MultiPercolateRequestParameters> pathInfo)
{
MultiPercolatePathInfo.Update(pathInfo, this);
}
}
[DescriptorFor("Mpercolate")]
public partial class MultiPercolateDescriptor : FixedIndexTypePathDescriptor<MultiPercolateDescriptor, MultiPercolateRequestParameters>, IMultiPercolateRequest
{
private IMultiPercolateRequest Self { get { return this; } }
IList<IPercolateOperation> IMultiPercolateRequest.Percolations { get; set; }
public MultiPercolateDescriptor()
{
this.Self.Percolations = new List<IPercolateOperation>();
}
public MultiPercolateDescriptor Percolate<T>(Func<PercolateDescriptor<T>, PercolateDescriptor<T>> getSelector)
where T : class
{
getSelector.ThrowIfNull("getSelector");
var descriptor = getSelector(new PercolateDescriptor<T>().Index<T>().Type<T>());
Self.Percolations.Add(descriptor);
return this;
}
public MultiPercolateDescriptor Count<T>(Func<PercolateCountDescriptor<T>, PercolateCountDescriptor<T>> getSelector)
where T : class
{
getSelector.ThrowIfNull("getSelector");
var descriptor = getSelector(new PercolateCountDescriptor<T>().Index<T>().Type<T>());
Self.Percolations.Add(descriptor);
return this;
}
protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<MultiPercolateRequestParameters> pathInfo)
{
MultiPercolatePathInfo.Update(pathInfo, this);
}
}
}
| 32.380282 | 160 | 0.791214 |
[
"Apache-2.0"
] |
Tasteful/elasticsearch-net
|
src/Nest/DSL/MultiPercolateDescriptor.cs
| 2,301 |
C#
|
using System.Threading;
using Streamliner.Actions;
using Streamliner.Blocks.Base;
using Streamliner.Core.Links;
using Streamliner.Definitions;
using Streamliner.Definitions.Metadata.Blocks;
namespace Streamliner.Blocks
{
public sealed class ConsumerBlock<T> : BlockBase, ITargetBlock<T>
{
public IBlockLinkReceiver<T> Receiver { get; }
private readonly ConsumerBlockActionBase<T> _action;
public ConsumerBlock(BlockHeader header, IBlockLinkReceiver<T> receiver, ConsumerBlockActionBase<T> action, FlowConsumerDefinition<T> definition) :
base(header, definition.Settings)
{
Receiver = receiver;
_action = action;
}
protected override void ProcessItem(CancellationToken token = default(CancellationToken))
{
T item = Receiver.Receive(token);
_action.Consume(item, token);
}
protected override void OnStart(object context = null)
{
_action.Start(context);
base.OnStart(context);
}
protected override void OnStop()
{
_action.Stop();
base.OnStop();
}
}
}
| 28.97561 | 155 | 0.641414 |
[
"MIT"
] |
Codeh4ck/Streamliner
|
Streamliner/Blocks/ConsumerBlock.cs
| 1,190 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.ResourceManager.Compute.Models
{
/// <summary> The Reboot Role Instance asynchronous operation requests a reboot of a role instance in the cloud service. </summary>
public partial class CloudServiceRoleInstanceRestartOperation : Operation
{
private readonly OperationInternals _operation;
/// <summary> Initializes a new instance of CloudServiceRoleInstanceRestartOperation for mocking. </summary>
protected CloudServiceRoleInstanceRestartOperation()
{
}
internal CloudServiceRoleInstanceRestartOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response)
{
_operation = new OperationInternals(clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "CloudServiceRoleInstanceRestartOperation");
}
/// <inheritdoc />
public override string Id => _operation.Id;
/// <inheritdoc />
public override bool HasCompleted => _operation.HasCompleted;
/// <inheritdoc />
public override Response GetRawResponse() => _operation.GetRawResponse();
/// <inheritdoc />
public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response> WaitForCompletionResponseAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response> WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(pollingInterval, cancellationToken);
}
}
| 41.925926 | 229 | 0.745583 |
[
"MIT"
] |
93mishra/azure-sdk-for-net
|
sdk/compute/Azure.ResourceManager.Compute/src/Generated/LongRunningOperation/CloudServiceRoleInstanceRestartOperation.cs
| 2,264 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Microsoft.Diagnostics.Runtime.Desktop
{
internal class PrimitiveType : BaseDesktopHeapType
{
public PrimitiveType(DesktopGCHeap heap, ClrElementType type)
: base(0, heap, heap.DesktopRuntime.ErrorModule, 0)
{
ElementType = type;
}
public override int BaseSize => DesktopInstanceField.GetSize(this, ElementType);
public override ClrType BaseType => DesktopHeap.ValueType;
public override int ElementSize => 0;
public override ClrHeap Heap => DesktopHeap;
public override IList<ClrInterface> Interfaces => new ClrInterface[0];
public override bool IsAbstract => false;
public override bool IsFinalizable => false;
public override bool IsInterface => false;
public override bool IsInternal => false;
public override bool IsPrivate => false;
public override bool IsProtected => false;
public override bool IsPublic => false;
public override bool IsSealed => false;
public override uint MetadataToken => 0;
public override ulong MethodTable => 0;
public override string Name => GetElementTypeName();
public override IEnumerable<ulong> EnumerateMethodTables()
{
return new ulong[0];
}
public override void EnumerateRefsOfObject(ulong objRef, Action<ulong, int> action)
{
}
public override void EnumerateRefsOfObjectCarefully(ulong objRef, Action<ulong, int> action)
{
}
public override ulong GetArrayElementAddress(ulong objRef, int index)
{
throw new InvalidOperationException();
}
public override object GetArrayElementValue(ulong objRef, int index)
{
throw new InvalidOperationException();
}
public override int GetArrayLength(ulong objRef)
{
throw new InvalidOperationException();
}
public override ClrInstanceField GetFieldByName(string name)
{
return null;
}
public override bool GetFieldForOffset(int fieldOffset, bool inner, out ClrInstanceField childField, out int childFieldOffset)
{
childField = null;
childFieldOffset = 0;
return false;
}
public override ulong GetSize(ulong objRef)
{
return 0;
}
public override ClrStaticField GetStaticFieldByName(string name)
{
return null;
}
internal override ulong GetModuleAddress(ClrAppDomain domain)
{
return 0;
}
public override IList<ClrInstanceField> Fields => new ClrInstanceField[0];
private string GetElementTypeName()
{
switch (ElementType)
{
case ClrElementType.Boolean:
return "System.Boolean";
case ClrElementType.Char:
return "System.Char";
case ClrElementType.Int8:
return "System.SByte";
case ClrElementType.UInt8:
return "System.Byte";
case ClrElementType.Int16:
return "System.Int16";
case ClrElementType.UInt16:
return "System.UInt16";
case ClrElementType.Int32:
return "System.Int32";
case ClrElementType.UInt32:
return "System.UInt32";
case ClrElementType.Int64:
return "System.Int64";
case ClrElementType.UInt64:
return "System.UInt64";
case ClrElementType.Float:
return "System.Single";
case ClrElementType.Double:
return "System.Double";
case ClrElementType.NativeInt:
return "System.IntPtr";
case ClrElementType.NativeUInt:
return "System.UIntPtr";
case ClrElementType.Struct:
return "Sytem.ValueType";
}
return ElementType.ToString();
}
}
}
| 31.082759 | 134 | 0.581762 |
[
"MIT"
] |
DamirAinullin/clrmd
|
src/Microsoft.Diagnostics.Runtime/src/Desktop/PrimitiveType.cs
| 4,509 |
C#
|
using System;
namespace R5T.T0036.X002
{
/// <summary>
/// <see cref="IMethodName"/> extensions for <see cref="Microsoft"/>-related method names.
/// </summary>
public class Documentation
{
}
}
| 17 | 94 | 0.61086 |
[
"MIT"
] |
SafetyCone/R5T.T0036
|
source/R5T.T0036.X002/Code/Documentation.cs
| 223 |
C#
|
using MonoGame.Extended.Entities;
namespace MonoGame.Extended.Gui.Tests.Implementation
{
[EntityComponent]
public class EntityComponentBasic
{
public int Number { get; set; }
}
}
| 20.4 | 52 | 0.70098 |
[
"MIT"
] |
damian-666/MonoGame.Extended
|
Source/Tests/MonoGame.Extended.Entities.Tests/Implementation/EntityComponentBasic.cs
| 206 |
C#
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.Translate.v3
{
/// <summary>The Translate Service.</summary>
public class TranslateService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v3";
/// <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 TranslateService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public TranslateService(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 => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "translate";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://translation.googleapis.com/";
#else
"https://translation.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://translation.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Cloud Translation API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Translate text from one language to another using Google Translate</summary>
public static string CloudTranslation = "https://www.googleapis.com/auth/cloud-translation";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Cloud Translation API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Translate text from one language to another using Google Translate</summary>
public const string CloudTranslation = "https://www.googleapis.com/auth/cloud-translation";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for Translate requests.</summary>
public abstract class TranslateBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new TranslateBaseServiceRequest instance.</summary>
protected TranslateBaseServiceRequest(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 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <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>
[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 = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <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>
[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 Translate 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;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Glossaries = new GlossariesResource(service);
Operations = new OperationsResource(service);
}
/// <summary>Gets the Glossaries resource.</summary>
public virtual GlossariesResource Glossaries { get; }
/// <summary>The "glossaries" collection of methods.</summary>
public class GlossariesResource
{
private const string Resource = "glossaries";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GlossariesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Creates a glossary and returns the long-running operation. Returns NOT_FOUND, if the project doesn't
/// exist.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">Required. The project name.</param>
public virtual CreateRequest Create(Google.Apis.Translate.v3.Data.Glossary body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>
/// Creates a glossary and returns the long-running operation. Returns NOT_FOUND, if the project doesn't
/// exist.
/// </summary>
public class CreateRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.Glossary body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>Required. The project name.</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.Translate.v3.Data.Glossary Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}/glossaries";
/// <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/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>
/// Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns
/// NOT_FOUND, if the glossary doesn't exist.
/// </summary>
/// <param name="name">Required. The name of the glossary to delete.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns
/// NOT_FOUND, if the glossary doesn't exist.
/// </summary>
public class DeleteRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Operation>
{
/// <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 glossary to delete.</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 => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+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/[^/]+/locations/[^/]+/glossaries/[^/]+$",
});
}
}
/// <summary>Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist.</summary>
/// <param name="name">Required. The name of the glossary to retrieve.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist.</summary>
public class GetRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Glossary>
{
/// <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 glossary to retrieve.</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";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+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/[^/]+/locations/[^/]+/glossaries/[^/]+$",
});
}
}
/// <summary>Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.</summary>
/// <param name="parent">
/// Required. The name of the project from which to list all of the glossaries.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.</summary>
public class ListRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.ListGlossariesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>Required. The name of the project from which to list all of the glossaries.</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Filter specifying constraints of a list operation. Specify the constraint by the
/// format of "key=value", where key must be "src" or "tgt", and the value must be a valid language
/// code. For multiple restrictions, concatenate them by "AND" (uppercase only), such as: "src=en-US
/// AND tgt=zh-CN". Notice that the exact match is used here, which means using 'en-US' and 'en' can
/// lead to different results, which depends on the language code you used when you create the
/// glossary. For the unidirectional glossaries, the "src" and "tgt" add restrictions on the source
/// and target language code separately. For the equivalent term set glossaries, the "src" and/or
/// "tgt" add restrictions on the term set. For example: "src=en-US AND tgt=zh-CN" will only pick
/// the unidirectional glossaries which exactly match the source language code as "en-US" and the
/// target language code "zh-CN", but all equivalent term set glossaries which contain "en-US" and
/// "zh-CN" in their language set will be picked. If missing, no filtering is performed.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Requested page size. The server may return fewer glossaries than requested. If
/// unspecified, the server picks an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. A token identifying a page of results the server should return. Typically, this is the
/// value of [ListGlossariesResponse.next_page_token] returned from the previous call to
/// `ListGlossaries` method. The first page is returned if `page_token`is empty or missing.
/// </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 => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}/glossaries";
/// <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/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
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("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
/// <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>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.Translate.v3.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
public class CancelRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.CancelOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</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.Translate.v3.Data.CancelOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+name}:cancel";
/// <summary>Initializes Cancel 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/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
public class DeleteRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Empty>
{
/// <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 operation resource to be deleted.</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 => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+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/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <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 : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Operation>
{
/// <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";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+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/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
public class ListRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list page token.</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 => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+name}/operations";
/// <summary>Initializes List 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/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
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("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Waits until the specified long-running operation is done or reaches at most a specified timeout,
/// returning the latest state. If the operation is already done, the latest state is immediately
/// returned. If the timeout specified is greater than the default HTTP/RPC timeout, the HTTP/RPC
/// timeout is used. If the server does not support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Note that this method is on a best-effort basis. It may return the
/// latest state before the specified timeout (including immediately), meaning even an immediate
/// response is no guarantee that the operation is done.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to wait on.</param>
public virtual WaitRequest Wait(Google.Apis.Translate.v3.Data.WaitOperationRequest body, string name)
{
return new WaitRequest(service, body, name);
}
/// <summary>
/// Waits until the specified long-running operation is done or reaches at most a specified timeout,
/// returning the latest state. If the operation is already done, the latest state is immediately
/// returned. If the timeout specified is greater than the default HTTP/RPC timeout, the HTTP/RPC
/// timeout is used. If the server does not support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Note that this method is on a best-effort basis. It may return the
/// latest state before the specified timeout (including immediately), meaning even an immediate
/// response is no guarantee that the operation is done.
/// </summary>
public class WaitRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Operation>
{
/// <summary>Constructs a new Wait request.</summary>
public WaitRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.WaitOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to wait on.</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.Translate.v3.Data.WaitOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "wait";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+name}:wait";
/// <summary>Initializes Wait 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/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
}
/// <summary>
/// Translates a large volume of document in asynchronous batch mode. This function provides real-time
/// output as the inputs are being processed. If caller cancels a request, the partial results (for an input
/// file, it's all or nothing) may still be available on the specified output location. This call returns
/// immediately and you can use google.longrunning.Operation.name to poll the status of the call.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Location to make a regional call. Format:
/// `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported for
/// batch translation. Only AutoML Translation models or glossaries within the same region (have the same
/// location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </param>
public virtual BatchTranslateDocumentRequest BatchTranslateDocument(Google.Apis.Translate.v3.Data.BatchTranslateDocumentRequest body, string parent)
{
return new BatchTranslateDocumentRequest(service, body, parent);
}
/// <summary>
/// Translates a large volume of document in asynchronous batch mode. This function provides real-time
/// output as the inputs are being processed. If caller cancels a request, the partial results (for an input
/// file, it's all or nothing) may still be available on the specified output location. This call returns
/// immediately and you can use google.longrunning.Operation.name to poll the status of the call.
/// </summary>
public class BatchTranslateDocumentRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Operation>
{
/// <summary>Constructs a new BatchTranslateDocument request.</summary>
public BatchTranslateDocumentRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.BatchTranslateDocumentRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Location to make a regional call. Format:
/// `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported
/// for batch translation. Only AutoML Translation models or glossaries within the same region (have the
/// same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </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.Translate.v3.Data.BatchTranslateDocumentRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "batchTranslateDocument";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:batchTranslateDocument";
/// <summary>Initializes BatchTranslateDocument 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/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>
/// Translates a large volume of text in asynchronous batch mode. This function provides real-time output as
/// the inputs are being processed. If caller cancels a request, the partial results (for an input file,
/// it's all or nothing) may still be available on the specified output location. This call returns
/// immediately and you can use google.longrunning.Operation.name to poll the status of the call.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported for
/// batch translation. Only AutoML Translation models or glossaries within the same region (have the same
/// location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </param>
public virtual BatchTranslateTextRequest BatchTranslateText(Google.Apis.Translate.v3.Data.BatchTranslateTextRequest body, string parent)
{
return new BatchTranslateTextRequest(service, body, parent);
}
/// <summary>
/// Translates a large volume of text in asynchronous batch mode. This function provides real-time output as
/// the inputs are being processed. If caller cancels a request, the partial results (for an input file,
/// it's all or nothing) may still be available on the specified output location. This call returns
/// immediately and you can use google.longrunning.Operation.name to poll the status of the call.
/// </summary>
public class BatchTranslateTextRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Operation>
{
/// <summary>Constructs a new BatchTranslateText request.</summary>
public BatchTranslateTextRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.BatchTranslateTextRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported
/// for batch translation. Only AutoML Translation models or glossaries within the same region (have the
/// same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </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.Translate.v3.Data.BatchTranslateTextRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "batchTranslateText";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:batchTranslateText";
/// <summary>Initializes BatchTranslateText 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/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Detects the language of text within a request.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be
/// used. Otherwise an INVALID_ARGUMENT (400) error is returned.
/// </param>
public virtual DetectLanguageRequest DetectLanguage(Google.Apis.Translate.v3.Data.DetectLanguageRequest body, string parent)
{
return new DetectLanguageRequest(service, body, parent);
}
/// <summary>Detects the language of text within a request.</summary>
public class DetectLanguageRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.DetectLanguageResponse>
{
/// <summary>Constructs a new DetectLanguage request.</summary>
public DetectLanguageRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.DetectLanguageRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be
/// used. Otherwise an INVALID_ARGUMENT (400) error is returned.
/// </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.Translate.v3.Data.DetectLanguageRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "detectLanguage";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:detectLanguage";
/// <summary>Initializes DetectLanguage 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/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Gets information about a location.</summary>
/// <param name="name">Resource name for the location.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a location.</summary>
public class GetRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.Location>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Resource name for the location.</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";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+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/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Returns a list of supported languages for translation.</summary>
/// <param name="parent">
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models within
/// the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is
/// returned.
/// </param>
public virtual GetSupportedLanguagesRequest GetSupportedLanguages(string parent)
{
return new GetSupportedLanguagesRequest(service, parent);
}
/// <summary>Returns a list of supported languages for translation.</summary>
public class GetSupportedLanguagesRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.SupportedLanguages>
{
/// <summary>Constructs a new GetSupportedLanguages request.</summary>
public GetSupportedLanguagesRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models
/// within the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400)
/// error is returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. The language to use to return localized, human readable names of supported languages. If
/// missing, then display names are not returned in a response.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("displayLanguageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DisplayLanguageCode { get; set; }
/// <summary>
/// Optional. Get supported languages of this model. The format depends on model type: - AutoML
/// Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` -
/// General (built-in) models:
/// `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, Returns languages
/// supported by the specified model. If missing, we get supported languages of Google general NMT
/// model.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("model", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Model { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getSupportedLanguages";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}/supportedLanguages";
/// <summary>Initializes GetSupportedLanguages 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/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("displayLanguageCode", new Google.Apis.Discovery.Parameter
{
Name = "displayLanguageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("model", new Google.Apis.Discovery.Parameter
{
Name = "model",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists information about the supported locations for this service.</summary>
/// <param name="name">The resource that owns the locations collection, if applicable.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists information about the supported locations for this service.</summary>
public class ListRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.ListLocationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource that owns the locations collection, if applicable.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// A filter to narrow down results to a preferred subset. The filtering language accepts strings like
/// "displayName=tokyo", and is documented in more detail in [AIP-160](https://google.aip.dev/160).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// The maximum number of results to return. If not set, the service selects a default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A page token received from the `next_page_token` field in the response. Send that page token to
/// receive the subsequent page.
/// </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 => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+name}/locations";
/// <summary>Initializes List 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/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
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("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Translates documents in synchronous mode.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Location to make a regional call. Format:
/// `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use
/// `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global
/// location is required for requests using AutoML models or custom glossaries. Models and glossaries must
/// be within the same region (have the same location-id), otherwise an INVALID_ARGUMENT (400) error is
/// returned.
/// </param>
public virtual TranslateDocumentRequest TranslateDocument(Google.Apis.Translate.v3.Data.TranslateDocumentRequest body, string parent)
{
return new TranslateDocumentRequest(service, body, parent);
}
/// <summary>Translates documents in synchronous mode.</summary>
public class TranslateDocumentRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.TranslateDocumentResponse>
{
/// <summary>Constructs a new TranslateDocument request.</summary>
public TranslateDocumentRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.TranslateDocumentRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Location to make a regional call. Format:
/// `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use
/// `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global
/// location is required for requests using AutoML models or custom glossaries. Models and glossaries
/// must be within the same region (have the same location-id), otherwise an INVALID_ARGUMENT (400)
/// error is returned.
/// </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.Translate.v3.Data.TranslateDocumentRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "translateDocument";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:translateDocument";
/// <summary>Initializes TranslateDocument 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/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Translates input text and returns translated text.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or
/// custom glossaries. Models and glossaries must be within the same region (have same location-id),
/// otherwise an INVALID_ARGUMENT (400) error is returned.
/// </param>
public virtual TranslateTextRequest TranslateText(Google.Apis.Translate.v3.Data.TranslateTextRequest body, string parent)
{
return new TranslateTextRequest(service, body, parent);
}
/// <summary>Translates input text and returns translated text.</summary>
public class TranslateTextRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.TranslateTextResponse>
{
/// <summary>Constructs a new TranslateText request.</summary>
public TranslateTextRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.TranslateTextRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models
/// or custom glossaries. Models and glossaries must be within the same region (have same location-id),
/// otherwise an INVALID_ARGUMENT (400) error is returned.
/// </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.Translate.v3.Data.TranslateTextRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "translateText";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:translateText";
/// <summary>Initializes TranslateText 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/[^/]+/locations/[^/]+$",
});
}
}
}
/// <summary>Detects the language of text within a request.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global
/// calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Only
/// models within the same region (has same location-id) can be used. Otherwise an INVALID_ARGUMENT (400) error
/// is returned.
/// </param>
public virtual DetectLanguageRequest DetectLanguage(Google.Apis.Translate.v3.Data.DetectLanguageRequest body, string parent)
{
return new DetectLanguageRequest(service, body, parent);
}
/// <summary>Detects the language of text within a request.</summary>
public class DetectLanguageRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.DetectLanguageResponse>
{
/// <summary>Constructs a new DetectLanguage request.</summary>
public DetectLanguageRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.DetectLanguageRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be
/// used. Otherwise an INVALID_ARGUMENT (400) error is returned.
/// </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.Translate.v3.Data.DetectLanguageRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "detectLanguage";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:detectLanguage";
/// <summary>Initializes DetectLanguage 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 a list of supported languages for translation.</summary>
/// <param name="parent">
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global
/// calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`.
/// Non-global location is required for AutoML models. Only models within the same region (have same
/// location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </param>
public virtual GetSupportedLanguagesRequest GetSupportedLanguages(string parent)
{
return new GetSupportedLanguagesRequest(service, parent);
}
/// <summary>Returns a list of supported languages for translation.</summary>
public class GetSupportedLanguagesRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.SupportedLanguages>
{
/// <summary>Constructs a new GetSupportedLanguages request.</summary>
public GetSupportedLanguagesRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models within
/// the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is
/// returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. The language to use to return localized, human readable names of supported languages. If
/// missing, then display names are not returned in a response.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("displayLanguageCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DisplayLanguageCode { get; set; }
/// <summary>
/// Optional. Get supported languages of this model. The format depends on model type: - AutoML Translation
/// models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in)
/// models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, Returns languages
/// supported by the specified model. If missing, we get supported languages of Google general NMT model.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("model", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Model { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getSupportedLanguages";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}/supportedLanguages";
/// <summary>Initializes GetSupportedLanguages 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("displayLanguageCode", new Google.Apis.Discovery.Parameter
{
Name = "displayLanguageCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("model", new Google.Apis.Discovery.Parameter
{
Name = "model",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Translates input text and returns translated text.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global
/// calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`.
/// Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries
/// must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error is
/// returned.
/// </param>
public virtual TranslateTextRequest TranslateText(Google.Apis.Translate.v3.Data.TranslateTextRequest body, string parent)
{
return new TranslateTextRequest(service, body, parent);
}
/// <summary>Translates input text and returns translated text.</summary>
public class TranslateTextRequest : TranslateBaseServiceRequest<Google.Apis.Translate.v3.Data.TranslateTextResponse>
{
/// <summary>Constructs a new TranslateText request.</summary>
public TranslateTextRequest(Google.Apis.Services.IClientService service, Google.Apis.Translate.v3.Data.TranslateTextRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Project or location to make a call. Must refer to a caller's project. Format:
/// `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For
/// global calls, use `projects/{project-number-or-id}/locations/global` or
/// `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or
/// custom glossaries. Models and glossaries must be within the same region (have same location-id),
/// otherwise an INVALID_ARGUMENT (400) error is returned.
/// </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.Translate.v3.Data.TranslateTextRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "translateText";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v3/{+parent}:translateText";
/// <summary>Initializes TranslateText 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.Translate.v3.Data
{
/// <summary>Input configuration for BatchTranslateDocument request.</summary>
public class BatchDocumentInputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Google Cloud Storage location for the source input. This can be a single file (for example,
/// `gs://translation-test/input.docx`) or a wildcard (for example, `gs://translation-test/*`). File mime type
/// is determined based on extension. Supported mime type includes: - `pdf`, application/pdf - `docx`,
/// application/vnd.openxmlformats-officedocument.wordprocessingml.document - `pptx`,
/// application/vnd.openxmlformats-officedocument.presentationml.presentation - `xlsx`,
/// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet The max file size to support for `.docx`,
/// `.pptx` and `.xlsx` is 100MB. The max file size to support for `.pdf` is 1GB and the max page limit is 1000
/// pages. The max file size to support for all input documents is 1GB.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsSource")]
public virtual GcsSource GcsSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Output configuration for BatchTranslateDocument request.</summary>
public class BatchDocumentOutputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Google Cloud Storage destination for output content. For every single input document (for example,
/// gs://a/b/c.[extension]), we generate at most 2 * n output files. (n is the # of target_language_codes in the
/// BatchTranslateDocumentRequest). While the input documents are being processed, we write/update an index file
/// `index.csv` under `gcs_destination.output_uri_prefix` (for example, gs://translation_output/index.csv) The
/// index file is generated/updated as new files are being translated. The format is:
/// input_document,target_language_code,translation_output,error_output,
/// glossary_translation_output,glossary_error_output `input_document` is one file we matched using
/// gcs_source.input_uri. `target_language_code` is provided in the request. `translation_output` contains the
/// translations. (details provided below) `error_output` contains the error message during processing of the
/// file. Both translations_file and errors_file could be empty strings if we have no content to output.
/// `glossary_translation_output` and `glossary_error_output` are the translated output/error when we apply
/// glossaries. They could also be empty if we have no content to output. Once a row is present in index.csv,
/// the input/output matching never changes. Callers should also expect all the content in input_file are
/// processed and ready to be consumed (that is, no partial output file is written). Since index.csv will be
/// keeping updated during the process, please make sure there is no custom retention policy applied on the
/// output bucket that may avoid file updating.
/// (https://cloud.google.com/storage/docs/bucket-lock?hl=en#retention-policy) The naming format of translation
/// output files follows (for target language code [trg]): `translation_output`:
/// gs://translation_output/a_b_c_[trg]_translation.[extension] `glossary_translation_output`:
/// gs://translation_test/a_b_c_[trg]_glossary_translation.[extension] The output document will maintain the
/// same file format as the input document. The naming format of error output files follows (for target language
/// code [trg]): `error_output`: gs://translation_test/a_b_c_[trg]_errors.txt `glossary_error_output`:
/// gs://translation_test/a_b_c_[trg]_glossary_translation.txt The error output is a txt file containing error
/// details.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsDestination")]
public virtual GcsDestination GcsDestination { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The BatchTranslateDocument request.</summary>
public class BatchTranslateDocumentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("formatConversions")]
public virtual System.Collections.Generic.IDictionary<string, string> FormatConversions { get; set; }
/// <summary>Optional. Glossaries to be applied. It's keyed by target language code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaries")]
public virtual System.Collections.Generic.IDictionary<string, TranslateTextGlossaryConfig> Glossaries { get; set; }
/// <summary>
/// Required. Input configurations. The total number of files matched should be &lt;= 100. The total content
/// size to translate should be &lt;= 100M Unicode codepoints. The files must use UTF-8 encoding.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputConfigs")]
public virtual System.Collections.Generic.IList<BatchDocumentInputConfig> InputConfigs { get; set; }
/// <summary>
/// Optional. The models to use for translation. Map's key is target language code. Map's value is the model
/// name. Value can be a built-in general model, or an AutoML Translation model. The value format depends on
/// model type: - AutoML Translation models:
/// `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models:
/// `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, If the map is empty or a
/// specific model is not requested for a language pair, then default google model (nmt) is used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("models")]
public virtual System.Collections.Generic.IDictionary<string, string> Models { get; set; }
/// <summary>
/// Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we
/// don't generate output for duplicate inputs.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputConfig")]
public virtual BatchDocumentOutputConfig OutputConfig { get; set; }
/// <summary>
/// Required. The BCP-47 language code of the input document if known, for example, "en-US" or "sr-Latn".
/// Supported language codes are listed in Language Support (https://cloud.google.com/translate/docs/languages).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceLanguageCode")]
public virtual string SourceLanguageCode { get; set; }
/// <summary>
/// Required. The BCP-47 language code to use for translation of the input document. Specify up to 10 language
/// codes here.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetLanguageCodes")]
public virtual System.Collections.Generic.IList<string> TargetLanguageCodes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The batch translation request.</summary>
public class BatchTranslateTextRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Glossaries to be applied for translation. It's keyed by target language code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaries")]
public virtual System.Collections.Generic.IDictionary<string, TranslateTextGlossaryConfig> Glossaries { get; set; }
/// <summary>
/// Required. Input configurations. The total number of files matched should be &lt;= 100. The total content
/// size should be &lt;= 100M Unicode codepoints. The files must use UTF-8 encoding.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputConfigs")]
public virtual System.Collections.Generic.IList<InputConfig> InputConfigs { get; set; }
/// <summary>
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than
/// 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and
/// dashes. International characters are allowed. Label values are optional. Label keys must start with a
/// letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Optional. The models to use for translation. Map's key is target language code. Map's value is model name.
/// Value can be a built-in general model, or an AutoML Translation model. The value format depends on model
/// type: - AutoML Translation models:
/// `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models:
/// `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, If the map is empty or a
/// specific model is not requested for a language pair, then default google model (nmt) is used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("models")]
public virtual System.Collections.Generic.IDictionary<string, string> Models { get; set; }
/// <summary>
/// Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we
/// don't generate output for duplicate inputs.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputConfig")]
public virtual OutputConfig OutputConfig { get; set; }
/// <summary>Required. Source language code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceLanguageCode")]
public virtual string SourceLanguageCode { get; set; }
/// <summary>Required. Specify up to 10 language codes here.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetLanguageCodes")]
public virtual System.Collections.Generic.IList<string> TargetLanguageCodes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for language detection.</summary>
public class DetectLanguageRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The content of the input stored as a string.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("content")]
public virtual string Content { get; set; }
/// <summary>
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than
/// 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and
/// dashes. International characters are allowed. Label values are optional. Label keys must start with a
/// letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME
/// type defaults to "text/html".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>
/// Optional. The language detection model to be used. Format:
/// `projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}` Only one
/// language detection model is currently supported:
/// `projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default`. If not
/// specified, the default model is used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for language detection.</summary>
public class DetectLanguageResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The most probable language detected by the Translation API. For each request, the Translation API will
/// always return only one result.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("languages")]
public virtual System.Collections.Generic.IList<DetectedLanguage> Languages { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for language detection.</summary>
public class DetectedLanguage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The confidence of the detection result for this language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("confidence")]
public virtual System.Nullable<float> Confidence { get; set; }
/// <summary>The BCP-47 language code of source content in the request, detected automatically.</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>A document translation request input config.</summary>
public class DocumentInputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Document's content represented as a stream of bytes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("content")]
public virtual string Content { get; set; }
/// <summary>
/// Google Cloud Storage location. This must be a single file. For example: gs://example_bucket/example_file.pdf
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsSource")]
public virtual GcsSource GcsSource { get; set; }
/// <summary>
/// Specifies the input document's mime_type. If not specified it will be determined using the file extension
/// for gcs_source provided files. For a file provided through bytes content the mime_type must be provided.
/// Currently supported mime types are: - application/pdf -
/// application/vnd.openxmlformats-officedocument.wordprocessingml.document -
/// application/vnd.openxmlformats-officedocument.presentationml.presentation -
/// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A document translation request output config.</summary>
public class DocumentOutputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Google Cloud Storage destination for the translation output, e.g., `gs://my_bucket/my_directory/`.
/// The destination directory provided does not have to be empty, but the bucket must exist. If a file with the
/// same name as the output file already exists in the destination an error will be returned. For a
/// DocumentInputConfig.contents provided document, the output file will have the name
/// "output_[trg]_translations.[ext]", where - [trg] corresponds to the translated file's language code, - [ext]
/// corresponds to the translated file's extension according to its mime type. For a DocumentInputConfig.gcs_uri
/// provided document, the output file will have a name according to its URI. For example: an input file with
/// URI: "gs://a/b/c.[extension]" stored in a gcs_destination bucket with name "my_bucket" will have an output
/// URI: "gs://my_bucket/a_b_c_[trg]_translations.[ext]", where - [trg] corresponds to the translated file's
/// language code, - [ext] corresponds to the translated file's extension according to its mime type. If the
/// document was directly provided through the request, then the output document will have the format:
/// "gs://my_bucket/translated_document_[trg]_translations.[ext], where - [trg] corresponds to the translated
/// file's language code, - [ext] corresponds to the translated file's extension according to its mime type. If
/// a glossary was provided, then the output URI for the glossary translation will be equal to the default
/// output URI but have `glossary_translations` instead of `translations`. For the previous example, its
/// glossary URI would be: "gs://my_bucket/a_b_c_[trg]_glossary_translations.[ext]". Thus the max number of
/// output files will be 2 (Translated document, Glossary translated document). Callers should expect no partial
/// outputs. If there is any error during document translation, no output will be stored in the Cloud Storage
/// bucket.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsDestination")]
public virtual GcsDestination GcsDestination { get; set; }
/// <summary>
/// Optional. Specifies the translated document's mime_type. If not specified, the translated file's mime type
/// will be the same as the input file's mime type. Currently only support the output mime type to be the same
/// as input mime type. - application/pdf -
/// application/vnd.openxmlformats-officedocument.wordprocessingml.document -
/// application/vnd.openxmlformats-officedocument.presentationml.presentation -
/// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A translated document message.</summary>
public class DocumentTranslation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The array of translated documents. It is expected to be size 1 for now. We may produce multiple translated
/// documents in the future for other type of file formats.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("byteStreamOutputs")]
public virtual System.Collections.Generic.IList<string> ByteStreamOutputs { get; set; }
/// <summary>
/// The detected language for the input document. If the user did not provide the source language for the input
/// document, this field will have the language code automatically detected. If the source language was passed,
/// auto-detection of the language does not occur and this field is empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("detectedLanguageCode")]
public virtual string DetectedLanguageCode { get; set; }
/// <summary>The translated document's mime type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { 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 Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The Google Cloud Storage location for the output content.</summary>
public class GcsDestination : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The bucket used in 'output_uri_prefix' must exist and there must be no files under
/// 'output_uri_prefix'. 'output_uri_prefix' must end with "/" and start with "gs://". One 'output_uri_prefix'
/// can only be used by one batch translation job at a time. Otherwise an INVALID_ARGUMENT (400) error is
/// returned.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("outputUriPrefix")]
public virtual string OutputUriPrefix { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The Google Cloud Storage location for the input content.</summary>
public class GcsSource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Source data URI. For example, `gs://my_bucket/my_object`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputUri")]
public virtual string InputUri { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a glossary built from user provided data.</summary>
public class Glossary : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. When the glossary creation was finished.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>Output only. The number of entries defined in the glossary.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entryCount")]
public virtual System.Nullable<int> EntryCount { get; set; }
/// <summary>
/// Required. Provides examples to build the glossary from. Total glossary must not exceed 10M Unicode
/// codepoints.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("inputConfig")]
public virtual GlossaryInputConfig InputConfig { get; set; }
/// <summary>Used with equivalent term set glossaries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCodesSet")]
public virtual LanguageCodesSet LanguageCodesSet { get; set; }
/// <summary>Used with unidirectional glossaries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("languagePair")]
public virtual LanguageCodePair LanguagePair { get; set; }
/// <summary>
/// Required. The resource name of the glossary. Glossary names have the form
/// `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. When CreateGlossary was called.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("submitTime")]
public virtual object SubmitTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Input configuration for glossaries.</summary>
public class GlossaryInputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. Google Cloud Storage location of glossary data. File format is determined based on the filename
/// extension. API returns [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file formats. Wildcards
/// are not allowed. This must be a single file in one of the following formats: For unidirectional glossaries:
/// - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated. The first column is source text. The
/// second column is target text. The file must not contain headers. That is, the first row is data, not column
/// names. - TMX (`.tmx`): TMX file with parallel data defining source/target term pairs. For equivalent term
/// sets glossaries: - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms in multiple
/// languages. See documentation for more information -
/// [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsSource")]
public virtual GcsSource GcsSource { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Input configuration for BatchTranslateText request.</summary>
public class InputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. Google Cloud Storage location for the source input. This can be a single file (for example,
/// `gs://translation-test/input.tsv`) or a wildcard (for example, `gs://translation-test/*`). If a file
/// extension is `.tsv`, it can contain either one or two columns. The first column (optional) is the id of the
/// text request. If the first column is missing, we use the row number (0-based) from the input file as the ID
/// in the output file. The second column is the actual text to be translated. We recommend each row be
/// &lt;= 10K Unicode codepoints, otherwise an error might be returned. Note that the input tsv must be RFC
/// 4180 compliant. You could use https://github.com/Clever/csvlint to check potential formatting errors in your
/// tsv file. csvlint --delimiter='\t' your_input_file.tsv The other supported file extensions are `.txt` or
/// `.html`, which is treated as a single large chunk of text.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsSource")]
public virtual GcsSource GcsSource { get; set; }
/// <summary>
/// Optional. Can be "text/plain" or "text/html". For `.tsv`, "text/html" is used if mime_type is missing. For
/// `.html`, this field must be "text/html" or empty. For `.txt`, this field must be "text/plain" or empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Used with unidirectional glossaries.</summary>
public class LanguageCodePair : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The BCP-47 language code of the input text, for example, "en-US". Expected to be an exact match
/// for GlossaryTerm.language_code.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceLanguageCode")]
public virtual string SourceLanguageCode { get; set; }
/// <summary>
/// Required. The BCP-47 language code for translation output, for example, "zh-CN". Expected to be an exact
/// match for GlossaryTerm.language_code.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetLanguageCode")]
public virtual string TargetLanguageCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Used with equivalent term set glossaries.</summary>
public class LanguageCodesSet : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The BCP-47 language code(s) for terms defined in the glossary. All entries are unique. The list contains at
/// least two entries. Expected to be an exact match for GlossaryTerm.language_code.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCodes")]
public virtual System.Collections.Generic.IList<string> LanguageCodes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for ListGlossaries.</summary>
public class ListGlossariesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of glossaries for a project.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaries")]
public virtual System.Collections.Generic.IList<Glossary> Glossaries { get; set; }
/// <summary>
/// A token to retrieve a page of results. Pass this value in the [ListGlossariesRequest.page_token] field in
/// the subsequent call to `ListGlossaries` method to retrieve the next page of results.
/// </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 Locations.ListLocations.</summary>
public class ListLocationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of locations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locations")]
public virtual System.Collections.Generic.IList<Location> Locations { get; set; }
/// <summary>The standard List next-page token.</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 Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A resource that represents Google Cloud Platform location.</summary>
public class Location : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The friendly name for this location, typically a nearby city name. For example, "Tokyo".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>The canonical id for this location. For example: `"us-east1"`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locationId")]
public virtual string LocationId { get; set; }
/// <summary>Service-specific metadata. For example the available capacity at the given location.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// Resource name for the location, which may vary between implementations. For example:
/// `"projects/example-project/locations/us-east1"`
/// </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 resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : 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 Status 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 be a resource name ending with `operations/{unique_id}`.
/// </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>Output configuration for BatchTranslateText request.</summary>
public class OutputConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Google Cloud Storage destination for output content. For every single input file (for example,
/// gs://a/b/c.[extension]), we generate at most 2 * n output files. (n is the # of target_language_codes in the
/// BatchTranslateTextRequest). Output files (tsv) generated are compliant with RFC 4180 except that record
/// delimiters are '\n' instead of '\r\n'. We don't provide any way to change record delimiters. While the input
/// files are being processed, we write/update an index file 'index.csv' under 'output_uri_prefix' (for example,
/// gs://translation-test/index.csv) The index file is generated/updated as new files are being translated. The
/// format is: input_file,target_language_code,translations_file,errors_file,
/// glossary_translations_file,glossary_errors_file input_file is one file we matched using
/// gcs_source.input_uri. target_language_code is provided in the request. translations_file contains the
/// translations. (details provided below) errors_file contains the errors during processing of the file.
/// (details below). Both translations_file and errors_file could be empty strings if we have no content to
/// output. glossary_translations_file and glossary_errors_file are always empty strings if the input_file is
/// tsv. They could also be empty if we have no content to output. Once a row is present in index.csv, the
/// input/output matching never changes. Callers should also expect all the content in input_file are processed
/// and ready to be consumed (that is, no partial output file is written). Since index.csv will be keeping
/// updated during the process, please make sure there is no custom retention policy applied on the output
/// bucket that may avoid file updating.
/// (https://cloud.google.com/storage/docs/bucket-lock?hl=en#retention-policy) The format of translations_file
/// (for target language code 'trg') is: gs://translation_test/a_b_c_'trg'_translations.[extension] If the input
/// file extension is tsv, the output has the following columns: Column 1: ID of the request provided in the
/// input, if it's not provided in the input, then the input row number is used (0-based). Column 2: source
/// sentence. Column 3: translation without applying a glossary. Empty string if there is an error. Column 4
/// (only present if a glossary is provided in the request): translation after applying the glossary. Empty
/// string if there is an error applying the glossary. Could be same string as column 3 if there is no glossary
/// applied. If input file extension is a txt or html, the translation is directly written to the output file.
/// If glossary is requested, a separate glossary_translations_file has format of
/// gs://translation_test/a_b_c_'trg'_glossary_translations.[extension] The format of errors file (for target
/// language code 'trg') is: gs://translation_test/a_b_c_'trg'_errors.[extension] If the input file extension is
/// tsv, errors_file contains the following: Column 1: ID of the request provided in the input, if it's not
/// provided in the input, then the input row number is used (0-based). Column 2: source sentence. Column 3:
/// Error detail for the translation. Could be empty. Column 4 (only present if a glossary is provided in the
/// request): Error when applying the glossary. If the input file extension is txt or html, glossary_error_file
/// will be generated that contains error details. glossary_error_file has format of
/// gs://translation_test/a_b_c_'trg'_glossary_errors.[extension]
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsDestination")]
public virtual GcsDestination GcsDestination { get; set; }
/// <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). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : 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>
/// A single supported language response corresponds to information related to one supported language.
/// </summary>
public class SupportedLanguage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Human readable name of the language localized in the display language specified in the request.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Supported language code, generally consisting of its ISO 639-1 identifier, for example, 'en', 'ja'. In
/// certain cases, BCP-47 codes including language and region identifiers are returned (for example, 'zh-TW' and
/// 'zh-CN')
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("languageCode")]
public virtual string LanguageCode { get; set; }
/// <summary>Can be used as source language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("supportSource")]
public virtual System.Nullable<bool> SupportSource { get; set; }
/// <summary>Can be used as target language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("supportTarget")]
public virtual System.Nullable<bool> SupportTarget { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for discovering supported languages.</summary>
public class SupportedLanguages : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// A list of supported language responses. This list contains an entry for each language the Translation API
/// supports.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("languages")]
public virtual System.Collections.Generic.IList<SupportedLanguage> Languages { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A document translation request.</summary>
public class TranslateDocumentRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Input configurations.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("documentInputConfig")]
public virtual DocumentInputConfig DocumentInputConfig { get; set; }
/// <summary>
/// Optional. Output configurations. Defines if the output file should be stored within Cloud Storage as well as
/// the desired output format. If not provided the translated file will only be returned through a byte-stream
/// and its output mime type will be the same as the input file's mime type.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("documentOutputConfig")]
public virtual DocumentOutputConfig DocumentOutputConfig { get; set; }
/// <summary>
/// Optional. Glossary to be applied. The glossary must be within the same region (have the same location-id) as
/// the model, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaryConfig")]
public virtual TranslateTextGlossaryConfig GlossaryConfig { get; set; }
/// <summary>
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than
/// 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and
/// dashes. International characters are allowed. Label values are optional. Label keys must start with a
/// letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Optional. The `model` type requested for this translation. The format depends on model type: - AutoML
/// Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General
/// (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, If not
/// provided, the default Google model (NMT) will be used for translation.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>
/// Optional. The BCP-47 language code of the input document if known, for example, "en-US" or "sr-Latn".
/// Supported language codes are listed in Language Support. If the source language isn't specified, the API
/// attempts to identify the source language automatically and returns the source language within the response.
/// Source language must be specified if the request contains a glossary or a custom model.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceLanguageCode")]
public virtual string SourceLanguageCode { get; set; }
/// <summary>
/// Required. The BCP-47 language code to use for translation of the input document, set to one of the language
/// codes listed in Language Support.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetLanguageCode")]
public virtual string TargetLanguageCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A translated document response message.</summary>
public class TranslateDocumentResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Translated document.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("documentTranslation")]
public virtual DocumentTranslation DocumentTranslation { get; set; }
/// <summary>The `glossary_config` used for this translation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaryConfig")]
public virtual TranslateTextGlossaryConfig GlossaryConfig { get; set; }
/// <summary>
/// The document's translation output if a glossary is provided in the request. This can be the same as
/// [TranslateDocumentResponse.document_translation] if no glossary terms apply.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaryDocumentTranslation")]
public virtual DocumentTranslation GlossaryDocumentTranslation { get; set; }
/// <summary>
/// Only present when 'model' is present in the request. 'model' is normalized to have a project number. For
/// example: If the 'model' field in TranslateDocumentRequest is:
/// `projects/{project-id}/locations/{location-id}/models/general/nmt` then `model` here would be normalized to
/// `projects/{project-number}/locations/{location-id}/models/general/nmt`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Configures which glossary should be used for a specific target language, and defines options for applying that
/// glossary.
/// </summary>
public class TranslateTextGlossaryConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The `glossary` to be applied for this translation. The format depends on glossary: - User provided
/// custom glossary: `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossary")]
public virtual string Glossary { get; set; }
/// <summary>Optional. Indicates match is case-insensitive. Default value is false if missing.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ignoreCase")]
public virtual System.Nullable<bool> IgnoreCase { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for synchronous translation.</summary>
public class TranslateTextRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The content of the input in string format. We recommend the total content be less than 30k
/// codepoints. The max length of this field is 1024. Use BatchTranslateText for larger text.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("contents")]
public virtual System.Collections.Generic.IList<string> Contents { get; set; }
/// <summary>
/// Optional. Glossary to be applied. The glossary must be within the same region (have the same location-id) as
/// the model, otherwise an INVALID_ARGUMENT (400) error is returned.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaryConfig")]
public virtual TranslateTextGlossaryConfig GlossaryConfig { get; set; }
/// <summary>
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than
/// 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and
/// dashes. International characters are allowed. Label values are optional. Label keys must start with a
/// letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME
/// type defaults to "text/html".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>
/// Optional. The `model` type requested for this translation. The format depends on model type: - AutoML
/// Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General
/// (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, For global
/// (non-regionalized) requests, use `location-id` `global`. For example,
/// `projects/{project-number-or-id}/locations/global/models/general/nmt`. If not provided, the default Google
/// model (NMT) will be used
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>
/// Optional. The BCP-47 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported
/// language codes are listed in Language Support. If the source language isn't specified, the API attempts to
/// identify the source language automatically and returns the source language within the response.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceLanguageCode")]
public virtual string SourceLanguageCode { get; set; }
/// <summary>
/// Required. The BCP-47 language code to use for translation of the input text, set to one of the language
/// codes listed in Language Support.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetLanguageCode")]
public virtual string TargetLanguageCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class TranslateTextResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Text translation responses if a glossary is provided in the request. This can be the same as `translations`
/// if no terms apply. This field has the same length as `contents`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaryTranslations")]
public virtual System.Collections.Generic.IList<Translation> GlossaryTranslations { get; set; }
/// <summary>
/// Text translation responses with no glossary applied. This field has the same length as `contents`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("translations")]
public virtual System.Collections.Generic.IList<Translation> Translations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A single translation response.</summary>
public class Translation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The BCP-47 language code of source text in the initial request, detected automatically, if no source
/// language was passed within the initial request. If the source language was passed, auto-detection of the
/// language does not occur and this field is empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("detectedLanguageCode")]
public virtual string DetectedLanguageCode { get; set; }
/// <summary>The `glossary_config` used for this translation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("glossaryConfig")]
public virtual TranslateTextGlossaryConfig GlossaryConfig { get; set; }
/// <summary>
/// Only present when `model` is present in the request. `model` here is normalized to have project number. For
/// example: If the `model` requested in TranslationTextRequest is
/// `projects/{project-id}/locations/{location-id}/models/general/nmt` then `model` here would be normalized to
/// `projects/{project-number}/locations/{location-id}/models/general/nmt`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("model")]
public virtual string Model { get; set; }
/// <summary>
/// Text translated into the target language. If an error occurs during translation, this field might be
/// excluded from the response.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("translatedText")]
public virtual string TranslatedText { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.WaitOperation.</summary>
public class WaitOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The maximum duration to wait before timing out. If left blank, the wait will be at most the time permitted
/// by the underlying HTTP/RPC protocol. If RPC context deadline is also specified, the shorter one will be
/// used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeout")]
public virtual object Timeout { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 54.606027 | 194 | 0.599712 |
[
"Apache-2.0"
] |
amanda-tarafa/google-api-dotnet-client
|
Src/Generated/Google.Apis.Translate.v3/Google.Apis.Translate.v3.cs
| 148,583 |
C#
|
using Lazurite.Security.Permissions;
using LazuriteUI.Windows.Controls;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace LazuriteUI.Windows.Main.Security.PermissionsViews
{
/// <summary>
/// Логика взаимодействия для SelectPermissionView.xaml
/// </summary>
public partial class SelectPermissionView : UserControl
{
public SelectPermissionView()
{
InitializeComponent();
foreach (var permissionType in Lazurite.Security.Utils.GetPermissionTypes().OrderBy(x=> Lazurite.ActionsDomain.Utils.ExtractHumanFriendlyName(x)))
{
var itemView = new ItemView();
itemView.Margin = new Thickness(0, 1, 0, 0);
itemView.Tag = permissionType;
itemView.Icon = Icons.Icon.ChevronRight;
itemView.Content = Lazurite.ActionsDomain.Utils.ExtractHumanFriendlyName(permissionType);
itemView.Click += (o, e) => {
var permission = (IPermission)Activator.CreateInstance(permissionType);
PermissionCreated?.Invoke(permission);
};
itemsView.Children.Add(itemView);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public event Action<IPermission> PermissionCreated;
public static void Show(Action<IPermission> callback)
{
var control = new SelectPermissionView();
var dialog = new DialogView(control);
control.PermissionCreated += (permission) => {
callback?.Invoke(permission);
dialog.Close();
};
dialog.Show();
}
}
}
| 37.541667 | 158 | 0.619312 |
[
"Apache-2.0"
] |
noant/Lazurite
|
Lazurite/LazuriteUI.Windows.Main/Security/PermissionsViews/SelectPermissionView.xaml.cs
| 1,827 |
C#
|
namespace Eventus.Storage
{
using Configuration;
using System;
using System.Linq;
using System.Threading.Tasks;
using Domain;
using EventBus;
using Exceptions;
using Microsoft.Extensions.Logging;
/// <summary>
/// The default Eventus Aggregate repository
/// </summary>
public class Repository : IRepository
{
private readonly IEventStorageProvider _eventStorageProvider;
private readonly ISnapshotStorageProvider _snapshotStorageProvider;
private readonly ISnapshotCalculator _snapshotCalculator;
private readonly EventusOptions _options;
private readonly IEventPublisher? _eventPublisher;
private readonly ILogger<Repository> _logger;
public Repository(IEventStorageProvider eventStorageProvider,
ISnapshotStorageProvider snapshotStorageProvider,
ISnapshotCalculator snapshotCalculator,
EventusOptions options,
ILogger<Repository> logger,
IEventPublisher? eventPublisher = null)
{
_eventStorageProvider = eventStorageProvider;
_snapshotStorageProvider = snapshotStorageProvider;
_snapshotCalculator = snapshotCalculator;
_options = options;
_eventPublisher = eventPublisher;
_logger = logger;
}
public async Task<TAggregate?> GetByIdAsync<TAggregate>(Guid id) where TAggregate : Aggregate
{
var snapshot = await GetPossibleSnapshot<TAggregate>(id);
if (snapshot != null)
{
return await LoadFromSnapshot<TAggregate>(id, snapshot);
}
return await LoadFromEvents<TAggregate>(id);
}
private async Task<Snapshot?> GetPossibleSnapshot<TAggregate>(Guid id) where TAggregate : Aggregate
{
var isSnapshottable = typeof(ISnapshottable).IsAssignableFrom(typeof(TAggregate));
Snapshot? snapshot = null;
if (_options.SnapshottingEnabled && isSnapshottable)
{
_logger.LogDebug(
"Aggregate: '{Aggregate}' is marked as snapshottable and Snapshotting is enabled so trying to find the most recent snapshot for aggregate",
id);
snapshot = await _snapshotStorageProvider.GetSnapshotAsync(typeof(TAggregate), id);
}
return snapshot;
}
private async Task<TAggregate?> LoadFromSnapshot<TAggregate>(Guid id, Snapshot snapshot)
where TAggregate : Aggregate
{
_logger.LogDebug("Building aggregate: '{Aggregate}' from snapshot", id);
var item = ConstructAggregate<TAggregate>();
if (item == null)
{
return null;
}
(item as ISnapshottable)?.ApplySnapshot(snapshot);
_logger.LogDebug(
"Loading events for aggregate: '{Aggregate}' since last snapshot at version: {SnapshotVersion}", id,
snapshot.Version);
var events = await _eventStorageProvider.GetEventsAsync(typeof(TAggregate), id, snapshot.Version + 1);
var eventList = events.ToList();
if (eventList.Any())
{
item.LoadFromHistory(eventList);
}
return item;
}
private async Task<TAggregate?> LoadFromEvents<TAggregate>(Guid id) where TAggregate : Aggregate
{
_logger.LogDebug("Building aggregate: '{Aggregate}' from events stream", id);
var events = (await _eventStorageProvider.GetEventsAsync(typeof(TAggregate), id)).ToList();
if (events.Any())
{
var item = ConstructAggregate<TAggregate>();
if (item == null)
{
return null;
}
item.LoadFromHistory(events);
return item;
}
return null;
}
public Task SaveAsync<TAggregate>(TAggregate aggregate) where TAggregate : Aggregate
{
_logger.LogDebug("Saving aggregate: '{Aggregate}'", aggregate.Id);
if (!aggregate.HasUncommittedChanges())
return Task.CompletedTask;
_logger.LogDebug("Aggregate: '{Aggregate}' has '{ChangesToCommit}' uncommitted changes", aggregate.Id, aggregate.GetUncommittedChanges().Count);
return CommitChangesAsync(aggregate);
}
private async Task CommitChangesAsync(Aggregate aggregate)
{
await ValidateCanCommitChanges(aggregate);
var changesToCommit = aggregate.GetUncommittedChanges();
_logger.LogDebug("Committing changes for aggregate: '{Aggregate}'", aggregate.Id);
await _eventStorageProvider.CommitChangesAsync(aggregate);
if (_eventPublisher != null)
{
_logger.LogDebug("Publishing aggregate: '{Aggregate}' events", aggregate.Id);
foreach (var e in changesToCommit)
{
await _eventPublisher.PublishAsync(e);
}
}
if (_options.GetSnapshotEnabled(aggregate.GetType()) && aggregate is ISnapshottable snapshottable &&
_snapshotCalculator.ShouldCreateSnapShot(aggregate))
{
_logger.LogDebug(
"Taking a snapshot for aggregate: '{Aggregate}' current version: '{CurrentVersion}' changes to commit: {ChangesToCommit}",
aggregate.Id, aggregate.CurrentVersion, changesToCommit.Count);
await _snapshotStorageProvider.SaveSnapshotAsync(aggregate.GetType(), snapshottable.TakeSnapshot());
}
_logger.LogDebug("Marking all aggregate: '{Aggregate}' changes as committed", aggregate.Id);
aggregate.MarkChangesAsCommitted();
}
private async Task ValidateCanCommitChanges(Aggregate aggregate)
{
var expectedVersion = aggregate.LastCommittedVersion;
_logger.LogDebug(
"Getting latest event for aggregate: '{Aggregate}' to validate that aggregate is in a state to be saved",
aggregate.Id);
var item = await _eventStorageProvider.GetLastEventAsync(aggregate.GetType(), aggregate.Id);
if (item != null && expectedVersion == Aggregate.NoEventsStoredYet)
{
throw new AggregateCreationException(aggregate.Id, item.TargetVersion + 1);
}
if (item != null && item.TargetVersion + 1 != expectedVersion)
{
throw new ConcurrencyException(aggregate.Id);
}
}
private static TAggregate? ConstructAggregate<TAggregate>() where TAggregate : Aggregate
{
var instance = Activator.CreateInstance(typeof(TAggregate), true);
if (instance == null)
{
return null;
}
var aggregate = (TAggregate)instance;
return aggregate;
}
}
}
| 35.691542 | 159 | 0.601756 |
[
"MIT"
] |
ForrestTech/Eventus
|
src/Eventus/Storage/Repository.cs
| 7,176 |
C#
|
using HotChocolate.ApolloFederation;
namespace Inventory;
[ExtendServiceType]
public class Product
{
public Product(string upc)
{
Upc = upc;
}
[Key]
[External]
public string Upc { get; }
[External]
public int Weight { get; private set; }
[External]
public int Price { get; private set; }
public bool InStock { get; } = true;
// free for expensive items, else the estimate is based on weight
[Requires("price weight")]
public int GetShippingEstimate()
=> Price > 1000 ? 0 : (int)(Weight * 0.5);
[ReferenceResolver]
public static Product GetProduct(string upc)
=> new Product(upc);
}
| 19.941176 | 69 | 0.626844 |
[
"MIT"
] |
ChilliCream/prometheus
|
src/HotChocolate/ApolloFederation/examples/AnnotationBased/Inventory/Product.cs
| 678 |
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 iam-2010-05-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// Container for the parameters to the ChangePassword operation.
/// Changes the password of the IAM user who is calling this operation. This operation
/// can be performed using the AWS CLI, the AWS API, or the <b>My Security Credentials</b>
/// page in the AWS Management Console. The AWS account root user password is not affected
/// by this operation.
///
///
/// <para>
/// Use <a>UpdateLoginProfile</a> to use the AWS CLI, the AWS API, or the <b>Users</b>
/// page in the IAM console to change the password for any IAM user. For more information
/// about modifying passwords, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html">Managing
/// passwords</a> in the <i>IAM User Guide</i>.
/// </para>
/// </summary>
public partial class ChangePasswordRequest : AmazonIdentityManagementServiceRequest
{
private string _newPassword;
private string _oldPassword;
/// <summary>
/// Gets and sets the property NewPassword.
/// <para>
/// The new password. The new password must conform to the AWS account's password policy,
/// if one exists.
/// </para>
///
/// <para>
/// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> that is used to validate
/// this parameter is a string of characters. That string can include almost any printable
/// ASCII character from the space (<code>\u0020</code>) through the end of the ASCII
/// character range (<code>\u00FF</code>). You can also include the tab (<code>\u0009</code>),
/// line feed (<code>\u000A</code>), and carriage return (<code>\u000D</code>) characters.
/// Any of these characters are valid in a password. However, many tools, such as the
/// AWS Management Console, might restrict the ability to type certain characters because
/// they have special meaning within that tool.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
public string NewPassword
{
get { return this._newPassword; }
set { this._newPassword = value; }
}
// Check to see if NewPassword property is set
internal bool IsSetNewPassword()
{
return this._newPassword != null;
}
/// <summary>
/// Gets and sets the property OldPassword.
/// <para>
/// The IAM user's current password.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
public string OldPassword
{
get { return this._oldPassword; }
set { this._oldPassword = value; }
}
// Check to see if OldPassword property is set
internal bool IsSetOldPassword()
{
return this._oldPassword != null;
}
}
}
| 38.245098 | 132 | 0.635734 |
[
"Apache-2.0"
] |
KenHundley/aws-sdk-net
|
sdk/src/Services/IdentityManagement/Generated/Model/ChangePasswordRequest.cs
| 3,901 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Tor.Controller;
using System.Net;
using Tor.Helpers;
using System.ComponentModel;
namespace Tor
{
/// <summary>
/// A class containing information regarding a circuit within the tor service.
/// </summary>
public sealed class Circuit : MarshalByRefObject
{
private readonly Client client;
private readonly int id;
private readonly object synchronize;
private CircuitBuildFlags buildFlags;
private CircuitHSState hsState;
private List<string> paths;
private CircuitPurpose purpose;
private CircuitReason reason;
private RouterCollection routers;
private CircuitStatus status;
private DateTime timeCreated;
/// <summary>
/// Initializes a new instance of the <see cref="Circuit"/> class.
/// </summary>
/// <param name="client">The client for which the circuit belongs.</param>
/// <param name="id">The unique identifier of the circuit within the tor session.</param>
internal Circuit(Client client, int id)
{
this.buildFlags = CircuitBuildFlags.None;
this.client = client;
this.hsState = CircuitHSState.None;
this.id = id;
this.paths = new List<string>();
this.purpose = CircuitPurpose.None;
this.reason = CircuitReason.None;
this.synchronize = new object();
this.timeCreated = DateTime.MinValue;
}
#region Properties
/// <summary>
/// Gets the build flags associated with the circuit.
/// </summary>
public CircuitBuildFlags BuildFlags
{
get { return buildFlags; }
internal set { buildFlags = value; }
}
/// <summary>
/// Gets the hidden-service state of the circuit.
/// </summary>
public CircuitHSState HSState
{
get { return hsState; }
internal set { hsState = value; }
}
/// <summary>
/// Gets the unique identifier of the circuit in the tor session.
/// </summary>
public int ID
{
get { return id; }
}
/// <summary>
/// Gets the purpose of the circuit.
/// </summary>
public CircuitPurpose Purpose
{
get { return purpose; }
internal set { purpose = value; }
}
/// <summary>
/// Gets the reason associated with the circuit, usually assigned upon closed or failed events.
/// </summary>
public CircuitReason Reason
{
get { return reason; }
internal set { reason = value; }
}
/// <summary>
/// Gets the routers associated with the circuit.
/// </summary>
public RouterCollection Routers
{
get { return routers; }
}
/// <summary>
/// Gets the status of the circuit.
/// </summary>
public CircuitStatus Status
{
get { return status; }
internal set { status = value; }
}
/// <summary>
/// Gets the date and time the circuit was created.
/// </summary>
public DateTime TimeCreated
{
get { return timeCreated; }
internal set { timeCreated = value; }
}
/// <summary>
/// Gets or sets the collection containing the paths associated with the circuit.
/// </summary>
internal List<string> Paths
{
get { lock (synchronize) return paths; }
set { lock (synchronize) paths = value; }
}
#endregion
/// <summary>
/// Sends a request to the associated tor client to close the circuit.
/// </summary>
/// <returns><c>true</c> if the circuit is closed successfully; otherwise, <c>false</c>.</returns>
public bool Close()
{
return client.Controller.CloseCircuit(this);
}
/// <summary>
/// Sends a request to the associated tor client to extend the circuit.
/// </summary>
/// <param name="routers">The list of identities or nicknames to extend onto this circuit.</param>
/// <returns><c>true</c> if the circuit is extended successfully; otherwise, <c>false</c>.</returns>
public bool Extend(params string[] routers)
{
return client.Controller.ExtendCircuit(this, routers);
}
/// <summary>
/// Sends a request to the associated tor client to extend the circuit.
/// </summary>
/// <param name="routers">The list of routers to extend onto this circuit.</param>
/// <returns><c>true</c> if the circuit is extended successfully; otherwise, <c>false</c>.</returns>
public bool Extend(params Router[] routers)
{
string[] nicknames = new string[routers.Length];
for (int i = 0, length = routers.Length; i < length; i++)
nicknames[i] = routers[i].Nickname;
return client.Controller.ExtendCircuit(this, nicknames);
}
/// <summary>
/// Gets the routers associated with the circuit.
/// </summary>
/// <returns>A <see cref="RouterCollection"/> object instance.</returns>
internal RouterCollection GetRouters()
{
lock (synchronize)
{
List<Router> routers = new List<Router>();
if (paths == null || paths.Count == 0)
{
this.routers = new RouterCollection(routers);
return this.routers;
}
foreach (string path in paths)
{
string trimmed = path;
if (trimmed == null)
continue;
if (trimmed.StartsWith("$"))
trimmed = trimmed.Substring(1);
if (trimmed.Contains("~"))
trimmed = trimmed.Substring(0, trimmed.IndexOf("~"));
if (string.IsNullOrWhiteSpace(trimmed))
continue;
GetRouterStatusCommand command = new GetRouterStatusCommand(trimmed);
GetRouterStatusResponse response = command.Dispatch(client);
if (response.Success && response.Router != null)
routers.Add(response.Router);
}
this.routers = new RouterCollection(routers);
return this.routers;
}
}
}
/// <summary>
/// A class containing a read-only collection of <see cref="Circuit"/> objects.
/// </summary>
public sealed class CircuitCollection : ReadOnlyCollection<Circuit>
{
/// <summary>
/// Initializes a new instance of the <see cref="CircuitCollection"/> class.
/// </summary>
/// <param name="list">The list of circuits.</param>
internal CircuitCollection(IList<Circuit> list) : base(list)
{
}
}
}
| 32.665179 | 108 | 0.543119 |
[
"MIT"
] |
Zaczero/Tor4NET
|
Tor4NET/Tor/Circuits/Circuit.cs
| 7,319 |
C#
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from shared/tcpmib.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='MIB_TCPTABLE2.xml' path='doc/member[@name="MIB_TCPTABLE2"]/*' />
public partial struct MIB_TCPTABLE2
{
/// <include file='MIB_TCPTABLE2.xml' path='doc/member[@name="MIB_TCPTABLE2.dwNumEntries"]/*' />
[NativeTypeName("DWORD")]
public uint dwNumEntries;
/// <include file='MIB_TCPTABLE2.xml' path='doc/member[@name="MIB_TCPTABLE2.table"]/*' />
[NativeTypeName("MIB_TCPROW2 [1]")]
public _table_e__FixedBuffer table;
/// <include file='_table_e__FixedBuffer.xml' path='doc/member[@name="_table_e__FixedBuffer"]/*' />
public partial struct _table_e__FixedBuffer
{
public MIB_TCPROW2 e0;
public ref MIB_TCPROW2 this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref AsSpan(int.MaxValue)[index];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<MIB_TCPROW2> AsSpan(int length) => MemoryMarshal.CreateSpan(ref e0, length);
}
}
| 35.634146 | 145 | 0.689938 |
[
"MIT"
] |
reflectronic/terrafx.interop.windows
|
sources/Interop/Windows/Windows/shared/tcpmib/MIB_TCPTABLE2.cs
| 1,463 |
C#
|
//
// Copyright © Microsoft Corporation, All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
// ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
// PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache License, Version 2.0 for the specific language
// governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataModel.QueueMessage
{
/// <summary>
/// Models a RMS command that is transmitted in serialized format via Azure Queue from web role to worker role
/// </summary>
public class RmsCommand
{
private const char Delimiter = '/';
public enum Command
{
GetTemplate,
PublishTemplate
}
public Command RmsOperationCommand
{
get;
private set;
}
/// <summary>
/// Parameters to command
/// </summary>
public object[] Parameters
{
get;
private set;
}
/// <summary>
/// Makes an instance of RmsCommand from string
/// </summary>
/// <param name="stringfiedMessaged"></param>
public RmsCommand(string stringfiedMessaged)
{
//get command
string remainingString = stringfiedMessaged;
int firstIndexOfDelimiter = remainingString.IndexOf(Delimiter);
if (firstIndexOfDelimiter == -1)
{
this.RmsOperationCommand = remainingString.ConverToEnum<Command>();
return;
}
this.RmsOperationCommand = remainingString.Substring(0, firstIndexOfDelimiter).ConverToEnum<Command>();
remainingString = remainingString.Substring(firstIndexOfDelimiter).TrimStart(Delimiter);
//get parameters
List<object> parameters = new List<object>();
while (!string.IsNullOrWhiteSpace(remainingString))
{
firstIndexOfDelimiter = remainingString.IndexOf(Delimiter);
if (firstIndexOfDelimiter == -1)
{
parameters.Add(remainingString);
break;
}
parameters.Add(remainingString.Substring(0, firstIndexOfDelimiter));
remainingString = remainingString.Substring(firstIndexOfDelimiter).TrimStart(Delimiter);
}
Parameters = new object[parameters.Count];
parameters.CopyTo(Parameters);
}
public RmsCommand(Command command, params object[] parameters)
{
RmsOperationCommand = command;
Parameters = parameters;
}
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder(RmsOperationCommand.ConvertToString());
foreach (object parameter in Parameters)
{
stringBuilder.AppendFormat("{0}{1}", Delimiter, parameter.ToString());
}
return stringBuilder.ToString();
}
}
/// <summary>
/// Extension methods for enum to string and vice versa operations
/// </summary>
public static class EnumExtensions
{
public static string ConvertToString(this Enum en)
{
return Enum.GetName(en.GetType(), en);
}
public static EnumType ConverToEnum<EnumType>(this String eValue)
{
return (EnumType)Enum.Parse(typeof(EnumType), eValue);
}
}
}
| 31.983871 | 115 | 0.607665 |
[
"MIT"
] |
Azure-Samples/Azure-Information-Protection-Samples
|
IpcAzureApp/DataModel/QueueMessage/RmsCommand.cs
| 3,969 |
C#
|
namespace CookWithMe.Web.Areas.Identity.Pages.Account.Manage
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using CookWithMe.Common;
using CookWithMe.Data.Common.Repositories;
using CookWithMe.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
#pragma warning disable SA1649 // File name should match first type name
public class DeletePersonalDataModel : PageModel
#pragma warning restore SA1649 // File name should match first type name
{
private readonly UserManager<ApplicationUser> userManager;
private readonly SignInManager<ApplicationUser> signInManager;
private readonly ILogger<DeletePersonalDataModel> logger;
private readonly IDeletableEntityRepository<ApplicationUser> userRepository;
private readonly IDeletableEntityRepository<Review> reviewRepository;
private readonly IRepository<UserAllergen> userAllergenRepository;
private readonly IRepository<UserShoppingList> userShoppingListRepository;
private readonly IRepository<UserFavoriteRecipe> userFavoriteRecipeRepository;
private readonly IRepository<UserCookedRecipe> userCookedRecipeRepository;
public DeletePersonalDataModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<DeletePersonalDataModel> logger,
IDeletableEntityRepository<ApplicationUser> userRepository,
IDeletableEntityRepository<Review> reviewRepository,
IRepository<UserAllergen> userAllergenRepository,
IRepository<UserShoppingList> userShoppingListRepository,
IRepository<UserFavoriteRecipe> userFavoriteRecipeRepository,
IRepository<UserCookedRecipe> userCookedRecipeRepository)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.logger = logger;
this.userRepository = userRepository;
this.reviewRepository = reviewRepository;
this.userAllergenRepository = userAllergenRepository;
this.userShoppingListRepository = userShoppingListRepository;
this.userFavoriteRecipeRepository = userFavoriteRecipeRepository;
this.userCookedRecipeRepository = userCookedRecipeRepository;
}
[BindProperty]
public InputModel Input { get; set; }
public bool RequirePassword { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await this.userManager.GetUserAsync(this.User);
if (user == null)
{
return this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'.");
}
this.RequirePassword = await this.userManager.HasPasswordAsync(user);
return this.Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await this.userManager.GetUserAsync(this.User);
if (user == null)
{
return this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'.");
}
this.RequirePassword = await this.userManager.HasPasswordAsync(user);
if (this.RequirePassword)
{
if (!await this.userManager.CheckPasswordAsync(user, this.Input.Password))
{
this.ModelState.AddModelError(string.Empty, "Password not correct.");
return this.Page();
}
}
var userId = await this.userManager.GetUserIdAsync(user);
if (this.User.IsInRole(GlobalConstants.AdministratorRoleName))
{
this.userRepository.Delete(user);
}
else
{
// Delete all Reviews
var userReviews = await this.reviewRepository
.All()
.Where(x => x.ReviewerId == userId)
.ToListAsync();
foreach (var review in userReviews)
{
this.reviewRepository.HardDelete(review);
}
await this.reviewRepository.SaveChangesAsync();
// Delete all UserAllergens
var userAllergens = await this.userAllergenRepository
.All()
.Where(x => x.UserId == userId)
.ToListAsync();
foreach (var userAllergen in userAllergens)
{
this.userAllergenRepository.Delete(userAllergen);
}
await this.userAllergenRepository.SaveChangesAsync();
// Delete all UserShoppinglists
var userShoppingLists = await this.userShoppingListRepository
.All()
.Where(x => x.UserId == userId)
.ToListAsync();
foreach (var userShoppingList in userShoppingLists)
{
this.userShoppingListRepository.Delete(userShoppingList);
}
await this.userShoppingListRepository.SaveChangesAsync();
// Delete all UserFavoriteRecipes
var userFavoriteRecipes = await this.userFavoriteRecipeRepository
.All()
.Where(x => x.UserId == userId)
.ToListAsync();
foreach (var userFavoriteRecipe in userFavoriteRecipes)
{
this.userFavoriteRecipeRepository.Delete(userFavoriteRecipe);
}
await this.userFavoriteRecipeRepository.SaveChangesAsync();
// Delete all UserCookedRecipes
var userCookedRecipes = await this.userCookedRecipeRepository
.All()
.Where(x => x.UserId == userId)
.ToListAsync();
foreach (var userCookedRecipe in userCookedRecipes)
{
this.userCookedRecipeRepository.Delete(userCookedRecipe);
}
await this.userCookedRecipeRepository.SaveChangesAsync();
// Delete personal data
user.UserName = null;
user.NormalizedUserName = null;
user.Email = null;
user.NormalizedEmail = null;
user.PasswordHash = null;
user.FullName = "DELETED";
user.Biography = null;
user.ProfilePhoto = null;
user.LifestyleId = null;
user.HasAdditionalInfo = false;
this.userRepository.Update(user);
await this.userRepository.SaveChangesAsync();
this.userRepository.Delete(user);
}
var result = await this.userRepository.SaveChangesAsync();
if (result > 0 == false)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
await this.signInManager.SignOutAsync();
this.logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
return this.Redirect("~/");
}
public class InputModel
{
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}
}
| 38.676617 | 116 | 0.593645 |
[
"MIT"
] |
VioletaKirova/CookWithMe
|
Web/CookWithMe.Web/Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml.cs
| 7,776 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using MyJetWallet.Domain.Assets;
using Service.AssetsDictionary.Grpc;
using Service.AssetsDictionary.Services.Proto;
namespace Service.AssetsDictionary.Services
{
public class AssetsService: Assets.AssetsBase
{
private readonly IAssetsDictionaryService _service;
public AssetsService(IAssetsDictionaryService service)
{
_service = service;
}
public override async Task<GetAllAssetsResponse> GetAll(Empty request, ServerCallContext context)
{
var assets = await _service.GetAllAssetsAsync();
var response = new GetAllAssetsResponse();
response.Assets.AddRange(assets.Assets.Select(e => new Asset()
{
BrokerId = e.BrokerId,
Symbol = e.Symbol,
Accuracy = e.Accuracy,
Description = e.Description
}));
return response;
}
public override async Task<GetAssetBySymbolResponse> GetBySymbol(GetAssetBySymbolRequest request, ServerCallContext context)
{
var asset = await _service.GetAssetByIdAsync(new AssetIdentity()
{
BrokerId = request.BrokerId,
Symbol = request.Symbol
});
if (!asset.HasValue())
return new GetAssetBySymbolResponse();
return new GetAssetBySymbolResponse()
{
Asset = new Asset()
{
BrokerId = asset.Value.BrokerId,
Symbol = asset.Value.Symbol,
Accuracy = asset.Value.Accuracy,
Description = asset.Value.Description
}
};
}
}
}
| 30.698413 | 132 | 0.59514 |
[
"MIT"
] |
MyJetWallet/Service.AssetsDictionary
|
src/Service.AssetsDictionary/Services/AssetsService.cs
| 1,936 |
C#
|
using System.Net;
using Core.Api.Testing;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Warehouse.Products.GettingProducts;
using Warehouse.Products.RegisteringProduct;
using Xunit;
namespace Warehouse.Api.Tests.Products.GettingProducts;
public class GetProductsFixture: ApiFixture
{
protected override string ApiUrl => "/api/products";
protected override Func<IWebHostBuilder, IWebHostBuilder> SetupWebHostBuilder =>
whb => WarehouseTestWebHostBuilder.Configure(whb, nameof(GetProductsFixture));
public IList<ProductListItem> RegisteredProducts = new List<ProductListItem>();
public override async Task InitializeAsync()
{
var productsToRegister = new[]
{
new RegisterProductRequest("ZX1234", "ValidName", "ValidDescription"),
new RegisterProductRequest("AD5678", "OtherValidName", "OtherValidDescription"),
new RegisterProductRequest("BH90210", "AnotherValid", "AnotherValidDescription")
};
foreach (var registerProduct in productsToRegister)
{
var registerResponse = await Post(registerProduct);
registerResponse.EnsureSuccessStatusCode()
.StatusCode.Should().Be(HttpStatusCode.Created);
var createdId = await registerResponse.GetResultFromJson<Guid>();
var (sku, name, _) = registerProduct;
RegisteredProducts.Add(new ProductListItem(createdId, sku!, name!));
}
}
}
public class GetProductsTests: IClassFixture<GetProductsFixture>
{
private readonly GetProductsFixture fixture;
public GetProductsTests(GetProductsFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public async Task ValidRequest_With_NoParams_ShouldReturn_200()
{
// Given
// When
var response = await fixture.Get();
// Then
response.EnsureSuccessStatusCode()
.StatusCode.Should().Be(HttpStatusCode.OK);
var products = await response.GetResultFromJson<IReadOnlyList<ProductListItem>>();
products.Should().NotBeEmpty();
products.Should().BeEquivalentTo(fixture.RegisteredProducts);
}
[Fact]
public async Task ValidRequest_With_Filter_ShouldReturn_SubsetOfRecords()
{
// Given
var filteredRecord = fixture.RegisteredProducts.First();
var filter = fixture.RegisteredProducts.First().Sku.Substring(1);
// When
var response = await fixture.Get($"?filter={filter}");
// Then
response.EnsureSuccessStatusCode()
.StatusCode.Should().Be(HttpStatusCode.OK);
var products = await response.GetResultFromJson<IReadOnlyList<ProductListItem>>();
products.Should().NotBeEmpty();
products.Should().BeEquivalentTo(new List<ProductListItem>{filteredRecord});
}
[Fact]
public async Task ValidRequest_With_Paging_ShouldReturn_PageOfRecords()
{
// Given
const int page = 2;
const int pageSize = 1;
var filteredRecords = fixture.RegisteredProducts
.Skip(page - 1)
.Take(pageSize)
.ToList();
// When
var response = await fixture.Get($"?page={page}&pageSize={pageSize}");
// Then
response.EnsureSuccessStatusCode()
.StatusCode.Should().Be(HttpStatusCode.OK);
var products = await response.GetResultFromJson<IReadOnlyList<ProductListItem>>();
products.Should().NotBeEmpty();
products.Should().BeEquivalentTo(filteredRecords);
}
[Fact]
public async Task NegativePage_ShouldReturn_400()
{
// Given
var pageSize = -20;
// When
var response = await fixture.Get($"?page={pageSize}");
// Then
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
[Theory]
[InlineData(0)]
[InlineData(-20)]
public async Task NegativeOrZeroPageSize_ShouldReturn_400(int pageSize)
{
// Given
// When
var response = await fixture.Get($"?page={pageSize}");
// Then
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
}
| 30.223022 | 92 | 0.657939 |
[
"MIT"
] |
MaciejWolf/EventSourcing.NetCore
|
Sample/Warehouse/Warehouse.Api.Tests/Products/GettingProducts/GetProductsTests.cs
| 4,203 |
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Devon4Net.Infrastructure.MediatR.Domain.ServiceInterfaces;
using Devon4Net.Infrastructure.MediatR.Handler;
using Devon4Net.WebAPI.Implementation.Business.MediatRManagement.Commands;
using Devon4Net.WebAPI.Implementation.Business.MediatRManagement.Dto;
using Devon4Net.WebAPI.Implementation.Business.TodoManagement.Service;
namespace Devon4Net.WebAPI.Implementation.Business.MediatRManagement.Handlers
{
public class CreateTodoHandler : MediatrRequestHandler<CreateTodoCommand, TodoResultDto>
{
private ITodoService TodoService { get; set; }
public CreateTodoHandler(ITodoService todoService, IMediatRBackupService mediatRBackupService, IMediatRBackupLiteDbService mediatRBackupLiteDbService) : base(mediatRBackupService, mediatRBackupLiteDbService)
{
Setup(todoService);
}
public CreateTodoHandler(ITodoService todoService, IMediatRBackupLiteDbService mediatRBackupLiteDbService) : base(mediatRBackupLiteDbService)
{
Setup(todoService);
}
public CreateTodoHandler(ITodoService todoService, IMediatRBackupService mediatRBackupService) : base(mediatRBackupService)
{
Setup(todoService);
}
private void Setup(ITodoService todoService)
{
TodoService = todoService;
}
public override async Task<TodoResultDto> HandleAction(CreateTodoCommand request, CancellationToken cancellationToken)
{
if (TodoService == null)
{
throw new ArgumentException("The service 'TodoService' is not ready. Please check your dependency injection declaration for this service");
}
var result = await TodoService.CreateTodo(request.Description);
return new TodoResultDto
{
Id = result.Id,
Done = result.Done,
Description = result.Description
};
}
}
}
| 35.859649 | 215 | 0.703523 |
[
"Apache-2.0"
] |
JuanSGA24/Alejandria
|
source/Templates/WebAPI/Devon4Net.WebAPI.Implementation/Business/MediatRManagement/Handlers/CreateTodoHandler.cs
| 2,046 |
C#
|
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
namespace FantasyData.Api.Client.Model.NHL
{
[DataContract(Namespace="", Name="TeamLine")]
[Serializable]
public partial class TeamLine
{
/// <summary>
/// The unique ID for the team
/// </summary>
[Description("The unique ID for the team")]
[DataMember(Name = "TeamID", Order = 1)]
public int TeamID { get; set; }
/// <summary>
/// Whether or not the team is active
/// </summary>
[Description("Whether or not the team is active")]
[DataMember(Name = "Key", Order = 2)]
public string Key { get; set; }
/// <summary>
/// The full team name
/// </summary>
[Description("The full team name")]
[DataMember(Name = "FullName", Order = 3)]
public string FullName { get; set; }
/// <summary>
/// The even strength lines for this team
/// </summary>
[Description("The even strength lines for this team")]
[DataMember(Name = "EvenStrengthLines", Order = 20004)]
public PlayerLine[] EvenStrengthLines { get; set; }
/// <summary>
/// The power play lines for this team
/// </summary>
[Description("The power play lines for this team")]
[DataMember(Name = "PowerPlayLines", Order = 20005)]
public PlayerLine[] PowerPlayLines { get; set; }
}
}
| 30.163265 | 63 | 0.570365 |
[
"MIT"
] |
SebastianLng/fantasydata-api-csharp
|
FantasyData.Api.Client/Model/NHL/TeamLine.cs
| 1,480 |
C#
|
// Copyright 2020 The Tilt Brush Authors
//
// 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.
// Only works on ARGB32, RGB24 and Alpha8 textures that are marked readable
using System;
using System.Threading;
using UnityEngine;
namespace TiltBrush {
public class TextureScale {
public class SharedData {
// mutable
public int finishCount;
// read only
public Mutex mutex;
public Color32[] newColors;
public Color32[] texColors;
public int texWidth;
public int newWidth;
public float ratioX;
public float ratioY;
}
public class ThreadData {
// read only
public SharedData shared;
public int start;
public int end;
}
/// Like Bilinear(), but with an easier interface.
/// Blocking, runs on current thread.
/// newColors may be null.
/// Return value may reuse texColors or newColors (or neither!)
public static Color32[] BlockingBilinear(
Color32[] texColors, int texWidth, int texHeight,
Color32[] newColors, int newWidth, int newHeight) {
if (texWidth == newWidth && texHeight == newHeight) {
return texColors;
}
if (newColors == null) {
newColors = new Color32[newWidth * newHeight];
}
Bilinear(texColors, texWidth, texHeight,
newColors, newWidth, newHeight);
return newColors;
}
// Helper for Bilinear()
// Returns a value up to 1 unit closer to desired (in log2 space)
static int moveTowardsLog(int start, int desired) {
if (start * desired <= 0) {
throw new System.ArgumentException("Signs must be the same; 0 not allowed.");
}
// Want the non-multiple of two to be at the upper end of the progression,
// for better filtering. But this is easier to write.
if (desired < start) {
int temp = start >> 1;
return (temp < desired ? desired : temp);
} else {
long temp = start << 1;
return (temp > desired ? desired : (int)temp);
}
}
// Helper to deal with manual buffer management.
// The repeated bilinear filtering seems to be causing excessive garbage
// to stick around.
unsafe struct ColorBuffer {
IntPtr dealloc; // Pointer to deallocate, or 0 if not explicitly allocated
public Color32* array;
public int length; // number of elements in array
public int width, height; // 2D size (product must be <= length)
// no allocation; pointer comes from a []
public ColorBuffer(Color32[] c, Color32* pc, int width_, int height_) {
width = width_;
height = height_;
length = c.Length;
dealloc = IntPtr.Zero;
array = pc;
}
// allocate non-garbage-collected memory
public ColorBuffer(int width_, int height_) {
width = width_;
height = height_;
length = width * height;
dealloc = System.Runtime.InteropServices.Marshal.AllocHGlobal(length * sizeof(Color32));
array = (Color32*)dealloc;
}
public void Deallocate() {
if (dealloc != IntPtr.Zero) {
System.Runtime.InteropServices.Marshal.FreeHGlobal(dealloc);
dealloc = IntPtr.Zero;
array = null;
length = width = height = 0;
}
}
};
/// Simplified to be single-threaded and blocking
private unsafe static void Bilinear(
Color32[] texColors, int texWidth, int texHeight,
Color32[] newColors, int newWidth, int newHeight) {
// A single pass of bilinear filtering blends 4 pixels together,
// so don't try to reduce by more than a factor of 2 per iteration
Debug.Assert(newWidth * newHeight == newColors.Length);
fixed (Color32* pTex = texColors) {
ColorBuffer cur = new ColorBuffer(texColors, pTex, texWidth, texHeight);
while (true) {
int tmpWidth = moveTowardsLog(cur.width, newWidth);
int tmpHeight = moveTowardsLog(cur.height, newHeight);
if (newColors.Length == tmpWidth * tmpHeight) {
fixed (Color32* pNew = newColors) {
SinglePassBilinear(cur.array, cur.length, cur.width, cur.height,
pNew, newColors.Length, newWidth, newHeight);
}
return;
}
ColorBuffer tmp = new ColorBuffer(tmpWidth, tmpHeight);
SinglePassBilinear(cur.array, cur.length, cur.width, cur.height,
tmp.array, tmp.length, tmp.width, tmp.height);
cur.Deallocate();
cur = tmp;
}
}
}
/// Unthreaded single pass bilinear filter
private static unsafe void SinglePassBilinear(
Color32* texColors, int texLen, int texWidth, int texHeight,
Color32* newColors, int newLen, int newWidth, int newHeight) {
if (newLen < newWidth * newHeight) {
Debug.Assert(newLen >= newWidth * newHeight);
return;
}
#if false
// For reference, this is the point-sampled loop
float ratioX = ((float)texWidth) / newWidth;
float ratioY = ((float)texHeight) / newHeight;
for (var y = start; y < end; y++) {
var thisY = (int)(ratioY * y) * w;
var yw = y * w2;
for (var x = 0; x < w2; x++) {
newColors[yw + x] = texColors[(int)(thisY + ratioX * x)];
}
}
#endif
float ratioX = 1.0f / ((float)newWidth / (texWidth - 1));
float ratioY = 1.0f / ((float)newHeight / (texHeight - 1));
{
var w = texWidth;
var w2 = newWidth;
for (int y = 0; y < newHeight; y++) {
int yFloor = (int)Mathf.Floor(y * ratioY);
var y1 = yFloor * w;
var y2 = (yFloor + 1) * w;
var yw = y * w2;
for (int x = 0; x < w2; x++) {
int xFloor = (int)Mathf.Floor(x * ratioX);
var xLerp = x * ratioX - xFloor;
newColors[yw + x] = ColorLerpUnclamped(
ColorLerpUnclamped(texColors[y1 + xFloor], texColors[y1 + xFloor + 1], xLerp),
ColorLerpUnclamped(texColors[y2 + xFloor], texColors[y2 + xFloor + 1], xLerp),
y * ratioY - yFloor);
}
}
}
}
//
// Safe Compress will only compress pow of 2 textures
// Non pow 2 textures get extremely strange mipmap artifacts when compressed
// If we run into memory issues here, we may need to convert all incoming textures textures to pow of 2
// But if we do that we need to save the image aspect ratio before compression for reference Images
//
public static bool SafeCompress(Texture2D tex, bool highQuality = false) {
if (Mathf.IsPowerOfTwo(tex.width) && Mathf.IsPowerOfTwo(tex.height)) {
tex.Compress(highQuality);
return true;
} else {
return false;
}
}
private static Color32 ColorLerpUnclamped(Color32 c1, Color32 c2, float value) {
return new Color32(
(byte)(c1.r + (c2.r - c1.r) * value),
(byte)(c1.g + (c2.g - c1.g) * value),
(byte)(c1.b + (c2.b - c1.b) * value),
(byte)(c1.a + (c2.a - c1.a) * value));
}
}
} // namespace TiltBrush
| 34.018433 | 105 | 0.628962 |
[
"Apache-2.0"
] |
Babouchot/open-brush
|
Assets/Scripts/TextureScale.cs
| 7,384 |
C#
|
using Common;
using Plugin.Base;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Plugin.Microsoft.Azure.SignalR.Benchmark.AgentMethods
{
public class StreamingEcho : BaseStreamingSendMethod, IAgentMethod
{
public Task<IDictionary<string, object>> Do(
IDictionary<string, object> stepParameters,
IDictionary<string, object> pluginParameters)
{
return SimpleScenarioSend(stepParameters, pluginParameters, SignalRConstants.StreamingEchoCallbackName);
}
protected override async Task<IDictionary<string, object>> SimpleScenarioSend(
IDictionary<string, object> stepParameters,
IDictionary<string, object> pluginParameters,
string callbackMethod)
{
try
{
Log.Information($"Start {GetType().Name}...");
LoadParametersAndContext(stepParameters, pluginParameters);
// Generate necessary data
var data = new Dictionary<string, object>
{
{ SignalRConstants.MessageBlob, SignalRUtils.GenerateRandomData(MessageSize) } // message payload
};
// Reset counters
UpdateStatistics(StatisticsCollector, RemainderEnd);
// Send messages
await Task.WhenAll(from i in Enumerable.Range(0, Connections.Count)
where ConnectionIndex[i] % Modulo >= RemainderBegin && ConnectionIndex[i] % Modulo < RemainderEnd
select ContinuousSend((Connection: Connections[i],
LocalIndex: i,
CallbackMethod: callbackMethod,
StreamItemsCount,
StreamItemInterval),
data,
StreamingBaseSendAsync,
TimeSpan.FromMilliseconds(Duration),
TimeSpan.FromMilliseconds(Interval),
TimeSpan.FromMilliseconds(1),
TimeSpan.FromMilliseconds(Interval)));
Log.Information($"Finish {GetType().Name} {RemainderEnd}");
return null;
}
catch (Exception ex)
{
var message = $"Fail to {GetType().Name}: {ex}";
Log.Error(message);
throw;
}
}
protected async Task StreamingBaseSendAsync(
(IHubConnectionAdapter Connection,
int LocalIndex,
string CallbackMethod,
int streamCount,
int streamItemInterval) package,
IDictionary<string, object> data)
{
async Task StreamingWriter(ChannelWriter<IDictionary<string, object>> writer, IDictionary<string, object> sentData, int count, int streamItemWaiting)
{
Exception localException = null;
try
{
for (var i = 0; i < count; i++)
{
sentData[SignalRConstants.Timestamp] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
await writer.WriteAsync(sentData);
if (streamItemWaiting > 0)
{
await Task.Delay(streamItemWaiting);
}
// Update statistics
SignalRUtils.RecordSend(sentData, StatisticsCollector);
}
}
catch (Exception ex)
{
localException = ex;
}
writer.Complete(localException);
}
try
{
// Is the connection is not active, then stop sending message
if (package.Connection.GetStat() != SignalREnums.ConnectionInternalStat.Active)
return;
var payload = GenPayload(data);
var channel = Channel.CreateUnbounded<IDictionary<string, object>>();
_ = StreamingWriter(channel.Writer, payload, package.streamCount, package.streamItemInterval);
using (var c = new CancellationTokenSource(TimeSpan.FromSeconds(5 * package.streamCount)))
{
int recvCount = 0;
var stream = await package.Connection.StreamAsChannelAsync<IDictionary<string, object>>(package.CallbackMethod, channel.Reader, package.streamItemInterval, c.Token);
while (await stream.WaitToReadAsync(c.Token))
{
while (stream.TryRead(out var item))
{
var receiveTimestamp = Util.Timestamp();
if (item.TryGetValue(SignalRConstants.Timestamp, out object v))
{
var value = v.ToString();
var sendTimestamp = Convert.ToInt64(value);
var latency = receiveTimestamp - sendTimestamp;
StatisticsCollector.RecordLatency(latency);
SignalRUtils.RecordRecvSize(item, StatisticsCollector);
recvCount++;
}
}
}
if (recvCount < package.streamCount)
{
Log.Error($"The received streaming items {recvCount} is not equal to sending items {package.streamCount}");
StatisticsCollector.IncreaseStreamItemMissing(1);
}
}
}
catch (Exception ex)
{
var message = $"Error in {GetType().Name}: {ex}";
Log.Error(message);
}
}
}
}
| 45.265734 | 185 | 0.486328 |
[
"MIT"
] |
isabella232/azure-signalr-bench
|
src/signalr/AgentMethods/StreamingEcho.cs
| 6,475 |
C#
|
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Threading.Tasks;
using osu.Game.Online.API;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Rooms;
using osu.Server.Spectator.Entities;
namespace osu.Server.Spectator.Hubs
{
/// <summary>
/// Allows communication with multiplayer clients from potentially outside of a direct <see cref="MultiplayerHub"/> context.
/// </summary>
public interface IMultiplayerHubContext
{
/// <summary>
/// Notifies users in a room of an event.
/// </summary>
/// <remarks>
/// This should be used for events which have no permanent effect on state.
/// For operations which are intended to persist (and be visible to new users which join a room) use <see cref="NotifyMatchRoomStateChanged"/> or <see cref="NotifyMatchUserStateChanged"/> instead.
/// </remarks>
/// <param name="room">The room to send the event to.</param>
/// <param name="e">The event.</param>
Task NotifyNewMatchEvent(ServerMultiplayerRoom room, MatchServerEvent e);
/// <summary>
/// Notify users in a room that the room's <see cref="MultiplayerRoom.MatchState"/> has been altered.
/// </summary>
/// <param name="room">The room whose state has changed.</param>
Task NotifyMatchRoomStateChanged(ServerMultiplayerRoom room);
/// <summary>
/// Notifies users in a room that a user's <see cref="MultiplayerRoomUser.MatchState"/> has been altered.
/// </summary>
/// <param name="room">The room to send the event to.</param>
/// <param name="user">The user whose state has changed.</param>
Task NotifyMatchUserStateChanged(ServerMultiplayerRoom room, MultiplayerRoomUser user);
/// <summary>
/// Notifies users in a room that a playlist item has been added.
/// </summary>
/// <param name="room">The room to send the event to.</param>
/// <param name="item">The added item.</param>
Task NotifyPlaylistItemAdded(ServerMultiplayerRoom room, MultiplayerPlaylistItem item);
/// <summary>
/// Notifies users in a room that a playlist item has been removed.
/// </summary>
/// <param name="room">The room to send the event to.</param>
/// <param name="playlistItemId">The removed item.</param>
Task NotifyPlaylistItemRemoved(ServerMultiplayerRoom room, long playlistItemId);
/// <summary>
/// Notifies users in a room that a playlist item has been changed.
/// </summary>
/// <remarks>
/// Adjusts user mod selections to ensure mod validity, and unreadies all users and stops the current countdown if the currently-selected playlist item was changed.
/// </remarks>
/// <param name="room">The room to send the event to.</param>
/// <param name="item">The changed item.</param>
Task NotifyPlaylistItemChanged(ServerMultiplayerRoom room, MultiplayerPlaylistItem item);
/// <summary>
/// Notifies users in a room that the room's settings have changed.
/// </summary>
/// <remarks>
/// Adjusts user mod selections to ensure mod validity, unreadies all users, and stops the current countdown.
/// </remarks>
/// <param name="room">The room to send the event to.</param>
Task NotifySettingsChanged(ServerMultiplayerRoom room);
/// <summary>
/// Retrieves a <see cref="ServerMultiplayerRoom"/> usage.
/// </summary>
/// <param name="roomId">The ID of the room to retrieve.</param>
Task<ItemUsage<ServerMultiplayerRoom>> GetRoom(long roomId);
/// <summary>
/// Unreadies all users in a room.
/// </summary>
/// <remarks>
/// Stops the current countdown.
/// </remarks>
/// <param name="room">The room to unready users in.</param>
Task UnreadyAllUsers(ServerMultiplayerRoom room);
/// <summary>
/// Adjusts user mod selections to ensure they're valid for the current playlist item.
/// </summary>
/// <param name="room">The room to validate user mods in.</param>
Task EnsureAllUsersValidMods(ServerMultiplayerRoom room);
/// <summary>
/// Changes a user's mods in a room.
/// </summary>
/// <param name="newMods">The new mod selection.</param>
/// <param name="room">The room containing the user.</param>
/// <param name="user">The user.</param>
/// <exception cref="InvalidStateException">If the new selection is not valid for current playlist item.</exception>
Task ChangeUserMods(IEnumerable<APIMod> newMods, ServerMultiplayerRoom room, MultiplayerRoomUser user);
/// <summary>
/// Changes a user's state in a room.
/// </summary>
/// <param name="room">The room containing the user.</param>
/// <param name="user">The user.</param>
/// <param name="state">The new state.</param>
Task ChangeAndBroadcastUserState(ServerMultiplayerRoom room, MultiplayerRoomUser user, MultiplayerUserState state);
/// <summary>
/// Changes a room's state.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="newState">The new room state.</param>
Task ChangeRoomState(ServerMultiplayerRoom room, MultiplayerRoomState newState);
/// <summary>
/// Starts a match in a room.
/// </summary>
/// <param name="room">The room to start the match for.</param>
/// <exception cref="InvalidStateException">If the current playlist item is expired or the room is not in an <see cref="MultiplayerRoomState.Open"/> state.</exception>
Task StartMatch(ServerMultiplayerRoom room);
}
}
| 46.953125 | 204 | 0.636439 |
[
"MIT"
] |
ppy/osu-serer-spectator
|
osu.Server.Spectator/Hubs/IMultiplayerHubContext.cs
| 6,010 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ejercicio_2
{
/*
02. Ingresar un número y mostrar: el cuadrado y el cubo del mismo. Se
debe validar que el número sea mayor que cero, caso contrario,
mostrar el mensaje: "ERROR. Reingresar número!!!".
Nota: Utilizar el método ‘Pow’ de la clase Math para realizar la
operación.
*/
class Ejercicio_2
{
static void Main(string[] args)
{
double numero;
double cuadrado;
double cubo;
Console.Title = "Ejercicio Nro. 2";
Console.Write("Ingrese un numero mayor a 0: ");
do
{
while (!double.TryParse(Console.ReadLine(), out numero))
{
Console.Clear();
Console.Write("Error!!! No se ingreso un numero. Ingrese un numero mayor a 0: ");
}
if (numero <= 0)
{
Console.Clear();
Console.Write("ERROR. Reingresar número!!! ");
}
} while (numero <= 0);
cuadrado = Math.Pow(numero, 2);
cubo = Math.Pow(numero, 3);
Console.Clear();
Console.Write("El cuadrado de {0,0:#,###.00} es {1,0:#,###.00}, y al cubo es {2,0:#,###.00}. ", numero, cuadrado, cubo);
Console.ReadKey();
}
}
}
| 28.12963 | 133 | 0.484529 |
[
"CC0-1.0"
] |
RomeroFederico/Lab2ConceptosBasicosEj2
|
Ejercicio_2/Program.cs
| 1,531 |
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1433
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Mediachase.UI.Web.FileStorage {
/// <summary>
/// DownloadLink class.
/// </summary>
/// <remarks>
/// Auto-generated class.
/// </remarks>
public partial class DownloadLink {
/// <summary>
/// pT control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Mediachase.UI.Web.Modules.PageTemplateNext pT;
}
}
| 29.46875 | 84 | 0.480382 |
[
"MIT"
] |
InstantBusinessNetwork/IBN
|
Source/Server/WebPortal/FileStorage/DownloadLink.aspx.designer.cs
| 943 |
C#
|
#if UNITY_EDITOR
#pragma warning disable 0168 // variable declared but not used.
#pragma warning disable 0219 // variable assigned but not used.
#pragma warning disable 0414 // private field assigned but not used.
using UnityEngine;
using UnityEditor;
namespace Sketchfab
{
public class SketchfabUI
{
// Sketchfab UI
public GUIStyle basic;
public bool _isInitialized = false;
// UI Elements
public static Color SKFB_RED = new Color(0.8f, 0.0f, 0.0f);
public static Color SKFB_BLUE = new Color(69 / 255.0f, 185 / 255.0f, 223 / 255.0f);
public static string CLICKABLE_COLOR = "navy";
public static string ERROR_COLOR = "red";
public static Texture2D HEADER;
public static Texture2D DEFAULT_AVATAR;
Font OSBold;
Font OSLight;
Font OSRegular;
Font OSSemiBold;
Font TitiliumBlack;
Font TitiliumBold;
Font TitiliumLight;
Font TitiliumRegular;
Font TitiliumSemibold;
Font TitiliumThin;
public GUIStyle sketchfabModelName;
public GUIStyle sketchfabTitleLabel;
public GUIStyle sketchfabContentLabel;
public GUIStyle sketchfabSubContentLabel;
public GUIStyle keyStyle;
public GUIStyle valueStyle;
public GUIStyle sketchfabMiniModelname;
public GUIStyle sketchfabMiniAuthorname;
public GUIStyle SkfbClickableLabel;
public GUIStyle SketchfabButton;
public GUIStyle SketchfabLabel;
public SketchfabUI()
{
Initialize();
_isInitialized = true;
}
private void Initialize()
{
//basic
basic = new GUIStyle();
basic.fontStyle = FontStyle.BoldAndItalic;
// Fonts
OSLight = Resources.Load<Font>("OpenSans-Light");
OSBold = Resources.Load<Font>("OpenSans-Bold");
OSRegular = Resources.Load<Font>("OpenSans-Regular");
OSSemiBold = Resources.Load<Font>("OpenSans-SemiBold");
TitiliumBlack = Resources.Load<Font>("TitilliumWeb-Black");
TitiliumBold = Resources.Load<Font>("TitilliumWeb-Bold");
TitiliumLight = Resources.Load<Font>("TitilliumWeb-Light");
TitiliumRegular = Resources.Load<Font>("TitilliumWeb-Regular");
TitiliumSemibold = Resources.Load<Font>("TitilliumWeb-Semibold");
TitiliumThin = Resources.Load<Font>("TitilliumWeb-Thin");
sketchfabModelName = new GUIStyle(EditorStyles.wordWrappedMiniLabel);
sketchfabModelName.font = TitiliumBold;
sketchfabModelName.fontSize = 20;
sketchfabTitleLabel = new GUIStyle(EditorStyles.wordWrappedMiniLabel);
sketchfabTitleLabel.font = TitiliumRegular;
// Content label
sketchfabContentLabel = new GUIStyle(EditorStyles.wordWrappedMiniLabel);
sketchfabContentLabel.font = OSRegular;
sketchfabContentLabel.fontSize = 14;
sketchfabContentLabel.richText = true;
sketchfabSubContentLabel = new GUIStyle(sketchfabContentLabel);
sketchfabSubContentLabel.font = OSRegular;
sketchfabSubContentLabel.fontSize = 12;
sketchfabSubContentLabel.richText = true;
keyStyle = new GUIStyle(EditorStyles.label);
keyStyle.alignment = TextAnchor.MiddleLeft;
keyStyle.font = OSRegular;
keyStyle.fontSize = 12;
valueStyle = new GUIStyle(EditorStyles.label);
valueStyle.alignment = TextAnchor.MiddleRight;
valueStyle.font = OSBold;
valueStyle.fontSize = 12;
sketchfabMiniModelname = new GUIStyle(EditorStyles.miniLabel);
sketchfabMiniModelname.font = OSSemiBold;
sketchfabMiniModelname.fontSize = 12;
sketchfabMiniModelname.wordWrap = true;
sketchfabMiniModelname.alignment = TextAnchor.UpperCenter;
sketchfabMiniModelname.clipping = TextClipping.Clip;
sketchfabMiniModelname.margin = new RectOffset(0, 0, 0, 0);
sketchfabMiniModelname.padding = new RectOffset(0, 0, 0, 0);
sketchfabMiniAuthorname = new GUIStyle(EditorStyles.miniLabel);
sketchfabMiniAuthorname.font = OSRegular;
sketchfabMiniAuthorname.fontSize = 10;
sketchfabMiniAuthorname.wordWrap = true;
sketchfabMiniAuthorname.alignment = TextAnchor.UpperCenter;
sketchfabMiniAuthorname.clipping = TextClipping.Clip;
sketchfabMiniAuthorname.margin = new RectOffset(0, 0, 0, 0);
sketchfabMiniAuthorname.padding = new RectOffset(0, 0, 0, 0);
SkfbClickableLabel = new GUIStyle(EditorStyles.centeredGreyMiniLabel);
SkfbClickableLabel.richText = true;
SketchfabButton = new GUIStyle(EditorStyles.miniButton);
SketchfabButton.font = OSSemiBold;
SketchfabButton.fontSize = 11;
SketchfabButton.fixedHeight = 24;
SketchfabLabel = new GUIStyle(EditorStyles.miniLabel);
SketchfabLabel.richText = true;
}
public void displayModelName(string modelName)
{
GUILayout.Label(modelName, sketchfabModelName);
}
public void displayTitle(string title)
{
GUILayout.Label(title, sketchfabTitleLabel);
}
public void displayContent(string content)
{
GUILayout.Label(content, sketchfabContentLabel);
}
public void displaySubContent(string subContent)
{
GUILayout.Label(subContent, sketchfabSubContentLabel);
}
public void showUpToDate(string latestVersion)
{
GUILayout.BeginHorizontal();
GUILayout.Label("Exporter is up to date (version:" + latestVersion + ")", EditorStyles.centeredGreyMiniLabel);
GUILayout.FlexibleSpace();
if (GUILayout.Button(ClickableTextColor("Help"), SkfbClickableLabel, GUILayout.Height(20)))
{
Application.OpenURL(SketchfabPlugin.Urls.latestRelease);
}
if (GUILayout.Button(ClickableTextColor("Report an issue"), SkfbClickableLabel, GUILayout.Height(20)))
{
Application.OpenURL(SketchfabPlugin.Urls.reportAnIssue);
}
GUILayout.EndHorizontal();
}
public void displayModelStats(string key, string value)
{
GUILayout.BeginHorizontal(GUILayout.Width(200));
GUILayout.Label(key, keyStyle);
GUILayout.Label(value, valueStyle);
GUILayout.EndHorizontal();
}
public static Texture2D MakeTex(int width, int height, Color col)
{
Color[] pix = new Color[width * height];
for (int i = 0; i < pix.Length; ++i)
{
pix[i] = col;
}
Texture2D result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}
public static string ClickableTextColor(string text)
{
return "<color=" + SketchfabUI.CLICKABLE_COLOR + ">" + text + "</color>";
}
public static string ErrorTextColor(string text)
{
return "<color=" + SketchfabUI.ERROR_COLOR + ">" + text + "</color>";
}
}
}
#endif
| 31.268657 | 113 | 0.747017 |
[
"BSD-2-Clause"
] |
1-10/VisualEffectGraphSample
|
Assets/Sketchfab For Unity/Scripts/SketchfabUI.cs
| 6,287 |
C#
|
using System;
using System.Text;
namespace StriderMqtt
{
public class ConnectPacket : PacketBase
{
internal const byte PacketTypeCode = 0x01;
internal const string ProtocolNameV3_1 = "MQIsdp";
internal const string ProtocolNameV3_1_1 = "MQTT";
// max length for client id (removed in 3.1.1)
internal const int ClientIdMaxLength = 23;
internal const ushort KeepAlivePeriodDefault = 60; // seconds
// connect flags
internal const byte UsernameFlagOffset = 0x07;
internal const byte PasswordFlagOffset = 0x06;
internal const byte WillRetainFlagOffset = 0x05;
internal const byte WillQosFlagOffset = 0x03;
internal const byte WillFlagOffset = 0x02;
internal const byte CleanSessionFlagOffset = 0x01;
public MqttProtocolVersion ProtocolVersion
{
get;
set;
}
public string ClientId
{
get;
set;
}
public bool WillRetain
{
get;
set;
}
public MqttQos WillQosLevel
{
get;
set;
}
public bool WillFlag
{
get;
set;
}
public string WillTopic
{
get;
set;
}
public byte[] WillMessage
{
get;
set;
}
public string Username
{
get;
set;
}
public string Password
{
get;
set;
}
public bool CleanSession
{
get;
set;
}
internal ushort KeepAlivePeriod
{
get;
set;
}
internal ConnectPacket()
{
this.PacketType = PacketTypeCode;
}
/// <summary>
/// Reads a Connect packet from the given stream.
/// (This method should not be used since clients don't receive Connect packets)
/// </summary>
/// <param name="fixedHeaderFirstByte">Fixed header first byte previously read</param>
/// <param name="stream">The stream to read from</param>
/// <param name="protocolVersion">The protocol version to be used to read</param>
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Connect packet should not be received");
}
/// <summary>
/// Writes the Connect packet to the given stream and using the given
/// protocol version.
/// </summary>
/// <param name="stream">The stream to write to</param>
/// <param name="protocolVersion">Protocol to be used to write</param>
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
if (protocolVersion == MqttProtocolVersion.V3_1_1)
{
// will flag set, will topic and will message MUST be present
if (this.WillFlag && (WillMessage == null || String.IsNullOrEmpty(WillTopic)))
{
throw new MqttProtocolException("Last will message is invalid");
}
// willflag not set, retain must be 0 and will topic and message MUST NOT be present
else if (!this.WillFlag && (this.WillRetain || WillMessage != null || !String.IsNullOrEmpty(WillTopic)))
{
throw new MqttProtocolException("Last will message is invalid");
}
}
if (this.WillFlag && ((this.WillTopic.Length < Packet.MinTopicLength) || (this.WillTopic.Length > Packet.MaxTopicLength)))
{
throw new MqttProtocolException("Invalid last will topic length");
}
writer.SetFixedHeader(PacketType);
MakeVariableHeader(writer);
MakePayload(writer);
}
void MakeVariableHeader(PacketWriter w)
{
if (this.ProtocolVersion == MqttProtocolVersion.V3_1)
{
w.AppendTextField(ProtocolNameV3_1);
}
else
{
w.AppendTextField(ProtocolNameV3_1_1);
}
w.Append((byte)this.ProtocolVersion);
w.Append(MakeConnectFlags());
w.AppendIntegerField(KeepAlivePeriod);
}
byte MakeConnectFlags()
{
byte connectFlags = 0x00;
connectFlags |= (Username != null) ? (byte)(1 << UsernameFlagOffset) : (byte)0x00;
connectFlags |= (Password != null) ? (byte)(1 << PasswordFlagOffset) : (byte)0x00;
connectFlags |= (this.WillRetain) ? (byte)(1 << WillRetainFlagOffset) : (byte)0x00;
if (this.WillFlag)
connectFlags |= (byte)((byte)WillQosLevel << WillQosFlagOffset);
connectFlags |= (this.WillFlag) ? (byte)(1 << WillFlagOffset) : (byte)0x00;
connectFlags |= (this.CleanSession) ? (byte)(1 << CleanSessionFlagOffset) : (byte)0x00;
return connectFlags;
}
void MakePayload(PacketWriter w)
{
w.AppendTextField(ClientId);
if (!String.IsNullOrEmpty(WillTopic))
{
w.AppendTextField(WillTopic);
}
if (WillMessage != null)
{
w.AppendBytesField(WillMessage);
}
if (Username != null)
{
w.AppendTextField(Username);
}
if (Password != null)
{
w.AppendTextField(Password);
}
}
}
public class ConnackPacket : PacketBase
{
internal const byte PacketTypeCode = 0x02;
private const byte SessionPresentFlag = 0x01;
public bool SessionPresent {
get;
private set;
}
public ConnackReturnCode ReturnCode {
get;
set;
}
internal ConnackPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Clients should not send connack packets");
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
if (protocolVersion == MqttProtocolVersion.V3_1_1)
{
if ((reader.FixedHeaderFirstByte & Packet.PacketFlagsBitMask) != Packet.ZeroedHeaderFlagBits)
{
throw new MqttProtocolException("Connack packet received with invalid header flags");
}
}
if (reader.RemainingLength != 2)
{
throw new MqttProtocolException("Connack packet received with invalid remaining length");
}
this.SessionPresent = (reader.ReadByte() & SessionPresentFlag) > 0;
this.ReturnCode = (ConnackReturnCode)reader.ReadByte();
}
}
internal class PingreqPacket : PacketBase
{
internal const byte PacketTypeCode = 0x0C;
internal const byte PingreqFlagBits = 0x00;
internal PingreqPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
writer.SetFixedHeader(this.PacketType);
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Pingreq packet should not be received");
}
}
internal class PingrespPacket : PacketBase
{
internal const byte PacketTypeCode = 0x0D;
internal PingrespPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Clients should not send pingresp packets");
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
if (protocolVersion == MqttProtocolVersion.V3_1_1)
{
if ((reader.FixedHeaderFirstByte & Packet.PacketFlagsBitMask) != Packet.ZeroedHeaderFlagBits)
{
throw new MqttProtocolException("Pingresp packet received with invalid header flags");
}
}
if (reader.RemainingLength != 0)
{
throw new MqttProtocolException("Pingresp packet received with invalid remaining length");
}
}
}
internal class DisconnectPacket : PacketBase
{
internal const byte PacketTypeCode = 0x0E;
internal DisconnectPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Disconnect packet should not be received");
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
writer.SetFixedHeader(PacketType);
}
}
}
| 24.30581 | 125 | 0.676774 |
[
"Apache-2.0"
] |
RapidScada/scada-community
|
Drivers/KpMqtt/KpMqtt/StriderMqtt/ConnectionPackets.cs
| 7,948 |
C#
|
using RobotCtrl;
namespace Testat2.Tracks
{
internal class ArcRight : Track
{
private readonly float angle;
private readonly float radius;
internal ArcRight(Robot robot, ObstacleDetector obstacleDetector, float angle, float radius) : base(robot, obstacleDetector)
{
this.angle = angle;
this.radius = radius;
}
protected override void RunTrack()
{
this.Robot.Drive.RunArcRight(this.radius, this.angle, this.Speed, this.Acceleration);
}
}
}
| 26.181818 | 133 | 0.598958 |
[
"MIT"
] |
wtjerry/hslu_csa
|
Testat2/Tracks/ArcRight.cs
| 578 |
C#
|
using System.Collections.Generic;
using sfa.Tl.Marketing.Communication.Models.Dto;
namespace sfa.Tl.Marketing.Communication.UnitTests.Builders
{
public class ProviderLocationBuilder
{
public ProviderLocation Build() => new ProviderLocation
{
ProviderName = "Test Provider",
Name = "Test Location",
Postcode = "CV1 2WT",
Town = "Coventry",
Latitude = 52.400997,
Longitude = -1.508122,
DistanceInMiles = 9.5,
DeliveryYears = new List<DeliveryYear>(),
Website = "https://test.provider.co.uk"
};
}
}
| 29.181818 | 63 | 0.588785 |
[
"MIT"
] |
uk-gov-mirror/SkillsFundingAgency.tl-marketing-and-communication
|
Tests/sfa.Tl.Marketing.Communication.Tests/Builders/ProviderLocationBuilder.cs
| 644 |
C#
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ShareFile.Api.Client;
using ShareFile.Api.Client.Events;
using ShareFile.Api.Models;
using ShareFile.Api.Powershell.Browser;
using ShareFile.Api.Powershell.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ShareFile.Api.Powershell
{
/// <summary>
/// Class the encapsulates a ShareFile Client SDK and an OAuth authentication context.
/// It extends the SDK Client to support persistency of authentication context (OAuth, or
/// saved passwords); handling of OAuth expiration; and support for multiple authentication
/// domains for Connectors.
/// </summary>
public class PSShareFileClient
{
public string Path { get; set; }
public ShareFileClient Client { get; set; }
public AuthenticationDomain PrimaryDomain { get; set; }
public Dictionary<string, AuthenticationDomain> Domains { get; set; }
public PSShareFileClient(string path, AuthenticationDomain domain = null)
{
Path = path;
Domains = new Dictionary<string, AuthenticationDomain>();
if (domain != null)
{
Domains.Add(domain.Uri, domain);
PrimaryDomain = domain;
}
}
public Session GetSession()
{
WebpopInternetExplorerMode.SetUseCurrentIERegistryKey();
if (PrimaryDomain != null)
{
// Add username/password credentials if domain is ShareFile; Account is known; and credentials were provided
if (PrimaryDomain.IsShareFileUri
&& PrimaryDomain.Credential != null
&& PrimaryDomain.Account != null
&& !PrimaryDomain.Account.Equals("secure")
&& !PrimaryDomain.Account.Equals("g"))
{
AuthenticateUsernamePassword(PrimaryDomain.Account, PrimaryDomain.Domain, PrimaryDomain.Credential.UserName, PrimaryDomain.Credential.Password);
}
// Handle all other auth scenarios
if (Client == null) Client = CreateClient(PrimaryDomain);
return Client.Sessions.Get().Execute();
}
return null;
}
public AuthenticationDomain AuthenticateUsernamePassword(string domain)
{
var dialog = new BasicAuthDialog(domain);
var output = dialog.ShowDialog();
if (output == System.Windows.Forms.DialogResult.OK)
{
var authDomain = new AuthenticationDomain() { Uri = domain };
if (authDomain.Provider.Equals(Resources.ShareFileProvider) && authDomain.IsShareFileUri)
{
authDomain = AuthenticateUsernamePassword(authDomain.Account, authDomain.Domain, dialog.Username, dialog.Password);
}
else
{
authDomain.Credential = new NetworkCredential(dialog.Username, dialog.Password);
if (Client == null) Client = CreateClient(authDomain);
Client.AddCredentials(new Uri(authDomain.Uri), "basic", authDomain.Credential);
}
if (Domains.ContainsKey(authDomain.Uri)) Domains.Remove(authDomain.Uri);
Domains.Add(authDomain.Uri, authDomain);
Save();
return authDomain;
}
return null;
}
public AuthenticationDomain AuthenticateUsernamePassword(string account, string domain, string username, SecureString securePassword)
{
string password = null;
IntPtr bstr = Marshal.SecureStringToBSTR(securePassword);
try
{
password = Marshal.PtrToStringBSTR(bstr);
}
finally
{
Marshal.FreeBSTR(bstr);
}
return AuthenticateUsernamePassword(account, domain, username, password);
}
public AuthenticationDomain AuthenticateUsernamePassword(string account, string domain, string username, string password)
{
AuthenticationDomain authDomain = null;
var accountAndDomain = string.IsNullOrEmpty(account) ? domain : string.Format("{0}.{1}", account, domain);
var uri = string.Format("https://{0}/oauth/token", accountAndDomain);
var request = HttpWebRequest.CreateHttp(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var body = new StreamWriter(request.GetRequestStream()))
{
body.Write(
Uri.EscapeUriString(string.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}",
Resources.ClientId,
Resources.ClientSecret,
username,
password)));
}
var response = (HttpWebResponse)request.GetResponse();
using (var body = new StreamReader(response.GetResponseStream()))
{
var jobj = JsonConvert.DeserializeObject<JObject>(body.ReadToEnd());
authDomain = new AuthenticationDomain();
authDomain.OAuthToken = jobj["access_token"] != null ? jobj["access_token"].ToString() : null;
uri = string.Format("https://{0}/{1}/{2}", accountAndDomain, Resources.ShareFileProvider, Resources.DefaultApiVersion);
authDomain.Uri = uri;
if (Domains.ContainsKey(authDomain.Uri)) Domains.Remove(authDomain.Uri);
Domains.Add(authDomain.Uri, authDomain);
if (Client == null) Client = CreateClient(authDomain);
var session = Client.Sessions.Get().Execute();
authDomain.AuthID = session.Id;
this.Save();
}
return authDomain;
}
public AuthenticationDomain AuthenticateOAuth(AuthenticationDomain domain)
{
var webDialogThread = new WebDialogThread(this, domain);
var t = new Thread(webDialogThread.Run);
t.SetApartmentState(ApartmentState.STA);
t.Start();
var ResultDomain = webDialogThread.Result;
if (ResultDomain != null && ResultDomain.OAuthToken != null)
{
if (Domains.ContainsKey(ResultDomain.Uri)) Domains.Remove(ResultDomain.Uri);
Domains.Add(ResultDomain.Uri, ResultDomain);
PrimaryDomain = ResultDomain;
Client.AddOAuthCredentials(new Uri(ResultDomain.Uri), ResultDomain.OAuthToken);
Client.BaseUri = new Uri(ResultDomain.Uri);
this.Save();
}
else throw new Exception("Invalid Authentication");
return ResultDomain;
}
public AuthenticationDomain AuthenticateForms(AuthenticationDomain domain, Uri formUri, Uri tokenUri, string root)
{
var webDialogThread = new WebDialogThread(this, domain, formUri, tokenUri, root);
var t = new Thread(webDialogThread.Run);
t.SetApartmentState(ApartmentState.STA);
t.Start();
var ResultDomain = webDialogThread.Result;
if (ResultDomain != null && (ResultDomain.OAuthToken != null || ResultDomain.AuthID != null))
{
if (Domains.ContainsKey(ResultDomain.Uri)) Domains.Remove(ResultDomain.Uri);
Domains.Add(ResultDomain.Uri, ResultDomain);
Client.AddAuthenticationId(new Uri(ResultDomain.Uri), ResultDomain.AuthID);
Client.BaseUri = new Uri(ResultDomain.Uri);
this.Save();
}
else throw new Exception("Invalid Authentication");
return ResultDomain;
}
/// <summary>
/// Callback method for Redirection events received by the ShareFile Client SDK
/// </summary>
/// <param name="requestMessage"></param>
/// <param name="redirection"></param>
/// <returns></returns>
private EventHandlerResponse OnDomainChange(HttpRequestMessage requestMessage, Redirection redirection)
{
// Check if we already have a session on the target
bool hasSession = true;
if (redirection.SessionCheck)
{
hasSession = false;
try
{
var query = new ShareFile.Api.Client.Requests.Query<Session>(Client);
query.Uri(new Uri(redirection.SessionUri.ToString() + "?root=" + redirection.Root));
var session = query.Execute();
hasSession = true;
}
catch (Exception)
{ }
}
// If we're not authenticated, we have to authenticate now using Forms
if (!hasSession && redirection.FormsUri != null)
{
var authDomain = new AuthenticationDomain() { Uri = redirection.SessionUri.ToString() };
authDomain = this.AuthenticateForms(authDomain,
new Uri(string.Format("{0}?root={1}&redirect_url={2}", redirection.FormsUri, redirection.Root, Uri.EscapeUriString(Resources.RedirectURL))),
redirection.TokenUri,
redirection.Root);
if (authDomain.OAuthToken == null)
{
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Throw };
}
}
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Redirect, Redirection = redirection };
}
/// <summary>
/// Callback method for exceptions received from the ShareFile SDK Client.
/// </summary>
/// <remarks>
/// This method handles authorization exceptions raised by the ShareFile Client, allowing this Powershell
/// provider to navigate multiple authentication domains.
/// </remarks>
/// <param name="response">Http response message that raised the exception</param>
/// <param name="retryCount">Number of retries on the same SDK request</param>
/// <returns>An EventHandlerResponse indicating the action the SDK should take - retry, throw or redirect</returns>
private EventHandlerResponse OnException(HttpResponseMessage response, int retryCount)
{
if (retryCount > int.Parse(Resources.MaxExceptionRetry))
{
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Throw };
}
AuthenticationDomain authDomain = null;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// Check cached credentials for this API domain
foreach (var id in Domains.Keys)
{
if (response.RequestMessage.RequestUri.Host.EndsWith(new Uri(Domains[id].Uri).Host))
{
authDomain = Domains[id];
if (!string.IsNullOrEmpty(Domains[id].OAuthRefreshToken))
{
var token = GetTokenResponse(
"POST",
string.Format("https://{0}.{1}/oauth/token", Domains[id].Account, Domains[id].Domain),
string.Format("grant_type=refresh_token&redirect_uri={0}&refresh_token={1}&client_id={2}&client_secret={3}",
Resources.RedirectURL, Domains[id].OAuthRefreshToken, Resources.ClientId, Resources.ClientSecret));
Domains[id].OAuthToken = token.AccessToken;
Domains[id].OAuthRefreshToken = token.RefreshToken;
Client.AddOAuthCredentials(new Uri(Domains[id].Uri), token.AccessToken);
Save();
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Retry };
}
else if (Domains[id].Credential != null && retryCount <= 1)
{
if (Domains[id].Provider.Equals(Resources.ShareFileProvider) && Domains[id].IsShareFileUri)
{
Domains[id] = AuthenticateUsernamePassword(Domains[id].Account, Domains[id].Domain, Domains[id].Credential.UserName, Domains[id].Credential.Password);
}
else
{
Client.AddCredentials(new Uri(Domains[id].Uri), "basic", Domains[id].Credential);
}
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Retry };
}
}
}
// No cached, or bad cached credentials for this domain request
// Check the headers for authentication challenges
if (authDomain == null) authDomain = new AuthenticationDomain() { Uri = response.RequestMessage.RequestUri.ToString() };
IEnumerable<string> values = null;
if (response.Headers.TryGetValues("WWW-Authenticate", out values))
{
foreach (var authMethodString in values)
{
var authMethodParts = authMethodString.Split(' ');
var authMethod = authMethodParts[0].Trim();
if (authMethod.Equals("Bearer"))
{
authDomain = this.AuthenticateOAuth(authDomain);
return new EventHandlerResponse() { Action = authDomain != null ? EventHandlerResponseAction.Retry : EventHandlerResponseAction.Throw };
}
else if (retryCount == 0 && (authMethod.Equals("NTLM") || authMethod.Equals("Kerberos")))
{
// if retryCount > 0, then Network Credentials failed at least once;
// causes fallback to username/password
Client.AddCredentials(new Uri(authDomain.Uri), authMethod, CredentialCache.DefaultNetworkCredentials);
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Retry };
}
else if (authMethod.Equals("Basic") || authMethod.Equals("NTLM"))
{
authDomain = this.AuthenticateUsernamePassword(authDomain.Uri);
return new EventHandlerResponse() { Action = authDomain != null ? EventHandlerResponseAction.Retry : EventHandlerResponseAction.Throw };
}
}
}
}
return new EventHandlerResponse() { Action = EventHandlerResponseAction.Throw };
}
public void Load()
{
using (var reader = new StreamReader(new FileStream(Path, FileMode.Open)))
{
AuthenticationDomain domain = null;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != null)
{
line = line.Trim();
if (line.StartsWith("["))
{
if (domain != null)
{
Domains.Add(domain.Id, domain);
}
domain = new AuthenticationDomain();
domain.Id = line.Substring(1, line.IndexOf(']') - 1);
}
else if (line.StartsWith("Provider")) domain.Provider = line.Split('=')[1].Trim();
else if (line.StartsWith("IsDefault")) domain.IsDefault = bool.Parse(line.Split('=')[1].Trim());
else if (line.StartsWith("Uri")) domain.Uri = line.Split('=')[1].Trim();
else if (line.StartsWith("AccessToken")) domain.OAuthToken = line.Split('=')[1].Trim();
else if (line.StartsWith("RefreshToken")) domain.OAuthRefreshToken = line.Split('=')[1].Trim();
else if (line.StartsWith("Account")) domain.Account = line.Split('=')[1].Trim();
else if (line.StartsWith("Domain")) domain.Domain = line.Split('=')[1].Trim();
else if (line.StartsWith("ApiVersion")) domain.ApiVersion = line.Split('=')[1].Trim();
else if (line.StartsWith("NetworkCredential"))
{
string cred = line.Split('=')[1].Trim();
string username = cred.Split(',')[0].Trim();
string password = cred.Split(',')[1].Trim();
domain.Credential = new NetworkCredential(username, password);
}
}
}
if (domain != null)
{
Domains.Add(domain.Id, domain);
}
}
// Load the default auth domain
foreach (var id in Domains.Keys)
{
if (Domains[id].IsDefault)
{
Client = CreateClient(Domains[id]);
PrimaryDomain = Domains[id];
if (!string.IsNullOrEmpty(Domains[id].OAuthToken))
{
Client.AddOAuthCredentials(new Uri(Domains[id].Uri), Domains[id].OAuthToken);
}
break;
}
}
}
public void Save()
{
if (Path != null)
{
if (Path.IndexOf('.') < 0) Path += ".sfps";
using (var writer = new StreamWriter(new FileStream(Path, FileMode.Create)))
{
foreach (var id in Domains.Keys)
{
if (Domains[id].Domain != null && !Domains[id].Domain.ToLower().Equals("secure"))
{
writer.WriteLine(string.Format("[{0}]", id));
writer.WriteLine("Provider=" + Domains[id].Provider);
writer.WriteLine("IsDefault=" + (Client.BaseUri.ToString().ToLower() == Domains[id].Uri.ToLower()));
writer.WriteLine("Version=" + Resources.Version);
writer.WriteLine("Uri=" + Domains[id].Uri ?? "");
writer.WriteLine("AccessToken=" + Domains[id].OAuthToken ?? "");
writer.WriteLine("RefreshToken=" + Domains[id].OAuthRefreshToken ?? "");
writer.WriteLine("Account=" + Domains[id].Account ?? "");
writer.WriteLine("Domain=" + Domains[id].Domain ?? "");
writer.WriteLine("ApiVersion=" + Domains[id].ApiVersion ?? "");
if (Domains[id].Credential != null)
{
writer.WriteLine("NetworkCredential=" + Domains[id].Credential.UserName + ", " + Domains[id].Credential.Password ?? "");
}
}
}
}
}
}
private ShareFileClient CreateClient(AuthenticationDomain domain)
{
Configuration config = Configuration.Default();
config.HttpTimeout = 200000;
var client = new ShareFileClient(domain.Uri, config);
if (domain.OAuthToken != null)
{
client.AddOAuthCredentials(new Uri(domain.Uri), domain.OAuthToken);
}
client.AddExceptionHandler(OnException);
client.AddChangeDomainHandler(OnDomainChange);
return client;
}
private OAuthToken GetTokenResponse(string method, string uri, string body)
{
var request = HttpWebRequest.CreateHttp(uri);
request.Method = method;
if (body != null)
{
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(body);
}
}
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return JsonConvert.DeserializeObject<OAuthToken>(reader.ReadToEnd());
}
}
private class WebDialogThread
{
public AuthenticationDomain Result
{
get
{
_waitHandle.WaitOne();
return _result;
}
}
private AuthenticationDomain _result = null;
private AutoResetEvent _waitHandle = new AutoResetEvent(false);
private PSShareFileClient _psClient;
private AuthenticationDomain _requestDomain;
private Uri _formUri;
private Uri _tokenUri;
private string _root;
public WebDialogThread(PSShareFileClient psClient, AuthenticationDomain domain, Uri formUri = null, Uri tokenUri = null, string root = null)
{
_psClient = psClient;
_requestDomain = domain;
_formUri = formUri;
_tokenUri = tokenUri;
_root = root;
}
public void Run()
{
AuthenticationDomain authDomain = null;
var browser = new OAuthAuthenticationForm();
Uri requestUri = null;
if (_formUri == null)
{
requestUri = new Uri(string.Format("https://{0}.{1}/oauth/authorize?response_type=code&client_id={2}{3}{4}&redirect_uri={5}",
_requestDomain.Account ?? "secure",
_requestDomain.Domain,
Resources.ClientId,
_requestDomain.Account != null && !_requestDomain.Account.Equals("secure") ? "&subdomain=" + _requestDomain.Account : "",
_requestDomain.Username != null ? "&username=" + Uri.EscapeUriString(_requestDomain.Username) : "",
Uri.EscapeUriString(Resources.RedirectURL)));
browser.AddUrlEventHandler(Resources.RedirectURL, uri =>
{
try
{
// return is <redirect_url>/oauth/authorize#access_token=...&subdomain=...&apicp=...&appcp=...
var query = new Dictionary<string, string>();
OAuthToken token = null;
if (!string.IsNullOrEmpty(uri.Query))
{
foreach (var kvp in uri.Query.Substring(1).Split('&'))
{
var kvpSplit = kvp.Split('=');
if (kvpSplit.Length == 2) query.Add(kvpSplit[0], kvpSplit[1]);
}
var subdomain = query["subdomain"];
var apiCP = query["apicp"];
var appCP = query["appcp"];
token = _psClient.GetTokenResponse(
"POST",
string.Format("https://{0}.{1}/oauth/token", subdomain, appCP),
string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&requirev3=true", query["code"],
Resources.ClientId, Resources.ClientSecret));
authDomain = new AuthenticationDomain();
authDomain.OAuthToken = token.AccessToken;
authDomain.OAuthRefreshToken = token.RefreshToken;
authDomain.Account = token.Subdomain;
authDomain.Provider = Resources.ShareFileProvider;
authDomain.Domain = token.ApiCP;
authDomain.ApiVersion = Resources.DefaultApiVersion;
return true;
}
else return false;
}
catch (Exception)
{
return true;
}
});
}
else
{
requestUri = _formUri;
browser.AddUrlEventHandler(Resources.RedirectURL, uri =>
{
var query = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(uri.Query))
{
foreach (var kvp in uri.Query.Substring(1).Split('&'))
{
var kvpSplit = kvp.Split('=');
if (kvpSplit.Length == 2) query.Add(kvpSplit[0], kvpSplit[1]);
}
var request = HttpWebRequest.CreateHttp(_tokenUri.ToString() + string.Format("?root={0}&code={1}", _root, query["code"]));
var response = (HttpWebResponse)request.GetResponse();
Session session = null;
using (var reader = new StreamReader(response.GetResponseStream()))
{
session = JsonConvert.DeserializeObject<Session>(reader.ReadToEnd());
}
authDomain = new AuthenticationDomain();
authDomain.AuthID = session.Id;
authDomain.Uri = uri.ToString();
return true;
}
else return false;
});
}
browser.Navigate(requestUri);
_result = authDomain;
_waitHandle.Set();
}
}
}
}
| 50.510909 | 183 | 0.501602 |
[
"MIT"
] |
citrix/ShareFile-PowerShell
|
ShareFileSnapIn/PSShareFileClient.cs
| 27,783 |
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: EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type EntitlementManagementConnectedOrganizationsCollectionRequest.
/// </summary>
public partial class EntitlementManagementConnectedOrganizationsCollectionRequest : BaseRequest, IEntitlementManagementConnectedOrganizationsCollectionRequest
{
/// <summary>
/// Constructs a new EntitlementManagementConnectedOrganizationsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public EntitlementManagementConnectedOrganizationsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified ConnectedOrganization to the collection via POST.
/// </summary>
/// <param name="connectedOrganization">The ConnectedOrganization to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ConnectedOrganization.</returns>
public System.Threading.Tasks.Task<ConnectedOrganization> AddAsync(ConnectedOrganization connectedOrganization, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsync<ConnectedOrganization>(connectedOrganization, cancellationToken);
}
/// <summary>
/// Adds the specified ConnectedOrganization to the collection via POST and returns a <see cref="GraphResponse{ConnectedOrganization}"/> object of the request.
/// </summary>
/// <param name="connectedOrganization">The ConnectedOrganization to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{ConnectedOrganization}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<ConnectedOrganization>> AddResponseAsync(ConnectedOrganization connectedOrganization, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<ConnectedOrganization>(connectedOrganization, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IEntitlementManagementConnectedOrganizationsCollectionPage> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var response = await this.SendAsync<EntitlementManagementConnectedOrganizationsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response?.Value?.CurrentPage != null)
{
response.Value.InitializeNextPageRequest(this.Client, response.NextLink);
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
return response.Value;
}
return null;
}
/// <summary>
/// Gets the collection page and returns a <see cref="GraphResponse{EntitlementManagementConnectedOrganizationsCollectionResponse}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{EntitlementManagementConnectedOrganizationsCollectionResponse}"/> object.</returns>
public System.Threading.Tasks.Task<GraphResponse<EntitlementManagementConnectedOrganizationsCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<EntitlementManagementConnectedOrganizationsCollectionResponse>(null, 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>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Expand(Expression<Func<ConnectedOrganization, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Select(Expression<Func<ConnectedOrganization, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IEntitlementManagementConnectedOrganizationsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| 47.009569 | 189 | 0.635318 |
[
"MIT"
] |
ScriptBox21/msgraph-sdk-dotnet
|
src/Microsoft.Graph/Generated/requests/EntitlementManagementConnectedOrganizationsCollectionRequest.cs
| 9,825 |
C#
|
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host;
using Roslynator.CSharp;
namespace Roslynator.CSharp
{
[Export(typeof(ILanguageService))]
[ExportMetadata("Language", LanguageNames.CSharp)]
[ExportMetadata("ServiceType", "Roslynator.ISyntaxFactsService")]
internal sealed class CSharpSyntaxFactsService : ISyntaxFactsService
{
public static CSharpSyntaxFactsService Instance { get; } = new CSharpSyntaxFactsService();
public string SingleLineCommentStart => "//";
public bool IsEndOfLineTrivia(SyntaxTrivia trivia)
{
return trivia.IsKind(SyntaxKind.EndOfLineTrivia);
}
public bool IsComment(SyntaxTrivia trivia)
{
return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia);
}
public bool IsSingleLineComment(SyntaxTrivia trivia)
{
return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia);
}
public bool IsWhitespaceTrivia(SyntaxTrivia trivia)
{
return trivia.IsKind(SyntaxKind.WhitespaceTrivia);
}
public SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0)
{
return SyntaxFactory.ParseLeadingTrivia(text, offset);
}
public SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0)
{
return SyntaxFactory.ParseTrailingTrivia(text, offset);
}
public bool BeginsWithAutoGeneratedComment(SyntaxNode root)
{
return GeneratedCodeUtility.BeginsWithAutoGeneratedComment(
root,
f => f.IsKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia));
}
public bool AreEquivalent(SyntaxTree oldTree, SyntaxTree newTree)
{
return SyntaxFactory.AreEquivalent(oldTree, newTree, topLevel: false);
}
}
}
| 34.412698 | 160 | 0.686808 |
[
"Apache-2.0"
] |
ADIX7/Roslynator
|
src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs
| 2,170 |
C#
|
/*Copyright 2015 Esri
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.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("MyCustomJobTab")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ESRI")]
[assembly: AssemblyProduct("MyCustomJobTab")]
[assembly: AssemblyCopyright("Copyright © ESRI 2008")]
[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("235d33c9-68d9-46ab-aea7-f6bcc853e5a9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.875 | 84 | 0.763323 |
[
"Apache-2.0"
] |
AngelVDelgadillo/workflowmanager-samples
|
CustomJobTab/CSharp/Properties/AssemblyInfo.cs
| 1,917 |
C#
|
using SHS.Domain.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace SHS.Service.UsersService.Dto
{
public class QueryUserFilter : QueryPageInput
{
public string Name { get; set; }
public string Phone { get; set; }
}
}
| 20.785714 | 49 | 0.694158 |
[
"MIT"
] |
Coding-Yu/SHS.CMS
|
Service/SHS.Service/UsersService/Dto/QueryUserFilter.cs
| 293 |
C#
|
using MediatR;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using NoDaysOffApp.Features.Core;
namespace NoDaysOffApp.Features.CompletedScheduledExercises
{
[Authorize]
[RoutePrefix("api/completedScheduledExercises")]
public class CompletedScheduledExerciseController : BaseApiController
{
public CompletedScheduledExerciseController(IMediator mediator)
:base(mediator) { }
[Route("add")]
[HttpPost]
[ResponseType(typeof(AddOrUpdateCompletedScheduledExerciseCommand.Response))]
public async Task<IHttpActionResult> Add(AddOrUpdateCompletedScheduledExerciseCommand.Request request) => Ok(await Send(request));
[Route("update")]
[HttpPut]
[ResponseType(typeof(AddOrUpdateCompletedScheduledExerciseCommand.Response))]
public async Task<IHttpActionResult> Update(AddOrUpdateCompletedScheduledExerciseCommand.Request request) => Ok(await Send(request));
[Route("get")]
[AllowAnonymous]
[HttpGet]
[ResponseType(typeof(GetCompletedScheduledExercisesQuery.Response))]
public async Task<IHttpActionResult> Get() => Ok(await Send(new GetCompletedScheduledExercisesQuery.Request()));
[Route("getById")]
[HttpGet]
[ResponseType(typeof(GetCompletedScheduledExerciseByIdQuery.Response))]
public async Task<IHttpActionResult> GetById([FromUri]GetCompletedScheduledExerciseByIdQuery.Request request) => Ok(await Send(request));
[Route("remove")]
[HttpDelete]
[ResponseType(typeof(RemoveCompletedScheduledExerciseCommand.Response))]
public async Task<IHttpActionResult> Remove([FromUri]RemoveCompletedScheduledExerciseCommand.Request request) => Ok(await Send(request));
}
}
| 40.434783 | 145 | 0.733333 |
[
"MIT"
] |
QuinntyneBrown/no-days-off-app
|
Features/CompletedScheduledExercises/CompletedScheduledExercisesController.cs
| 1,860 |
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using BuildXL.Cache.ContentStore.Distributed.NuCache.CopyScheduling;
using BuildXL.Cache.ContentStore.Grpc;
using BuildXL.Cache.ContentStore.Interfaces.Distributed;
using BuildXL.Cache.ContentStore.Interfaces.Logging;
using BuildXL.Cache.ContentStore.Interfaces.Utils;
using ContentStore.Grpc;
#nullable disable
namespace BuildXL.Cache.Host.Configuration
{
/// <summary>
/// Feature flag settings for an L2 Content Cache.
/// </summary>
[DataContract]
public class DistributedContentSettings
{
private const int DefaultMaxConcurrentCopyOperations = 512;
internal static readonly int[] DefaultRetryIntervalForCopiesMs =
new int[]
{
// retry the first 2 times quickly.
20,
200,
// then back-off exponentially.
1000,
5000,
10000,
30000,
// Borrowed from Empirical CacheV2 determined to be appropriate for general remote server restarts.
60000,
120000,
};
public static DistributedContentSettings CreateDisabled()
{
return new DistributedContentSettings
{
IsDistributedContentEnabled = false,
};
}
public static DistributedContentSettings CreateEnabled()
{
return new DistributedContentSettings()
{
IsDistributedContentEnabled = true,
};
}
/// <summary>
/// Settings for running deployment launcher
/// </summary>
[DataMember]
public LauncherSettings LauncherSettings { get; set; } = null;
[DataMember]
public LogManagerConfiguration LogManager { get; set; } = null;
/// <summary>
/// Feature flag to turn on distributed content tracking (L2/datacenter cache).
/// </summary>
[DataMember]
public bool IsDistributedContentEnabled { get; set; }
/// <summary>
/// Grpc port for backing cache service instance
/// </summary>
[DataMember]
public int? BackingGrpcPort { get; set; } = null;
/// <summary>
/// Grpc port for backing cache service instance
/// </summary>
[DataMember]
public string BackingScenario { get; set; } = null;
/// <summary>
/// The amount of time for nagling GetBulk (locations) for proactive copy operations
/// </summary>
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double ProactiveCopyGetBulkIntervalSeconds { get; set; } = 10;
/// <summary>
/// The size of nagle batch for proactive copy get bulk
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ProactiveCopyGetBulkBatchSize { get; set; } = 20;
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int ProactiveCopyMaxRetries { get; set; } = 0;
/// <summary>
/// Configurable Keyspace Prefixes
/// </summary>
[DataMember]
public string KeySpacePrefix { get; set; } = "CBPrefix";
/// <summary>
/// Name of the EventHub instance to connect to.
/// </summary>
[DataMember]
public string EventHubName { get; set; } = "eventhub";
/// <summary>
/// Name of the EventHub instance's consumer group name.
/// </summary>
[DataMember]
public string EventHubConsumerGroupName { get; set; } = "$Default";
/// <summary>
/// Adds suffix to resource names to allow instances in different ring to
/// share the same resource without conflicts. In particular this will add the
/// ring suffix to Azure blob container name and Redis keyspace (which is included
/// in event hub epoch).
/// </summary>
[DataMember]
public bool UseRingIsolation { get; set; } = false;
// Redis-related configuration
/// <summary>
/// TTL to be set in Redis for memoization entries.
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int RedisMemoizationExpiryTimeMinutes { get; set; } = 1500;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int RedisBatchPageSize { get; set; } = 500;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RedisConnectionErrorLimit { get; set; }
#region Redis Connection Multiplexer Configuration
[DataMember]
public bool? UseRedisPreventThreadTheftFeature { get; set; }
[DataMember]
[Validation.Enum(typeof(Severity), allowNull: true)]
public string RedisInternalLogSeverity { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RedisConfigCheckInSeconds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RedisKeepAliveInSeconds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RedisConnectionTimeoutInSeconds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RedisMultiplexerOperationTimeoutTimeoutInSeconds { get; set; }
#endregion Redis Connection Multiplexer Configuration
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RedisMemoizationDatabaseOperationTimeoutInSeconds { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RedisMemoizationSlowOperationCancellationTimeoutInSeconds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RedisReconnectionLimitBeforeServiceRestart { get; set; }
[DataMember]
public double? DefaultRedisOperationTimeoutInSeconds { get; set; }
[DataMember]
public TimeSpan? MinRedisReconnectInterval { get; set; }
[DataMember]
public bool? CancelBatchWhenMultiplexerIsClosed { get; set; }
[DataMember]
public bool? TreatObjectDisposedExceptionAsTransient { get; set; }
[DataMember]
[Validation.Range(-1, int.MaxValue)]
public int? RedisGetBlobTimeoutMilliseconds { get; set; }
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int? RedisGetCheckpointStateTimeoutInSeconds { get; set; }
// Redis retry configuration
[DataMember]
[Validation.Range(0, int.MaxValue, minInclusive: false)]
public int? RedisFixedIntervalRetryCount { get; set; }
// Just setting this value is enough to configure a custom exponential back-off policy with default min/max/interval.
[DataMember]
[Validation.Range(0, int.MaxValue, minInclusive: false)]
public int? RedisExponentialBackoffRetryCount { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RedisExponentialBackoffMinIntervalInSeconds { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RedisExponentialBackoffMaxIntervalInSeconds { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RedisExponentialBackoffDeltaIntervalInSeconds { get; set; }
// TODO: file a work item to remove the flag!
[DataMember]
public bool CheckLocalFiles { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int MaxShutdownDurationInMinutes { get; set; } = 30;
/// <summary>
/// If true, then content store will start a self-check to validate that the content in cache is valid at startup.
/// </summary>
[DataMember]
public bool StartSelfCheckAtStartup { get; set; } = false;
/// <summary>
/// An interval between self checks performed by a content store to make sure that all the data on disk matches it's hashes.
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int SelfCheckFrequencyInMinutes { get; set; } = (int)TimeSpan.FromDays(1).TotalMinutes;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? SelfCheckProgressReportingIntervalInMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? SelfCheckDelayInMilliseconds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? SelfCheckDefaultHddDelayInMilliseconds { get; set; }
/// <summary>
/// An epoch used for reseting self check of a content directory.
/// </summary>
[DataMember]
public string SelfCheckEpoch { get; set; } = "E0";
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? ReserveSpaceTimeoutInMinutes { get; set; }
[DataMember]
public bool IsRepairHandlingEnabled { get; set; } = false;
[DataMember]
public bool UseMdmCounters { get; set; } = true;
[DataMember]
public bool UseContextualEntryDatabaseOperationLogging { get; set; } = false;
[DataMember]
public bool TraceTouches { get; set; } = true;
[DataMember]
public bool? TraceNoStateChangeDatabaseOperations { get; set; }
[DataMember]
public bool LogReconciliationHashes { get; set; } = false;
/// <summary>
/// The TTL of blobs in Redis. Setting to 0 will disable blobs.
/// </summary>
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int BlobExpiryTimeMinutes { get; set; } = 0;
/// <summary>
/// Max size of blobs in Redis. Setting to 0 will disable blobs.
/// </summary>
[DataMember]
[Validation.Range(0, long.MaxValue)]
public long MaxBlobSize { get; set; } = 1024 * 4;
/// <summary>
/// Max capacity that blobs can occupy in Redis. Setting to 0 will disable blobs.
/// </summary>
[DataMember]
[Validation.Range(0, long.MaxValue)]
public long MaxBlobCapacity { get; set; } = 1024 * 1024 * 1024;
/// <summary>
/// The span of time that will delimit the operation count limit for blob operations.
/// </summary>
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int? BlobOperationLimitSpanSeconds { get; set; }
/// <summary>
/// The amount of blob operations that we allow to go to Redis in a given period of time.
/// </summary>
[DataMember]
[Validation.Range(0, int.MaxValue)]
public long? BlobOperationLimitCount { get; set; }
/// <summary>
/// Amount of entries to compute evictability metric for in a single pass. The larger this is, the faster the
/// candidate pool fills up, but also the slower it is to produce a candidate. Helps control how fast we need
/// to produce candidates.
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int EvictionWindowSize { get; set; } = 500;
/// <summary>
/// Amount of entries to compute evictability metric for before determining eviction order. The larger this is,
/// the slower and more resources eviction takes, but also the more accurate it becomes.
/// </summary>
/// <remarks>
/// Two pools are kept in memory at the same time, so we effectively keep double the amount of data in memory.
/// </remarks>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int EvictionPoolSize { get; set; } = 5000;
/// <summary>
/// A candidate must have an age older than this amount, or else it won't be evicted.
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? EvictionMinAgeMinutes { get; set; }
/// <summary>
/// Fraction of the pool considered trusted to be in the accurate order.
/// </summary>
[DataMember]
[Validation.Range(0, 1, maxInclusive: false)]
public float EvictionRemovalFraction { get; set; } = 0.015355f;
/// <summary>
/// Fraction of the pool that can be trusted to be spurious at each iteration
/// </summary>
[DataMember]
[Validation.Range(0, 1)]
public float EvictionDiscardFraction { get; set; } = 0;
/// <summary>
/// Configures whether to use full eviction sort logic
/// </summary>
[DataMember]
public bool UseFullEvictionSort { get; set; } = false;
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double? ThrottledEvictionIntervalMinutes { get; set; }
/// <summary>
/// Configures whether ages of content are updated when sorting during eviction
/// </summary>
[DataMember]
public bool UpdateStaleLocalLastAccessTimes { get; set; } = false;
/// <summary>
/// Configures whether to use new tiered eviction logic or not.
/// </summary>
[DataMember]
public bool UseTieredDistributedEviction { get; set; } = false;
[DataMember]
public bool PrioritizeDesignatedLocationsOnCopies { get; set; } = false;
[DataMember]
public bool DeprioritizeMasterOnCopies { get; set; } = false;
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int CopyAttemptsWithRestrictedReplicas { get; set; } = 0;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int RestrictedCopyReplicaCount { get; set; } = 3;
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double PeriodicCopyTracingIntervalMinutes { get; set; } = 5.0;
/// <summary>
/// After the first raided redis instance completes, the second instance is given a window of time to complete before the retries are cancelled.
/// Default to always wait for both instances to complete.
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RetryWindowSeconds { get; set; }
/// <summary>
/// If this variable is set we perform periodic logging to a file, indicating CaSaaS is still running and accepting operations.
/// We then print the duration CaSaaS was just down, in the log message stating service has started.
/// Default with the variable being null, no periodic logging will occur, and CaSaaS start log message does not include duration of last down time.
/// </summary>
[DataMember]
public int? ServiceRunningLogInSeconds { get; set; }
/// <summary>
/// Delays for retries for file copies
/// </summary>
// NOTE: This must be null so that System.Text.Json serialization does not try to add to the
// collection which will fail because its an array and add is not supported. This may be fixed in
// newer versions of System.Text.Json. Also, changing to IReadOnlyList<int> fails DataContractSerialization
// which is needed by QuickBuild.
[DataMember]
public int[] RetryIntervalForCopiesMs { get; set; }
public IReadOnlyList<TimeSpan> RetryIntervalForCopies => (RetryIntervalForCopiesMs ?? DefaultRetryIntervalForCopiesMs).Select(ms => TimeSpan.FromMilliseconds(ms)).ToList();
/// <summary>
/// Controls the maximum total number of copy retry attempts
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int MaxRetryCount { get; set; } = 32;
[DataMember]
public bool UseUnsafeByteStringConstruction { get; set; } = false;
[DataMember]
public ColdStorageSettings ColdStorageSettings { get; set; }
#region DistributedContentCopier
[DataMember]
[Validation.Range(0, long.MaxValue)]
public long? GrpcCopyCompressionSizeThreshold { get; set; }
[DataMember]
[Validation.Enum(typeof(CopyCompression), allowNull: true)]
public string GrpcCopyCompressionAlgorithm { get; set; }
[DataMember]
public bool? UseInRingMachinesForCopies { get; set; }
[DataMember]
public bool? StoreBuildIdInCache { get; set; }
#endregion
#region Grpc File Copier
[DataMember]
public string GrpcFileCopierGrpcCopyClientInvalidationPolicy { get; set; }
#endregion
#region Grpc Copy Client Cache
[DataMember]
[Validation.Range(0, 2)]
public int? GrpcCopyClientCacheResourcePoolVersion { get; set; }
/// <summary>
/// Upper bound on number of cached GRPC clients.
/// </summary>
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MaxGrpcClientCount { get; set; }
/// <summary>
/// Maximum cached age for GRPC clients.
/// </summary>
[DataMember]
[Validation.Range(1, double.MaxValue)]
public double? MaxGrpcClientAgeMinutes { get; set; }
[DataMember]
[Validation.Range(1, double.MaxValue)]
public double? GrpcCopyClientCacheGarbageCollectionPeriodMinutes { get; set; }
[DataMember]
public bool? GrpcCopyClientCacheEnableInstanceInvalidation { get; set; }
#endregion
#region Grpc Copy Client
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int? GrpcCopyClientBufferSizeBytes { get; set; }
[DataMember]
public bool? GrpcCopyClientConnectOnStartup { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double? TimeToFirstByteTimeoutInSeconds { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double? GrpcCopyClientDisconnectionTimeoutSeconds { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double? GrpcCopyClientConnectionTimeoutSeconds { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double? GrpcCopyClientOperationDeadlineSeconds { get; set; }
[DataMember]
public bool? GrpcCopyClientPropagateCallingMachineName { get; set; }
/// <remarks>
/// It is OK to embed serializable types with no DataContract inside
/// </remarks>
[DataMember]
public GrpcCoreClientOptions GrpcCopyClientGrpcCoreClientOptions { get; set; }
#endregion
#region Distributed Eviction
/// <summary>
/// When set to true, we will shut down the quota keeper before hibernating sessions to prevent a race condition of evicting pinned content
/// </summary>
[DataMember]
public bool ShutdownEvictionBeforeHibernation { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? ReplicaCreditInMinutes { get; set; } = 180;
#endregion
#region Bandwidth Check
[DataMember]
public bool IsBandwidthCheckEnabled { get; set; } = true;
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? MinimumSpeedInMbPerSec { get; set; } = null;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int BandwidthCheckIntervalSeconds { get; set; } = 60;
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double MaxBandwidthLimit { get; set; } = double.MaxValue;
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double BandwidthLimitMultiplier { get; set; } = 1;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int HistoricalBandwidthRecordsStored { get; set; } = 64;
[DataMember]
public BandwidthConfiguration[] BandwidthConfigurations { get; set; }
#endregion
#region Pin Configuration
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? PinMinUnverifiedCount { get; set; }
/// <summary>
/// Obsolete: will be removed in favor of AsyncCopyOnPinThreshold.
/// </summary>
[DataMember]
public int? StartCopyWhenPinMinUnverifiedCountThreshold { get; set; }
[DataMember]
public int? AsyncCopyOnPinThreshold { get; set; }
[DataMember]
[Validation.Range(0, 1, minInclusive: false, maxInclusive: false)]
public double? MachineRisk { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MaxIOOperations { get; set; }
#endregion
#region Local Location Store
#region Distributed Central Storage
[DataMember]
public bool UseDistributedCentralStorage { get; set; } = false;
[DataMember]
public bool UseSelfCheckSettingsForDistributedCentralStorage { get; set; } = false;
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double MaxCentralStorageRetentionGb { get; set; } = 25;
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int CentralStoragePropagationDelaySeconds { get; set; } = 5;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int CentralStoragePropagationIterations { get; set; } = 3;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int CentralStorageMaxSimultaneousCopies { get; set; } = 10;
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? DistributedCentralStoragePeerToPeerCopyTimeoutSeconds { get; set; } = null;
[DataMember]
public bool ProactiveCopyCheckpointFiles { get; set; } = false;
[DataMember]
public bool InlineCheckpointProactiveCopies { get; set; } = false;
#endregion
[DataMember]
public bool IsMasterEligible { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ReconciliationCycleFrequencyMinutes { get; set; } = 30;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ReconciliationMaxCycleSize { get; set; } = 100_000;
[DataMember]
public int? ReconciliationMaxRemoveHashesCycleSize { get; set; } = null;
[DataMember]
[Validation.Range(0, 1)]
public double? ReconciliationMaxRemoveHashesAddPercentage { get; set; } = null;
[DataMember]
[Validation.Enum(typeof(ReconciliationMode))]
public string ReconcileMode { get; set; } = ReconciliationMode.Once.ToString();
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ReconciliationAddLimit { get; set; } = 100_000;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ReconciliationRemoveLimit { get; set; } = 1_000_000;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? ReconcileHashesLogLimit { get; set; }
[DataMember]
public bool IsContentLocationDatabaseEnabled { get; set; } = false;
[DataMember]
public bool IsMachineReputationEnabled { get; set; } = true;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? IncrementalCheckpointDegreeOfParallelism { get; set; }
[DataMember]
public bool? ShouldFilterInactiveMachinesInLocalLocationStore { get; set; }
#region Content Location Database
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? ContentLocationDatabaseGcIntervalMinutes { get; set; }
[DataMember]
public bool ContentLocationDatabaseLogsBackupEnabled { get; set; }
[DataMember]
public bool? ContentLocationDatabaseOpenReadOnly { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? ContentLocationDatabaseLogsBackupRetentionMinutes { get; set; }
[DataMember]
public string ContentLocationDatabaseCompression { get; set; }
[DataMember]
[Validation.Range(1, long.MaxValue)]
public long? ContentLocationDatabaseEnumerateSortedKeysFromStorageBufferSize { get; set; }
[DataMember]
[Validation.Range(1, long.MaxValue)]
public long? ContentLocationDatabaseEnumerateEntriesWithSortedKeysFromStorageBufferSize { get; set; }
[DataMember]
public bool? ContentLocationDatabaseGarbageCollectionConcurrent { get; set; }
[DataMember]
public string ContentLocationDatabaseMetadataGarbageCollectionStrategy { get; set; }
[DataMember]
[Validation.Range(1, double.MaxValue)]
public double? ContentLocationDatabaseMetadataGarbageCollectionMaximumSizeMb { get; set; }
[DataMember]
public bool? ContentLocationDatabaseUseReadOptionsWithSetTotalOrderSeekInDbEnumeration { get; set; }
[DataMember]
public bool? ContentLocationDatabaseUseReadOptionsWithSetTotalOrderSeekInGarbageCollection { get; set; }
[DataMember]
public bool? ContentLocationDatabaseMetadataGarbageCollectionLogEnabled { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MaximumNumberOfMetadataEntriesToStore { get; set; }
#endregion
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int SecretsRetrievalRetryCount { get; set; } = 5;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int SecretsRetrievalMinBackoffSeconds { get; set; } = 10;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int SecretsRetrievalMaxBackoffSeconds { get; set; } = 60;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int SecretsRetrievalDeltaBackoffSeconds { get; set; } = 10;
/// <summary>
/// Name of an environment variable which contains an EventHub connection string.
/// </summary>
[DataMember]
public string EventHubSecretName { get; set; }
/// <summary>
/// This is either:
/// * a connection string for EventHub (don't do this).
/// * OR a URI such that:
/// * The URI's scheme and host define the URI for the intended Event Hub Namespace. This
/// resembles "sb://yourEventHub.servicebus.windows.net".
/// * The URI's query string contains a value for the Event Hub Name. Note that this must
/// be an Event Hub within the Namespace defined at the beginning of the URI.
/// * The URI's query string contains a value for the Managed Identity Id. Note that this
/// is a guid which currently appears as the "Client ID" for the managed identity.
/// * In all, this should resemble "sb://yourEventHub.servicebus.windows.net/name=eventHubName&identity=identityId".
/// Use <see cref="ManagedIdentityUriHelper"/> to construct or parse this value.
/// </summary>
[DataMember]
public string EventHubConnectionString { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MaxEventProcessingConcurrency { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? EventBatchSize { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? EventProcessingMaxQueueSize { get; set; }
[DataMember]
public string[] AzureStorageSecretNames { get; set; }
[DataMember]
public string AzureStorageSecretName { get; set; }
[DataMember]
public bool AzureBlobStorageUseSasTokens { get; set; } = false;
[DataMember]
public string EventHubEpoch { get; set; } = ".LLS_V1.2";
[DataMember]
public string GlobalRedisSecretName { get; set; }
[DataMember]
public string SecondaryGlobalRedisSecretName { get; set; }
[DataMember]
public bool? MirrorClusterState { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? HeartbeatIntervalMinutes { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? CreateCheckpointIntervalMinutes { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RestoreCheckpointIntervalMinutes { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? ProactiveReplicationIntervalMinutes { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? RestoreCheckpointTimeoutMinutes { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue, minInclusive: false)]
public double? UpdateClusterStateIntervalSeconds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? SafeToLazilyUpdateMachineCountThreshold { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? CentralStorageOperationTimeoutInMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? LocationEntryExpiryMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? RestoreCheckpointAgeThresholdMinutes { get; set; }
[DataMember]
public bool? PacemakerEnabled { get; set; }
[DataMember]
public uint? PacemakerNumberOfBuckets { get; set; }
[DataMember]
public bool? PacemakerUseRandomIdentifier { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? TouchFrequencyMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? ReconcileCacheLifetimeMinutes { get; set; }
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double? MaxProcessingDelayToReconcileMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MachineStateRecomputeIntervalMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MachineActiveToClosedIntervalMinutes { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MachineActiveToExpiredIntervalMinutes { get; set; }
// Files smaller than this will use the untrusted hash
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int TrustedHashFileSizeBoundary = 100000;
[DataMember]
[Validation.Range(-1, long.MaxValue)]
public long ParallelHashingFileSizeBoundary { get; set; } = -1;
[DataMember]
public bool UseRedundantPutFileShortcut { get; set; } = false;
/// <summary>
/// Gets or sets whether to override Unix file access modes.
/// </summary>
[DataMember]
public bool OverrideUnixFileAccessMode { get; set; } = false;
[DataMember]
public bool TraceFileSystemContentStoreDiagnosticMessages { get; set; } = false;
[DataMember]
public bool? UseAsynchronousFileStreamOptionByDefault { get; set; }
[DataMember]
public bool TraceProactiveCopy { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? SilentOperationDurationThreshold { get; set; }
[DataMember]
public bool? UseHierarchicalTraceIds { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? DefaultPendingOperationTracingIntervalInMinutes { get; set; }
[DataMember]
public bool UseFastHibernationPin { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int? MaximumConcurrentPutAndPlaceFileOperations { get; set; }
#region Metadata Storage
[DataMember]
public bool EnableMetadataStore { get; set; } = false;
[DataMember]
public bool EnableDistributedCache { get; set; } = false;
[DataMember]
public bool UseRedisMetadataStore { get; set; } = false;
[DataMember]
public bool UseMemoizationContentMetadataStore { get; set; } = false;
[DataMember]
public bool EnablePublishingCache { get; set; } = false;
#endregion
/// <summary>
/// Gets or sets the time period between logging incremental stats
/// </summary>
[DataMember]
public TimeSpan? LogIncrementalStatsInterval { get; set; }
[DataMember]
public string[] IncrementalStatisticsCounterNames { get; set; }
/// <summary>
/// Gets or sets the time period between logging machine-specific performance statistics.
/// </summary>
[DataMember]
public TimeSpan? LogMachineStatsInterval { get; set; }
[DataMember]
public bool? Unsafe_MasterThroughputCheckMode { get; set; }
[DataMember]
public DateTime? Unsafe_EventHubCursorPosition { get; set; }
[DataMember]
public bool? Unsafe_IgnoreEpoch { get; set; }
[DataMember]
public bool? TraceServiceGrpcOperations { get; set; }
#endregion
#region Proactive Copy / Replication
/// <summary>
/// Valid values: Disabled, InsideRing, OutsideRing, Both (See ProactiveCopyMode enum)
/// </summary>
[DataMember]
[Validation.Enum(typeof(ProactiveCopyMode))]
public string ProactiveCopyMode { get; set; } = "Disabled";
[DataMember]
public bool PushProactiveCopies { get; set; } = false;
[DataMember]
public bool ProactiveCopyOnPut { get; set; } = true;
[DataMember]
public bool ProactiveCopyOnPin { get; set; } = false;
[DataMember]
public bool ProactiveCopyUsePreferredLocations { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ProactiveCopyLocationsThreshold { get; set; } = 3;
[DataMember]
public bool ProactiveCopyRejectOldContent { get; set; } = false;
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ProactiveReplicationCopyLimit { get; set; } = 5;
[DataMember]
public bool EnableProactiveReplication { get; set; } = false;
[DataMember]
[Validation.Range(0, double.MaxValue)]
public double ProactiveReplicationDelaySeconds { get; set; } = 30;
[DataMember]
[Validation.Range(0, int.MaxValue)]
public int PreferredLocationsExpiryTimeMinutes { get; set; } = 30;
[DataMember]
public bool UseBinManager { get; set; } = false;
[DataMember]
[Validation.Enum(typeof(MultiplexMode))]
public string MultiplexStoreMode { get; set; } = nameof(MultiplexMode.Unified);
/// <summary>
/// Indicates whether machine locations should use universal format (i.e. uri) which
/// allows communication across machines of different platforms
/// </summary>
[DataMember]
public bool UseUniversalLocations { get; set; }
/// <summary>
/// Include domain name in machine location.
/// </summary>
[DataMember]
public bool UseDomainName { get; set; }
public MultiplexMode GetMultiplexMode()
{
if (UseUniversalLocations)
{
// Universal locations don't distinguish cache paths, so just use unified multiplex mode
return MultiplexMode.Unified;
}
return (MultiplexMode)Enum.Parse(typeof(MultiplexMode), MultiplexStoreMode);
}
#endregion
#region Copy Scheduler
[DataMember]
public string CopySchedulerType { get; set; }
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int MaxConcurrentCopyOperations { get; set; } = DefaultMaxConcurrentCopyOperations;
[DataMember]
[Validation.Enum(typeof(SemaphoreOrder))]
public string OrderForCopies { get; set; } = SemaphoreOrder.NonDeterministic.ToString();
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int MaxConcurrentProactiveCopyOperations { get; set; } = DefaultMaxConcurrentCopyOperations;
[DataMember]
[Validation.Enum(typeof(SemaphoreOrder))]
public string OrderForProactiveCopies { get; set; } = SemaphoreOrder.NonDeterministic.ToString();
[DataMember]
[Validation.Range(1, int.MaxValue)]
public int ProactiveCopyIOGateTimeoutSeconds { get; set; } = 900;
[DataMember]
public PrioritizedCopySchedulerConfiguration PrioritizedCopySchedulerConfiguration { get; set; }
#endregion
/// <summary>
/// The map of drive paths to alternate paths to access them
/// </summary>
[DataMember]
public Dictionary<string, string> AlternateDriveMap { get; set; } = new Dictionary<string, string>();
[DataMember]
public bool TouchContentHashLists { get; set; }
[DataMember]
public bool EnableCacheActivityTracker { get; set; }
[DataMember]
public TimeSpan TrackingActivityWindow { get; set; } = TimeSpan.FromMinutes(1);
[DataMember]
public TimeSpan TrackingSnapshotPeriod { get; set; } = TimeSpan.FromSeconds(30);
[DataMember]
public TimeSpan TrackingReportPeriod { get; set; } = TimeSpan.FromSeconds(30);
[DataMember]
public bool? UseSeparateConnectionForRedisBlobs { get; set; }
/// <summary>
/// Indicates whether distributed content store operates in special mode where content is only consumed from other machines but
/// not available as a content replica from which other machines can copy content.
///
/// In this mode, the machine does not register itself as a part of the distributed network and thus is not
/// discoverable as a content replica for any content on the machine. This is useful for scenarios where distributed network
/// partially composed of machines which are short-lived and thus should not participate in the distributed network for the
/// sake of avoid churn. The machines can still pull content from other machines by querying LLS DB/Redis and getting replicas
/// on machines which are long-lived (and this flag is false).
/// </summary>
[DataMember]
public bool? DistributedContentConsumerOnly { get; set; }
[DataMember]
public int PublishingConcurrencyLimit { get; set; } = 128;
[DataMember]
public bool ContentMetadataEnableResilience { get; set; }
[DataMember]
public bool UseBlobVolatileStorage { get; set; }
[DataMember]
public string ContentMetadataRedisSecretName { get; set; }
[DataMember]
public string ContentMetadataBlobSecretName { get; set; }
[DataMember]
public TimeSpanSetting ContentMetadataPersistInterval { get; set; } = TimeSpan.FromSeconds(5);
[DataMember]
public TimeSpanSetting ContentMetadataShutdownTimeout { get; set; } = TimeSpan.FromSeconds(30);
[DataMember]
public TimeSpanSetting ContentMetadataClientConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);
[DataMember]
public TimeSpanSetting ContentMetadataClientOperationTimeout { get; set; } = TimeSpan.FromMinutes(15);
[DataMember]
public TimeSpanSetting ContentMetadataRedisMaximumKeyLifetime { get; set; } = TimeSpan.FromMinutes(120);
[DataMember]
public string ContentMetadataLogBlobContainerName { get; set; } = "persistenteventstorage";
[DataMember]
public string ContentMetadataCentralStorageContainerName { get; set; } = "contentmetadata";
[DataMember]
public string RedisWriteAheadKeyPrefix { get; set; } = "rwalog";
[DataMember]
public bool ContentMetadataBatchVolatileWrites { get; set; } = true;
[DataMember]
public EnumSetting<ContentMetadataStoreMode> ContentMetadataStoreMode { get; set; } = Configuration.ContentMetadataStoreMode.Redis;
[DataMember]
public EnumSetting<ContentMetadataStoreMode>? BlobContentMetadataStoreModeOverride { get; set; }
[DataMember]
public EnumSetting<ContentMetadataStoreMode>? LocationContentMetadataStoreModeOverride { get; set; }
[DataMember]
public EnumSetting<ContentMetadataStoreMode>? MemoizationContentMetadataStoreModeOverride { get; set; }
[DataMember]
public EnumSetting<ContentMetadataStoreMode>? ClusterGlobalStoreModeOverride { get; set; }
[DataMember]
public bool ContentMetadataBlobsEnabled { get; set; } = true;
[DataMember]
public TimeSpanSetting? AsyncSessionShutdownTimeout { get; set; }
#region Azure Blob Storage-based Checkpoint Registry
[DataMember]
public bool UseBlobCheckpointRegistry { get; set; }
[DataMember]
public bool? BlobCheckpointRegistryStandalone { get; set; }
[DataMember]
public int? BlobCheckpointRegistryCheckpointLimit { get; set; }
[DataMember]
public TimeSpanSetting? BlobCheckpointRegistryGarbageCollectionTimeout { get; set; }
[DataMember]
public TimeSpanSetting? BlobCheckpointRegistryRegisterCheckpointTimeout { get; set; }
[DataMember]
public TimeSpanSetting? BlobCheckpointRegistryGetCheckpointStateTimeout { get; set; }
#endregion
#region Azure Blob Storage-based Master Election
[DataMember]
public bool UseBlobMasterElection { get; set; }
[DataMember]
public string BlobMasterElectionFileName { get; set; }
[DataMember]
public TimeSpanSetting? BlobMasterElectionLeaseExpiryTime { get; set; }
[DataMember]
public TimeSpanSetting? BlobMasterElectionFetchCurrentMasterTimeout { get; set; }
[DataMember]
public TimeSpanSetting? BlobMasterElectionUpdateMasterLeaseTimeout { get; set; }
[DataMember]
public TimeSpanSetting? BlobMasterElectionReleaseRoleIfNecessaryTimeout { get; set; }
[DataMember]
public TimeSpanSetting? BlobMasterElectionStorageInteractionTimeout { get; set; }
#endregion
}
/// <summary>
/// Specifies which multiplexing cache topology to use multiplex between drives.
/// </summary>
public enum MultiplexMode
{
/// <summary>
/// Defines the legacy multiplexing mode with a single multiplexed store at the root
///
/// MultiplexedContentStore
/// DistributedContentStore (LLS Machine Location = D:\)
/// FileSystemContentStore (D:\)
/// DistributedContentStore (LLS Machine Location = K:\)
/// FileSystemContentStore (K:\)
///
/// LLS settings = (PrimaryMachineLocation = D:\, AdditionalMachineLocations = [K:\])
/// </summary>
Legacy,
/// <summary>
/// Defines the transitioning multiplexing mode with root distributed store nesting multiplexed file system stores
/// but still maintaining LLS machine locations for all drives
///
/// DistributedContentStore (LLS Machine Location = D:\)
/// MultiplexedContentStore
/// FileSystemContentStore (D:\)
/// FileSystemContentStore (K:\)
///
/// LLS settings = (PrimaryMachineLocation = D:\, AdditionalMachineLocations = [K:\])
///
/// Keeps same LLS settings so it continues to heartbeat to keep K:\ (secondary) drive alive
/// During reconcile, content from K:\ drive will be added to D:\ (primary) machine location
/// NOTE: GRPC content server does not care or know about machine locations, it will try to retrieve content from all drives.
/// </summary>
Transitional,
/// <summary>
/// Defines the transitioning multiplexing mode with root distributed store nesting multiplexed file system stores
/// with only a single lls machine location for the primary drive
///
/// DistributedContentStore (LLS Machine Location = D:\)
/// MultiplexedContentStore
/// FileSystemContentStore (D:\)
/// FileSystemContentStore (K:\)
///
/// LLS settings = (PrimaryMachineLocation = D:\, AdditionalMachineLocations = [])
///
/// Finally, LLS settings only mention the single primary (D:\) machine location, and all content for the machine (on all drives) is
/// now registered under that machine location after going through the Transitional state.
/// NOTE: GRPC content server does not care or know about machine locations, it will try to retrieve content from all drives.
/// </summary>
Unified,
}
/// <nodoc />
public class BandwidthConfiguration
{
/// <summary>
/// Whether to invalidate Grpc Copy Client in case of an error.
/// </summary>
public bool? InvalidateOnTimeoutError { get; set; }
/// <summary>
/// Gets an optional connection timeout that can be used to reject the copy more aggressively during early copy attempts.
/// </summary>
public double? ConnectionTimeoutInSeconds { get; set; }
/// <summary>
/// The interval between the copy progress is checked.
/// </summary>
public double IntervalInSeconds { get; set; }
/// <summary>
/// The number of required bytes that should be copied within a given interval. Otherwise the copy would be canceled.
/// </summary>
public long RequiredBytes { get; set; }
/// <summary>
/// If true, the server will return an error response immediately if the number of pending copy operations crosses a threshold.
/// </summary>
public bool FailFastIfServerIsBusy { get; set; }
}
}
| 37.201066 | 181 | 0.615068 |
[
"MIT"
] |
microsoft/BuildXL
|
Public/Src/Cache/DistributedCache.Host/Configuration/DistributedContentSettings.cs
| 48,847 |
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using AutoCrane.Interfaces;
namespace AutoCrane.Services
{
internal sealed class DefaultClock : IClock
{
public DateTimeOffset Get()
{
return DateTimeOffset.UtcNow;
}
}
}
| 18.294118 | 47 | 0.652733 |
[
"MIT"
] |
QPC-database/AutoCrane
|
src/AutoCrane/Services/DefaultClock.cs
| 313 |
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArrayAverageCalculator.cs" company="Laszlo Lukacs">
// See LICENSE for details.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Numerics;
namespace DotNetNumericsBenchmark
{
public static class ArrayAverageCalculator
{
/// <summary>
/// Gets the average of the specified arrays using scalar calculations.
/// </summary>
/// <param name="lhs">Left hand side.</param>
/// <param name="rhs">Right hand side.</param>
/// <returns>A collection containing the average values of the specified arrays.</returns>
public static double[] Average2Scalar(double[] lhs, double[] rhs)
{
var result = new double[lhs.Length];
int i;
for (i = 0; i < lhs.Length; i++)
{
result[i] = (lhs[i] + rhs[i]) / 2.0;
}
return result;
}
/// <summary>
/// Gets the average of the specified arrays using SIMD instructions.
/// </summary>
/// <param name="lhs">Left hand side.</param>
/// <param name="rhs">Right hand side.</param>
/// <returns>A collection containing the average values of the specified arrays.</returns>
public static double[] Average2Simd(double[] lhs, double[] rhs)
{
var simdLength = Vector<double>.Count;
var result = new double[lhs.Length];
var divider = new Vector<double>(2.0);
int i;
for (i = 0; i <= lhs.Length - simdLength; i += simdLength)
{
var va = new Vector<double>(lhs, i);
var vb = new Vector<double>(rhs, i);
((va + vb) / divider).CopyTo(result, i);
}
for (; i < lhs.Length; ++i)
{
result[i] = (lhs[i] + rhs[i]) / 2.0;
}
return result;
}
/// <summary>
/// Gets the average of the specified 3 arrays using SIMD instructions.
/// </summary>
/// <param name="lhs">Left hand side.</param>
/// <param name="mhs">Middle hand side.</param>
/// <param name="rhs">Right hand side.</param>
/// <returns>
/// A collection containing the average values of the specified arrays.
/// </returns>
public static double[] Average3Simd(double[] lhs, double[] mhs, double[] rhs)
{
var simdLength = Vector<double>.Count;
var result = new double[lhs.Length];
var divider = new Vector<double>(3.0);
int i;
for (i = 0; i <= lhs.Length - simdLength; i += simdLength)
{
var va = new Vector<double>(lhs, i);
var vb = new Vector<double>(mhs, i);
var vc = new Vector<double>(rhs, i);
((va + vb + vc) / divider).CopyTo(result, i);
}
for (; i < lhs.Length; ++i)
{
result[i] = (lhs[i] + mhs[i] + rhs[i]) / 3.0;
}
return result;
}
}
}
| 36.744444 | 120 | 0.467191 |
[
"MIT"
] |
laszlolukacs/DotNetNumericsBenchmark
|
src/DotNetNumericsBenchmark/ArrayAverageCalculator.cs
| 3,309 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные со сборкой.
[assembly: AssemblyTitle("IO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IO")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("ea8e663c-7a3b-4051-bb03-894b9a02a388")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.054054 | 99 | 0.759233 |
[
"Apache-2.0"
] |
cutzsc/IO
|
IO/Properties/AssemblyInfo.cs
| 1,987 |
C#
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using BtsPortal.Entities.Esb;
using BtsPortal.Repositories.Interface;
using BtsPortal.Repositories.Utilities;
using Dapper;
namespace BtsPortal.Repositories.Db
{
public class EsbExceptionDbRepository : IEsbExceptionDbRepository
{
private readonly IDbConnection _dbConnection;
private readonly int _commandTimeoutSeconds;
public EsbExceptionDbRepository(IDbConnection dbConnection, int commandTimeoutSeconds = 600)
{
_dbConnection = dbConnection;
_commandTimeoutSeconds = commandTimeoutSeconds;
}
public FaultSummaryVm GetFaultSummary(DateTime? startDateTime, DateTime? endDateTime)
{
var vm = new FaultSummaryVm()
{
StartDate = startDateTime,
EndDate = endDateTime
};
const string query = @"
--Declare @startDateTime datetime, @endDateTime datetime
select application,UnResolved,Resolved,Resubmitted,Flagged,LastFaultOccurredDateUtc
from
(
select f.application,
Isnull(fst.[Name],'UnResolved') as FaultStatus
,f.FaultID
,md.LastFaultOccurredDateUtc
from Fault f (NOLOCK)
left outer join [dbo].[Portal_FaultStatus] fs (NOLOCK) on f.FaultID = fs.FaultId
left outer join [dbo].[Portal_FaultStatusType] fst (NOLOCK) on fs.FaultStatusTypeID = fst.Id
left outer join
(
select f.application
, max([DateTime]) as LastFaultOccurredDateUtc
from Fault f (NOLOCK)
where DateTime between ISNULL(@startDateTime,'2000-01-01') and ISNULL(@endDateTime,'2099-01-01')
group by f.application
) as md on f.Application = md.Application
where DateTime between ISNULL(@startDateTime,'2000-01-01') and ISNULL(@endDateTime,'2099-01-01')
) p
PIVOT
(
COUNT (faultid)
FOR FaultStatus IN
( UnResolved,Resolved,Resubmitted,Flagged )
) AS pvt
ORDER BY application
--select ErrorType,UnResolved,Resolved,Resubmitted,Flagged,LastFaultOccurredDateUtc
--from
--(
--select f.ErrorType,
--Isnull(fst.[Name],'UnResolved') as FaultStatus
--,f.FaultID
--,md.LastFaultOccurredDateUtc
--from Fault f (NOLOCK)
--left outer join [dbo].[Portal_FaultStatus] fs (NOLOCK) on f.FaultID = fs.FaultId
--left outer join [dbo].[Portal_FaultStatusType] fst (NOLOCK) on fs.FaultStatusTypeID = fst.Id
--left outer join
--(
-- select f.ErrorType
-- , max([DateTime]) as LastFaultOccurredDateUtc
-- from Fault f (NOLOCK)
-- where DateTime between ISNULL(@startDateTime,'2000-01-01') and ISNULL(@endDateTime,'2099-01-01')
-- group by f.ErrorType
--) as md on f.ErrorType = md.ErrorType
--where DateTime between ISNULL(@startDateTime,'2000-01-01') and ISNULL(@endDateTime,'2099-01-01')
--) p
--PIVOT
--(
--COUNT (faultid)
--FOR FaultStatus IN
--(UnResolved,Resolved,Resubmitted,Flagged )
--) AS pvt
--ORDER BY ErrorType
";
var data = _dbConnection.QueryMultiple(query, new { startDateTime, endDateTime });
vm.FaultSummariesByApplication = data.Read<FaultSummary>() as List<FaultSummary>;
//vm.FaultSummariesByErrorType = data.Read<FaultSummary>() as List<FaultSummary>;
return vm;
}
public List<FaultSearchResponse> GetFaults(FaultSearchRequest request, int page, out int totalRows, int pageSize)
{
const string query = @"
--Declare @fromDateTime datetime,
-- @toDateTime datetime,
-- @faultStatusTypeId int,
-- @errorType varchar(100),
-- @errorTypeExact varchar(100),
-- @faultCode varchar(100),
-- @failureCategory varchar(100),
-- @failureScope varchar(100),
-- @faultId varchar(50),
-- @message varchar(100),
-- @application varchar(100),
-- @pageNum int = 1,
-- @pageSize int = 100
select distinct
Application,
FaultSeverity,
DateTime as TransactionDateTimeUtc,
f.FaultID,
ErrorType,
FailureCategory,
FaultCode,
Scope,
ServiceName,
FaultGenerator,
MachineName,
ISNULL(fs.FaultStatusTypeId,1) as Status,
f.InsertMessagesFlag
from Fault f (NOLOCK)
left outer join Portal_FaultStatus fs (NOLOCK) on f.FaultID = fs.FaultID
left outer join Message m (NOLOCK) on f.FaultID = m.FaultID
left outer join MessageData md (NOLOCK) on m.MessageID = md.MessageID
where isnull(f.Application,'') = ISNULL(@application,f.Application)
and f.DateTime between ISNULL(@fromDateTime,'2000-01-01') and ISNULL(@toDateTime,'2099-01-01')
and ISNULL(fs.FaultStatusTypeId,1) = ISNULL(@faultStatusTypeId,ISNULL(fs.FaultStatusTypeId,1))
and cast(f.FaultID as varchar(50)) like '%' + ISNULL(@faultId,cast(f.FaultID as varchar(50))) + '%'
and isnull(f.ErrorType,'') like '%' + ISNULL(@errorType,f.ErrorType) + '%'
and isnull(f.ErrorType,'') = ISNULL(@errorTypeExact,f.ErrorType)
and isnull(f.FaultCode,'') like '%' + ISNULL(@faultCode,f.FaultCode) + '%'
and (md.MessageData is null or md.MessageData like '%' + ISNULL(@message,md.MessageData) + '%')
and isnull(f.FailureCategory,'') like '%' + ISNULL(@failureCategory,f.FailureCategory) + '%'
and isnull(f.Scope,'') like '%' + ISNULL(@failureScope,f.Scope) + '%'
order by f.DateTime desc
OFFSET (@pageNum -1) * @pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY ;
--total rows
select count(distinct f.FaultID) as TotalRows
from Fault f (NOLOCK)
left outer join Portal_FaultStatus fs (NOLOCK) on f.FaultID = fs.FaultID
left outer join [dbo].[Portal_FaultStatusType] fst (NOLOCK) on fs.FaultStatusTypeId=fst.Id
left outer join Message m (NOLOCK) on f.FaultID = m.FaultID
left outer join MessageData md (NOLOCK) on m.MessageID = md.MessageID
where isnull(f.Application,'') = ISNULL(@application,f.Application)
and f.DateTime between ISNULL(@fromDateTime,'2000-01-01') and ISNULL(@toDateTime,'2099-01-01')
and ISNULL(fs.FaultStatusTypeId,1) = ISNULL(@faultStatusTypeId,ISNULL(fs.FaultStatusTypeId,1))
and cast(f.FaultID as varchar(50)) like '%' + ISNULL(@faultId,cast(f.FaultID as varchar(50))) + '%'
and isnull(f.ErrorType,'') like '%' + ISNULL(@errorType,f.ErrorType) + '%'
and isnull(f.FaultCode,'') like '%' + ISNULL(@faultCode,f.FaultCode) + '%'
and isnull(md.MessageData,'') like '%' + ISNULL(@message,md.MessageData) + '%'
and isnull(f.FailureCategory,'') like '%' + ISNULL(@failureCategory,f.FailureCategory) + '%'
and isnull(f.Scope,'') like '%' + ISNULL(@failureScope,f.Scope) + '%'
";
List<FaultSearchResponse> responses;
totalRows = 0;
using (var multi = _dbConnection.QueryMultiple(query,
new
{
application = request.Application.ToDbStringAnsi(),
fromDateTime = request.FromDateTime,
toDateTime = request.ToDateTime,
faultStatusTypeId = request.Status,
errorType = request.ErrorType.ToDbStringAnsi(),
faultCode = request.FaultCode.ToDbStringAnsi(),
failureCategory = request.FailureCategory.ToDbStringAnsi(),
failureScope = request.FailureScope.ToDbStringAnsi(),
faultId = request.FaultId.ToDbStringAnsi(),
message = request.Message.ToDbStringAnsi(),
pageSize = pageSize,
errorTypeExact = request.ErrorTypeExact,
pageNum = page
}, commandTimeout: _commandTimeoutSeconds))
{
responses = multi.Read<FaultSearchResponse>().ToList();
totalRows = multi.Read<int>().Single();
}
return responses;
}
public FaultDetailAggregate GetFaultDetail(string faultId)
{
const string query = @"
--declare @faultId varchar(50)
--set @faultId = '13471b20-cb1a-412d-996a-4b58126284dd'
select
FaultID,
NativeMessageID,
ActivityID,
Application,
Description,
ErrorType,
FailureCategory,
FaultCode,
FaultDescription,
FaultSeverity,
Scope,
ServiceInstanceID,
ServiceName,
FaultGenerator,
MachineName,
DateTime,
ExceptionMessage,
ExceptionType,
ExceptionSource,
ExceptionTargetSite,
ExceptionStackTrace,
InnerExceptionMessage,
InsertMessagesFlag,
InsertedDate
from Fault f (NOLOCK)
where f.FaultID = @faultId
select FaultID,MessageID,InterchangeID,MessageName,ContentType
from Message (NOLOCK)
where FaultID = @faultId
select distinct FaultID, FaultStatusTypeId as FaultStatusType, UpdatedTime as UpdatedTimeUtc, UpdatedBy,Comment
from Portal_FaultHistory (NOLOCK)
where FaultID = @faultId
";
var vm = new FaultDetailAggregate();
using (var multi = _dbConnection.QueryMultiple(query,
new
{
faultId = faultId.ToDbStringAnsi()
}))
{
vm.FaultDetail = multi.Read<FaultDetail>().SingleOrDefault();
vm.FaultMessages = multi.Read<FaultMessage>().ToList();
vm.FaultHistories = multi.Read<FaultHistory>().ToList();
}
return vm;
}
public void UpdateFaultStatus(List<string> faultIdList, FaultStatusType statusType, string currentUser,
string batchId, string comment)
{
const string query = @"
--declare @faultId varchar(50),@faultStatusTypeId smallInt,@currentUser varchar(50),@batchId uniqueidentifier,@comment varchar(50)
MERGE Portal_FaultStatus AS target
USING (SELECT '{0}', '{1}') AS source (FaultId, FaultStatusTypeId)
ON (target.FaultId = source.FaultId)
WHEN MATCHED THEN
UPDATE SET FaultStatusTypeId = source.FaultStatusTypeId
WHEN NOT MATCHED THEN
INSERT (FaultID, FaultStatusTypeId)
VALUES (source.FaultID, source.FaultStatusTypeId);
insert into [dbo].[Portal_FaultHistory](FaultID, FaultStatusTypeId, UpdatedTime, UpdatedBy, UpdatedBatchId,Comment)
values(
'{0}',
'{1}',
GETUTCDATE(),
'{2}',
'{3}',
'{4}'
);
";
StringBuilder sqlStatements = new StringBuilder();
foreach (string faultId in faultIdList)
{
sqlStatements.AppendLine(string.Format(query, faultId, (int)statusType, currentUser, batchId, comment));
}
int result = _dbConnection.Execute(sqlStatements.ToString(), null, null, _commandTimeoutSeconds);
}
public MessageDetail GetFaultMessageDetail(string faultId, string messageId, int maxDataLength = 40000)
{
const string query = @"
--declare @faultid uniqueidentifier = 'b429c1a2-3e57-4734-8567-0c6d957fac0a'
-- ,@messageId uniqueidentifier = '6b81fb78-d8be-48fb-83fc-9bfb0e05c721'
-- ,@maxDataLength int = 40000
select FaultId,MessageID,ContentType,MessageName,InterchangeID
from Message (NOLOCK)
where CONVERT(varchar(36), FaultID) = @faultid
and CONVERT(varchar(36), MessageID) = @messageId
select MessageID,SUBSTRING ( MessageData ,0 , @maxDataLength ) as MessageData,DATALENGTH(MessageData) as MessageDataLength,@maxDataLength as MaxDataLength
from MessageData (NOLOCK)
where CONVERT(varchar(36), MessageID) = @messageId
select name,Value,Type
from ContextProperty (NOLOCK)
where CONVERT(varchar(36), MessageID) = @messageId
";
var vm = new MessageDetail();
using (var multi = _dbConnection.QueryMultiple(query,
new
{
faultId = faultId.ToDbStringAnsi(),
messageId = messageId.ToDbStringAnsi(),
maxDataLength = maxDataLength
}))
{
vm.Message = multi.Read<FaultMessage>().SingleOrDefault();
vm.Data = multi.Read<FaultMessageData>().SingleOrDefault();
vm.FaultMessageContexts = multi.Read<FaultMessageContext>().ToList();
}
return vm;
}
public FaultMessageData GetFaultMessageData(string messageId)
{
const string query = @"
--declare @messageId uniqueidentifier = '6b81fb78-d8be-48fb-83fc-9bfb0e05c721'
select MessageData
from MessageData (NOLOCK)
where CONVERT(varchar(36), MessageID) = @messageId
";
return _dbConnection.Query<FaultMessageData>(query, new
{
messageId = messageId.ToDbStringAnsi()
}).SingleOrDefault();
}
public EsbUserAlertSubscription GetAlerts(string currentUser)
{
const string query = @"
--declare @subscriber varchar(50)='AzureAD\NishantNepal'
SELECT
a.[AlertID],
[Name],
[ConditionsString],
[InsertedBy],
[InsertedDate],
(SELECT COUNT(AlertID) FROM dbo.AlertSubscription s WHERE AlertID = a.AlertID and active=1) AS TotalSubscriberCount,
ISNULL(ia.[IsSummaryAlert],0) as IsSummaryAlert
,ia.[LastFired]
,ia.[IntervalMins]
FROM dbo.Alert a (NOLOCK)
left outer join [dbo].[Portal_Alert] ia (NOLOCK) on a.AlertID = ia.alertid
select asu.alertid,asu.AlertSubscriptionID,a.Name,a.ConditionsString,asu.Active,asu.CustomEmail,asu.Subscriber,asu.[InsertedDate],asu.[InsertedBy]
from AlertSubscription asu(NOLOCK)
inner join Alert a (NOLOCK)on a.AlertID = asu.AlertID
where Subscriber = @subscriber
order by Active,name,asu.Subscriber,CustomEmail
select distinct asu.alertid,asu.AlertSubscriptionID,asu.CustomEmail,asu.Subscriber
from AlertSubscription asu(NOLOCK)
inner join Alert a (NOLOCK)on a.AlertID = asu.AlertID
where Active = 1
order by asu.Subscriber,CustomEmail
";
var vm = new EsbUserAlertSubscription()
{
CurrentUser = currentUser
};
List<EsbAlertSubscription> alertSubs = new List<EsbAlertSubscription>();
using (var multi = _dbConnection.QueryMultiple(query,
new
{
subscriber = currentUser.ToDbStringAnsi(),
}))
{
vm.Alerts = multi.Read<EsbAlert>().ToList();
vm.MyAlertSubscriptions = multi.Read<EsbAlertSubscription>().ToList();
alertSubs = multi.Read<EsbAlertSubscription>().ToList();
}
foreach (var alertSub in alertSubs)
{
var alert = vm.Alerts.FirstOrDefault(m => m.AlertId == alertSub.AlertId);
alert?.AlertSubscriptions.Add(new EsbAlertSubscription()
{
Active = true,
AlertId = alert.AlertId,
AlertSubscriptionId = alertSub.AlertSubscriptionId,
CustomEmail = alertSub.CustomEmail,
Subscriber = alertSub.Subscriber
});
}
return vm;
}
public void SaveAlert(Guid? alertId, string alertName, string conditionString, string insertedBy, AlertType alertType, int? alertMins, List<AlertCondition> conds)
{
Guid alert = alertId ?? Guid.NewGuid();
bool summaryAlert = alertType == AlertType.Summary;
const string query = @"
--declare @alertId uniqueidentifier,@name varchar(100),@conditionString varchar(max),@insertedDate datetime,@insertedBy varchar(100)
insert into Alert
(
AlertID,
Name,
ConditionsString,
InsertedDate,
InsertedBy
)
values
(
ISNULL(@alertId,newid())
,@name
,@conditionString
,GETDATE()
,@insertedBy
)
insert into Portal_Alert(AlertID, IsSummaryAlert,IntervalMins)
values (@alertId,@summaryAlert,@alertMins)
delete from [dbo].[AlertCondition]
where alertid = @alertId
";
int result = _dbConnection.Execute(query, new
{
alertId = alert,
name = alertName,
conditionString,
insertedBy = insertedBy,
summaryAlert = summaryAlert,
alertMins = alertMins
}, null, _commandTimeoutSeconds);
foreach (var condition in conds)
{
_dbConnection.Execute(@"insert into [dbo].[AlertCondition](AlertID, LeftSide, RightSide, Operator, InsertedDate) values(@AlertID, @LeftSide, @RightSide, @Operator, getdate())", new
{
alertId = alert,
LeftSide = condition.Criteria.ToDbStringAnsi(),
RightSide = condition.Value.ToDbStringAnsi(),
Operator = condition.Operation.ToDbStringAnsi(),
}, null, _commandTimeoutSeconds);
}
}
public void DeleteAlert(Guid? alertId, string deletedBy)
{
const string query = @"
delete from alert
where AlertID = @alertId
delete from Portal_Alert
where AlertID = @alertId
";
int result = _dbConnection.Execute(query, new
{
alertId = alertId
}, null, _commandTimeoutSeconds);
}
public void SaveAlertSubscription(EsbAlertSubscription alertSubscription, string currentUser)
{
const string query = @"
insert into [dbo].[AlertSubscription]
(
AlertSubscriptionID,
AlertID,
Active,
Subscriber,
IsGroup,
CustomEmail,
UseStartAndEndTime,
InsertedDate,
InsertedBy,
ModifiedDate,
ModifiedBy
)
values
(
newid(),
@alertId,
1,
@subscriber,
@isGroup,
@customEmail,
0,
getdate(),
@currentUser,
getdate(),
@currentUser
)
";
int result = _dbConnection.Execute(query, new
{
alertId = alertSubscription.AlertId,
subscriber = alertSubscription.Subscriber.ToDbStringAnsi(),
isGroup = alertSubscription.IsGroup,
customEmail = alertSubscription.CustomEmail,
currentUser = currentUser.ToDbStringAnsi()
}, null, _commandTimeoutSeconds);
}
public void ToggleAlertSubscriptionState(Guid alertSubscriptionId, bool state, string currentUser)
{
const string query = @"
update AlertSubscription
set Active = @currentState,ModifiedDate = getdate(),ModifiedBy = @currentUser
where AlertSubscriptionID = @alertSubscriptionId
";
int result = _dbConnection.Execute(query, new
{
currentState = state,
alertSubscriptionId = alertSubscriptionId,
currentUser = currentUser.ToDbStringAnsi()
}, null, _commandTimeoutSeconds);
}
public void DeleteAlertSubscription(Guid alertSubscriptionId)
{
const string query = @"
delete from AlertSubscription
where AlertSubscriptionID = @alertSubscriptionId
";
int result = _dbConnection.Execute(query, new
{
alertSubscriptionId = alertSubscriptionId
}, null, _commandTimeoutSeconds);
}
public List<EsbConfiguration> GetEsbConfiguration()
{
const string query = @"
SELECT [ConfigurationID]
,[Name]
,[Value]
,[Description]
,[ModifiedDate]
,[ModifiedBy]
FROM [EsbExceptionDb].[dbo].[Configuration]
";
return _dbConnection.Query<EsbConfiguration>(query).ToList();
}
public void UpdateEsbConfiguration(Guid configurationId, string value, string user)
{
const string query = @"
update Configuration
set Value = @value,
ModifiedBy = @user,
ModifiedDate = GETDATE()
where ConfigurationID = @configurationId
";
int result = _dbConnection.Execute(query, new
{
configurationId = configurationId,
value = value.ToDbStringAnsi(length: 256),
user = user.ToDbStringAnsi()
}, null, _commandTimeoutSeconds);
}
public AlertNotification GetAlertNotifications(int batchSize)
{
var vm = new AlertNotification();
const string query = @"
DECLARE @Statement nvarchar(4000)
--,@BatchSize int = 500
,@batchId uniqueidentifier = newid()
insert into [dbo].[Batch](BatchID, StartDatetime)
values(@batchId,getdate())
SET @Statement = N'SELECT TOP ' + CONVERT(varchar, @BatchSize) + '
f.[FaultID]
,f.[Application]
,f.[Description]
,f.[ErrorType]
,f.[FailureCategory]
,f.[FaultCode]
,f.[FaultDescription]
,f.[FaultSeverity]
,f.[Scope]
,f.[ServiceInstanceID]
,f.[ServiceName]
,f.[FaultGenerator]
,f.[MachineName]
,f.[DateTime]
,f.[ExceptionMessage]
,f.[ExceptionType]
,f.[ExceptionSource]
,f.[ExceptionTargetSite]
,f.[ExceptionStackTrace]
,f.[InnerExceptionMessage]
,f.[InsertedDate]
FROM dbo.Fault f
LEFT OUTER JOIN dbo.ProcessedFault pf ON pf.ProcessedFaultID = f.FaultID
LEFT OUTER JOIN [dbo].[Portal_FaultStatus] fs ON fs.FaultID = f.FaultID
WHERE
pf.ProcessedFaultID IS NULL
and ISNULL(fs.[FaultStatusTypeId],1) = 1
'
CREATE TABLE #tempFaults(
[FaultID] [uniqueidentifier] NOT NULL,
[Application] [varchar](256) NOT NULL,
[Description] [varchar](4096) NULL,
[ErrorType] [varchar](100) NOT NULL,
[FailureCategory] [varchar](256) NOT NULL,
[FaultCode] [varchar](20) NOT NULL,
[FaultDescription] [varchar](4096) NULL,
[FaultSeverity] [int] NULL,
[Scope] [varchar](256) NOT NULL,
[ServiceInstanceID] [varchar](38) NOT NULL,
[ServiceName] [varchar](256) NOT NULL,
[FaultGenerator] [varchar](50) NULL,
[MachineName] [varchar](256) NULL,
[DateTime] [datetime] NULL,
[ExceptionMessage] [varchar](4096) NOT NULL,
[ExceptionType] [varchar](100) NOT NULL,
[ExceptionSource] [varchar](256) NOT NULL,
[ExceptionTargetSite] [varchar](256) NOT NULL,
[ExceptionStackTrace] [varchar](4096) NOT NULL,
[InnerExceptionMessage] [varchar](4096) NOT NULL,
[InsertedDate] [datetime]
)
CREATE TABLE #tempFaults2(
[FaultID] [uniqueidentifier] NOT NULL,
[Application] [varchar](256) NOT NULL,
[Description] [varchar](4096) NULL,
[ErrorType] [varchar](100) NOT NULL,
[FailureCategory] [varchar](256) NOT NULL,
[FaultCode] [varchar](20) NOT NULL,
[FaultDescription] [varchar](4096) NULL,
[FaultSeverity] [int] NULL,
[Scope] [varchar](256) NOT NULL,
[ServiceInstanceID] [varchar](38) NOT NULL,
[ServiceName] [varchar](256) NOT NULL,
[FaultGenerator] [varchar](50) NULL,
[MachineName] [varchar](256) NULL,
[DateTime] [datetime] NULL,
[ExceptionMessage] [varchar](4096) NOT NULL,
[ExceptionType] [varchar](100) NOT NULL,
[ExceptionSource] [varchar](256) NOT NULL,
[ExceptionTargetSite] [varchar](256) NOT NULL,
[ExceptionStackTrace] [varchar](4096) NOT NULL,
[InnerExceptionMessage] [varchar](4096) NOT NULL,
[InsertedDate] [datetime]
)
insert into #tempFaults
EXECUTE sp_executesql @Statement
create table #tempFaultsToAlerts
(
faultid uniqueidentifier,
alertid uniqueidentifier
)
create table #tempAlerts
(
alertid uniqueidentifier,
ConditionsString varchar(max)
)
insert into #tempAlerts
--all valid alerts
select distinct a.AlertID,ConditionsString
from alert a
inner join AlertSubscription asu on a.AlertID = asu.AlertID and asu.Active = 1
left outer join Portal_Alert pa on a.AlertID = pa.AlertID
where ISNULL(pa.IsSummaryAlert,0) = 0
-----
Declare @alertId uniqueidentifier, @conditionsString varchar(max),@filterStatement nvarchar(4000)
DECLARE alert_cursor CURSOR FOR
SELECT alertid, conditionsstring
FROM #tempAlerts
OPEN alert_cursor
FETCH NEXT FROM alert_cursor
INTO @alertId, @conditionsString
WHILE @@FETCH_STATUS = 0
BEGIN
set @filterStatement = 'select * from #tempFaults where ' + @conditionsString
--print @filterStatement
insert into #tempFaults2
EXECUTE sp_executesql @filterStatement
insert into #tempFaultsToAlerts
select distinct faultid,@alertId from #tempFaults2
truncate table #tempFaults2
update [dbo].[Portal_Alert]
set [LastFired] = GETDATE()
where [AlertID] = @alertId
if @@ROWCOUNT = 0
insert into [dbo].[Portal_Alert](AlertID, IsSummaryAlert, LastFired)
values(@alertId,0,GETDATE())
FETCH NEXT FROM alert_cursor
INTO @alertId, @conditionsString
END
CLOSE alert_cursor;
DEALLOCATE alert_cursor;
--mark faults as processed
insert into ProcessedFault
select distinct faultid from #tempFaults
select @batchId as BatchId
select * from #tempFaultsToAlerts
select * from #tempFaults where faultid in (select distinct faultid from #tempFaultsToAlerts)
select a.AlertID, Name, ConditionsString,ia.[LastFired],ia.[IntervalMins],ISNULL(ia.[IsSummaryAlert],0) as IsSummaryAlert
from Alert a
left outer join [dbo].[Portal_Alert] ia (NOLOCK) on a.AlertID = ia.alertid and ISNULL(ia.[IsSummaryAlert],0) = 0
select a.AlertID, Name, ConditionsString,[Subscriber],[IsGroup],[CustomEmail],asu.AlertSubscriptionID
from Alert a
inner join [dbo].[AlertSubscription] asu on asu.AlertID = a.AlertID and asu.Active=1
where a.AlertID in (select distinct alertid from #tempFaultsToAlerts)
drop table #tempFaults
drop table #tempFaults2
drop table #tempFaultsToAlerts
drop table #tempAlerts
";
using (var multi = _dbConnection.QueryMultiple(query, new
{
batchSize = batchSize
},
commandTimeout: _commandTimeoutSeconds))
{
vm.BatchId = multi.Read<Guid>().FirstOrDefault();
vm.AlertFaults = multi.Read<AlertFault>().ToList();
vm.FaultDetails = multi.Read<FaultDetail>().ToList();
vm.Alerts = multi.Read<EsbAlert>().ToList();
vm.AlertSubscriptions = multi.Read<EsbAlertSubscription>().ToList();
}
return vm;
}
public void InsertAlertEmail(List<AlertEmailNotification> emailNotifications)
{
const string statment = @"insert into [dbo].[Portal_AlertEmail](AlertID, [To], [Subject], Body, [Sent], BatchID,IsSummaryAlert)
values (@AlertID, @To, @Subject, @Body, @Sent, @BatchID,@IsSummaryAlert)";
foreach (var emailNotification in emailNotifications)
{
_dbConnection.Execute(statment, emailNotification);
}
}
public void UpdateAlertLastFired(List<Guid> alertIds, DateTime lastFiredTime)
{
string query = @"update [dbo].[Portal_Alert]
set [LastFired] = @lastFiredTime
where [AlertID] = @alertId
if @@ROWCOUNT = 0
insert into Portal_Alert(AlertId,lastfired) values (@alertId,@lastFiredTime)";
foreach (var alertId in alertIds)
{
_dbConnection.Execute(query, new
{
alertId = alertId,
lastFiredTime = lastFiredTime
});
}
}
public void UpdateAlertBatchComplete(Guid batchId, string errorMsg)
{
string query = @"update Batch
set [EndDatetime] = getdate() ,[ErrorMessage] = @errorMsg
where [BatchID] = @batchId";
_dbConnection.Execute(query, new
{
batchId = batchId,
errorMsg = errorMsg.ToDbStringAnsi(length: 500)
});
}
public List<AlertEmailNotification> GetAlertEmails(int batchSize)
{
const string query = @"
SELECT TOP (@batchSize) [AlertEmailID]
,[AlertID]
,[To]
,[Subject]
,[Body]
,[Sent]
,[BatchID]
,[InsertedDate]
,[Error]
,IsSummaryAlert
FROM [EsbExceptionDb].[dbo].[Portal_AlertEmail] (NOLOCK)
where sent = 0
";
var data = _dbConnection.Query<AlertEmailNotification>(query, new
{
BatchSize = batchSize
}).ToList();
return data;
}
public void UpdateAlertEmails(List<AlertEmailNotification> emailNotifications)
{
string query = @"update [dbo].[Portal_AlertEmail]
set [Sent] = @sent,
error = @error
where [AlertEmailID] = @alertEmailId";
foreach (var emailNotif in emailNotifications)
{
_dbConnection.Execute(query, new
{
sent = emailNotif.Sent,
error = emailNotif.Error,
alertEmailId = emailNotif.AlertEmailId
});
}
}
public AlertView GetAlert(Guid? alertId)
{
const string query = @"
select a.AlertID, Name,ISNULL(ia.IsSummaryAlert,0) as IsSummaryAlert,ia.IntervalMins
from alert a
left outer join Portal_Alert ia on a.AlertID = ia.alertid
where a.AlertID = @alertId
select
AlertID,
LeftSide as Criteria,
RightSide as Value,
Operator as Operation,
InsertedDate
from [dbo].[AlertCondition]
where AlertID=@alertId
";
var vm = new AlertView();
using (var multi = _dbConnection.QueryMultiple(query,
new
{
alertId = alertId,
}, commandTimeout: _commandTimeoutSeconds))
{
vm.Alert = multi.Read<EsbAlert>().FirstOrDefault();
vm.AlertConditions = multi.Read<AlertCondition>().ToList();
}
return vm;
}
public void UpdateAlert(Guid alertId, AlertType alertType, int? alertMins)
{
bool isSummary = alertType == AlertType.Summary;
const string query = @"update Portal_Alert
set [IsSummaryAlert] = @isSummary,[IntervalMins] = @alertMins
where alertid = @alertid
if @@ROWCOUNT = 0
insert into Portal_Alert(AlertID, IsSummaryAlert, IntervalMins)
values(@alertId,@isSummary,@alertMins)";
_dbConnection.Execute(query, new
{
alertId = alertId,
isSummary = isSummary,
alertMins = alertMins
});
}
public AlertNotification GetAlertSummaryNotifications()
{
var vm = new AlertNotification();
const string query = @"
CREATE TABLE #tempFaults2(
AlertId uniqueidentifier NOT NULL,
[Application] [varchar](256) NOT NULL,
[ServiceName] [varchar](256) NOT NULL,
[ExceptionType] [varchar](100) NOT NULL,
Count int,
MaxTime datetime,
MinTime datetime
)
create table #tempAlerts
(
alertid uniqueidentifier,
ConditionsString varchar(max),
lastfired datetime,
intervalmins smallint
)
insert into #tempAlerts
--all valid alerts
select distinct a.AlertID,ConditionsString,ISNULL(ia.lastfired,'2000-01-01') as lastfired,ia.intervalmins
from Alert a (NOLOCK)
inner join AlertSubscription asu (NOLOCK) on a.AlertID = asu.AlertID and asu.Active = 1
left outer join Portal_Alert ia (NOLOCK) on ia.alertid = a.AlertID
where ia.issummaryalert = 1
and DATEDIFF(minute,ISNULL(ia.lastfired,'2000-01-01'),getdate()) > ISNULL(ia.intervalmins,120)
-----
Declare @alertId uniqueidentifier, @conditionsString varchar(max),@filterStatement nvarchar(4000),@intervalmins smallint
,@lastfired datetime
DECLARE alert_cursor CURSOR FOR
SELECT alertid, conditionsstring ,lastfired,intervalmins
FROM #tempAlerts
OPEN alert_cursor
FETCH NEXT FROM alert_cursor
INTO @alertId, @conditionsString ,@lastfired,@intervalmins
WHILE @@FETCH_STATUS = 0
BEGIN
declare @now datetime = getdate()
set @filterStatement = 'select distinct ''' + cast(@alertId as varchar(50)) + ''' ,Application,ServiceName,ExceptionType,count(*) as Count,max(datetime) as MaxTime,min(datetime) as MinTime from Fault (NOLOCK)
where InsertedDate >= ''' + convert(varchar(25), @lastfired, 120)
+ ''' and InsertedDate < ''' + convert(varchar(25), @now, 120)
+ ''' and ' + @conditionsString +
' group by Application,ExceptionType,ServiceName order by Count desc'
print @filterStatement
insert into #tempFaults2
EXECUTE sp_executesql @filterStatement
--insert into #tempFaultsToAlerts
--select distinct faultid,@alertId from #tempFaults2
update [dbo].[Portal_Alert]
set [LastFired] = @now
where [AlertID] = @alertId
FETCH NEXT FROM alert_cursor
INTO @alertId, @conditionsString ,@lastfired,@intervalmins
END
CLOSE alert_cursor;
DEALLOCATE alert_cursor;
select * from #tempFaults2
select a.AlertID, Name, ConditionsString,[Subscriber],[IsGroup],[CustomEmail],asu.AlertSubscriptionID
from Alert a
inner join [dbo].[AlertSubscription] asu on asu.AlertID = a.AlertID and asu.Active=1
where a.AlertID in (select distinct alertid from #tempFaults2)
drop table #tempFaults2
drop table #tempAlerts
";
using (var multi = _dbConnection.QueryMultiple(query, null, commandTimeout: _commandTimeoutSeconds))
{
vm.AlertFaultSummaries = multi.Read<AlertFaultSummary>().ToList();
vm.AlertSubscriptions = multi.Read<EsbAlertSubscription>().ToList();
}
return vm;
}
public void InsertFault(FaultDetail faultDetail, List<FaultMessage> faultMessages, List<FaultMessageContext> faultMessageContexts, List<FaultMessageData> faultMessageDatas, FaultHistory history)
{
const string faultQuery = @"
insert into [dbo].[Fault]
(
FaultID,
NativeMessageID,
ActivityID,
Application,
Description,
ErrorType,
FailureCategory,
FaultCode,
FaultDescription, FaultSeverity, Scope, ServiceInstanceID, ServiceName, FaultGenerator,
MachineName, DateTime, ExceptionMessage, ExceptionType, ExceptionSource, ExceptionTargetSite,
ExceptionStackTrace, InnerExceptionMessage, InsertMessagesFlag, InsertedDate
)
values
(
@FaultID,
@NativeMessageID,
@ActivityID,
@Application,
@Description,
@ErrorType,
@FailureCategory,
@FaultCode,
@FaultDescription, @FaultSeverity, @Scope, @ServiceInstanceID, @ServiceName, @FaultGenerator,
@MachineName, @DateTime, @ExceptionMessage, @ExceptionType, @ExceptionSource, @ExceptionTargetSite,
@ExceptionStackTrace, @InnerExceptionMessage, @InsertMessagesFlag, @InsertedDate
)
";
_dbConnection.Execute(faultQuery, faultDetail, null, _commandTimeoutSeconds);
foreach (var message in faultMessages)
{
const string query = @"
insert into Message
(
MessageID, NativeMessageID, FaultID, ContentType, MessageName, InterchangeID
)
values
(
@MessageID,
@NativeMessageID,
@FaultID,
@ContentType,
@MessageName,
@InterchangeID
)
";
_dbConnection.Execute(query, message, null, _commandTimeoutSeconds);
}
foreach (var message in faultMessageDatas)
{
const string query = @"
insert into MessageData
(MessageID, MessageData)
values (@MessageID, @MessageData)
";
_dbConnection.Execute(query, message, null, _commandTimeoutSeconds);
}
foreach (var message in faultMessageContexts)
{
const string query = @"
insert into ContextProperty
(ContextPropertyID, MessageID, Name, Value, Type, InsertedDate)
values
(@ContextPropertyID, @MessageID, @Name, @Value, @Type, GETUTCDATE())
";
_dbConnection.Execute(query, message, null, _commandTimeoutSeconds);
}
const string historyQuery = @"
insert into [dbo].[Portal_FaultHistory]
(FaultID, FaultStatusTypeId, UpdatedTime, UpdatedBy, UpdatedBatchId, Comment)
values(@FaultID, 1, getutcdate(), @UpdatedBy, NEWID(), @Comment)
";
_dbConnection.Execute(historyQuery, history, null, _commandTimeoutSeconds);
}
}
}
| 31.653262 | 209 | 0.657312 |
[
"MIT"
] |
adiraina/BtsPortal
|
BtsPortal.Repositories/Db/EsbExceptionDbRepository.cs
| 35,422 |
C#
|
using System;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class CameraController : MonoBehaviour
{
Camera camera;
[SerializeField] float scrollSpeed = 2.5f;
[SerializeField] float dragSpeed = 1.0f;
void Awake()
{
camera = GetComponent<Camera>();
}
void Update()
{
float scroll = Input.GetAxisRaw("Mouse ScrollWheel");
if (scroll < 0)
{
camera.orthographicSize += 1.0f * scrollSpeed;
}
else if (scroll > 0)
{
camera.orthographicSize -= 1.0f * scrollSpeed;
}
if (camera.orthographicSize < 4)
camera.orthographicSize = 4;
}
void LateUpdate()
{
if(Input.GetMouseButton(2))
transform.position -= new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0) * (dragSpeed * camera.orthographicSize * 0.01f);
}
}
| 22.875 | 149 | 0.582514 |
[
"MIT"
] |
bbtarzan12/Unity-Procedural-2D-Tile-Game
|
Assets/Scripts/Controller/CameraController.cs
| 915 |
C#
|
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using P0_AndresOrozco;
namespace P0_AndresOrozco.Migrations
{
[DbContext(typeof(StoreAppDBContext))]
[Migration("20201229212113_m0")]
partial class m0
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("P0_AndresOrozco.Customer", b =>
{
b.Property<string>("UserName")
.HasColumnType("nvarchar(450)");
b.Property<string>("FName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LName")
.HasColumnType("nvarchar(max)");
b.HasKey("UserName");
b.ToTable("customers");
});
modelBuilder.Entity("P0_AndresOrozco.Inventory", b =>
{
b.Property<Guid>("InventoryId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ProductName")
.HasColumnType("nvarchar(max)");
b.Property<int>("Quantity")
.HasColumnType("int");
b.Property<int>("StoreId")
.HasColumnType("int");
b.HasKey("InventoryId");
b.ToTable("inventory");
});
modelBuilder.Entity("P0_AndresOrozco.OrderHistory", b =>
{
b.Property<Guid>("OrderId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("CommonId")
.HasColumnType("uniqueidentifier");
b.Property<string>("ProductName")
.HasColumnType("nvarchar(max)");
b.Property<double>("ProductPrice")
.HasColumnType("float");
b.Property<int>("ProductQuantity")
.HasColumnType("int");
b.Property<int>("StoreId")
.HasColumnType("int");
b.Property<DateTime>("Timestamp")
.HasColumnType("datetime2");
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("OrderId");
b.ToTable("orderHistory");
});
modelBuilder.Entity("P0_AndresOrozco.Product", b =>
{
b.Property<string>("ProductName")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProductDescription")
.HasColumnType("nvarchar(max)");
b.Property<double>("ProductPrice")
.HasColumnType("float");
b.HasKey("ProductName");
b.ToTable("products");
});
modelBuilder.Entity("P0_AndresOrozco.Store", b =>
{
b.Property<int>("StoreId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<string>("StoreName")
.HasColumnType("nvarchar(max)");
b.HasKey("StoreId");
b.ToTable("stores");
});
#pragma warning restore 612, 618
}
}
}
| 33.751938 | 125 | 0.491272 |
[
"MIT"
] |
12142020-dotnet-uta/AndresOrozcoRepo1
|
P0_Store_Application/P0_AndresOrozco/Migrations/20201229212113_m0.Designer.cs
| 4,356 |
C#
|
using Data.Common.Test.Domain.Article;
using Data.Common.Test.Domain.Category;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace Data.Adapter.Sqlite.Test
{
/*
* 多表分组查询测试
*/
public class MultiTableGroupingTests : BaseTest
{
private readonly IArticleRepository _repository;
public MultiTableGroupingTests(ITestOutputHelper output) : base(output)
{
_repository = _serviceProvider.GetService<IArticleRepository>();
}
[Fact]
public void Test()
{
var sql = _repository.Find().LeftJoin<CategoryEntity>(m => m.T1.CategoryId == m.T2.Id)
.GroupBy(m => new { name = m.T2.Name.Substring(1, 3) })
.Select(m => new
{
Sum = m.Sum(x => x.T1.Id),
Count = m.Count(),
name1 = m.Key.name
})
.ToListSql();
Assert.Equal("SELECT SUM(T1.[Id]) AS [Sum],COUNT(0) AS [Count],SUBSTR(T2.[Name],2,3) AS [name1] FROM [Article] AS T1 LEFT JOIN [MyCategory] AS T2 ON T1.[CategoryId] = T2.[Id] WHERE T1.[Deleted] = 0 GROUP BY SUBSTR(T2.[Name],2,3)", sql);
}
[Fact]
public void Test1()
{
var sql = _repository.Find().LeftJoin<CategoryEntity>(m => m.T1.CategoryId == m.T2.Id)
.GroupBy(m => new
{
m.T2.Name
})
.Having(m => m.Sum(x => x.T1.Id) > 5)
.OrderBy(m => m.Sum(x => x.T1.Id))
.OrderByDescending(m => m.Key.Name.Substring(2))
.Select(m => new
{
Sum = m.Sum(x => x.T1.Id),
Name = m.Key.Name.Substring(5)
})
.ToListSql();
Assert.Equal("SELECT SUM(T1.[Id]) AS [Sum],SUBSTR(T2.[Name],6) AS [Name] FROM [Article] AS T1 LEFT JOIN [MyCategory] AS T2 ON T1.[CategoryId] = T2.[Id] WHERE T1.[Deleted] = 0 GROUP BY T2.[Name] HAVING SUM(T1.[Id]) > @P1 ORDER BY SUM(T1.[Id]) ASC, SUBSTR(T2.[Name],3) DESC", sql);
}
[Fact]
public void Test2()
{
var sql = _repository.Find().LeftJoin<CategoryEntity>(m => m.T1.CategoryId == m.T2.Id)
.GroupBy(m => new
{
m.T2.Name.Length
})
.Having(m => m.Sum(x => x.T1.Id) > 5)
.OrderBy(m => m.Sum(x => x.T1.Id))
.Select(m => new
{
Sum = m.Sum(x => x.T1.Id),
m.Key.Length
})
.ToListSql();
Assert.Equal("SELECT SUM(T1.[Id]) AS [Sum],LENGTH(T2.[Name]) AS [Length] FROM [Article] AS T1 LEFT JOIN [MyCategory] AS T2 ON T1.[CategoryId] = T2.[Id] WHERE T1.[Deleted] = 0 GROUP BY LENGTH(T2.[Name]) HAVING SUM(T1.[Id]) > @P1 ORDER BY SUM(T1.[Id]) ASC", sql);
}
}
}
| 38 | 291 | 0.490007 |
[
"MIT"
] |
17MKH/Mkh
|
test/02_Data/Data.Adapter.Sqlite.Test/MultiTableGroupingTests.cs
| 3,020 |
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("NGS_PolyCounter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NGS_PolyCounter")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ba22b440-be94-494c-b47a-7c99cc71e808")]
// 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.783784 | 84 | 0.748927 |
[
"MIT"
] |
GDanovski/NGS_PolyCounter
|
NGS_PolyCounter/Properties/AssemblyInfo.cs
| 1,401 |
C#
|
using System.Drawing;
namespace XDesignerGUI
{
public class SimpleRectangleTransform : TransformBase
{
private bool bolEnable = true;
private bool bolVisible = true;
private object objTag = null;
private int intPageIndex = 0;
private int intFlag2 = 0;
private int intFlag3 = 0;
protected RectangleF mySourceRect = RectangleF.Empty;
protected RectangleF myDescRect = RectangleF.Empty;
public bool Enable
{
get
{
return bolEnable;
}
set
{
bolEnable = value;
}
}
public bool Visible
{
get
{
return bolVisible;
}
set
{
bolVisible = value;
}
}
public object Tag
{
get
{
return objTag;
}
set
{
objTag = value;
}
}
public int PageIndex
{
get
{
return intPageIndex;
}
set
{
intPageIndex = value;
}
}
public int Flag2
{
get
{
return intFlag2;
}
set
{
intFlag2 = value;
}
}
public int Flag3
{
get
{
return intFlag3;
}
set
{
intFlag3 = value;
}
}
public RectangleF SourceRectF
{
get
{
return mySourceRect;
}
set
{
mySourceRect = value;
}
}
public Rectangle SourceRect
{
get
{
return new Rectangle((int)mySourceRect.Left, (int)mySourceRect.Top, (int)mySourceRect.Width, (int)mySourceRect.Height);
}
set
{
mySourceRect = new RectangleF(value.Left, value.Top, value.Width, value.Height);
}
}
public RectangleF DescRectF
{
get
{
return myDescRect;
}
set
{
myDescRect = value;
}
}
public Rectangle DescRect
{
get
{
return new Rectangle((int)myDescRect.Left, (int)myDescRect.Top, (int)myDescRect.Width, (int)myDescRect.Height);
}
set
{
myDescRect = new RectangleF(value.Left, value.Top, value.Width, value.Height);
}
}
public Point OffsetPosition => new Point((int)(myDescRect.Left - mySourceRect.Left), (int)(myDescRect.Top - mySourceRect.Top));
public PointF OffsetPositionF => new PointF(myDescRect.Left - mySourceRect.Left, myDescRect.Top - mySourceRect.Top);
public float XZoomRate
{
get
{
float width = myDescRect.Width;
return width / mySourceRect.Width;
}
}
public float YZoomRate
{
get
{
float height = myDescRect.Height;
return height / mySourceRect.Height;
}
}
public SimpleRectangleTransform()
{
}
public SimpleRectangleTransform(RectangleF vSourceRect, RectangleF vDescRect)
{
mySourceRect = vSourceRect;
myDescRect = vDescRect;
}
public override bool ContainsSourcePoint(int x, int y)
{
return mySourceRect.Contains(x, y);
}
public override Point TransformPoint(int x, int y)
{
PointF pointF = TransformPointF(x, y);
return new Point((int)pointF.X, (int)pointF.Y);
}
public override PointF TransformPointF(float x, float y)
{
x -= mySourceRect.Left;
y -= mySourceRect.Top;
if (mySourceRect.Width != myDescRect.Width && mySourceRect.Width != 0f)
{
x = x * myDescRect.Width / mySourceRect.Width;
}
if (mySourceRect.Height != myDescRect.Height && mySourceRect.Height != 0f)
{
y = y * myDescRect.Height / mySourceRect.Height;
}
return new PointF(x + (float)DescRect.Left, y + (float)DescRect.Top);
}
public override Size TransformSize(int w, int h)
{
if (mySourceRect.Width != myDescRect.Width && mySourceRect.Width != 0f)
{
w = (int)((float)w * myDescRect.Width / mySourceRect.Width);
}
if (mySourceRect.Height != myDescRect.Height && mySourceRect.Height != 0f)
{
h = (int)((float)h * myDescRect.Height / mySourceRect.Height);
}
return new Size(w, h);
}
public override SizeF TransformSizeF(float w, float h)
{
if (mySourceRect.Width != myDescRect.Width && mySourceRect.Width != 0f)
{
w = w * myDescRect.Width / mySourceRect.Width;
}
if (mySourceRect.Height != myDescRect.Height && mySourceRect.Height != 0f)
{
h = h * myDescRect.Height / mySourceRect.Height;
}
return new SizeF(w, h);
}
public override Point UnTransformPoint(Point p)
{
PointF pointF = UnTransformPointF(p.X, p.Y);
return new Point((int)pointF.X, (int)pointF.Y);
}
public override Point UnTransformPoint(int x, int y)
{
PointF pointF = UnTransformPointF(x, y);
return new Point((int)pointF.X, (int)pointF.Y);
}
public override PointF UnTransformPointF(float x, float y)
{
x -= (float)DescRect.Left;
y -= (float)DescRect.Top;
if (mySourceRect.Width != myDescRect.Width && myDescRect.Width != 0f)
{
x = x * mySourceRect.Width / myDescRect.Width;
}
if (mySourceRect.Height != myDescRect.Height && myDescRect.Height != 0f)
{
y = y * mySourceRect.Height / myDescRect.Height;
}
return new PointF(x + (float)SourceRect.Left, y + (float)SourceRect.Top);
}
public override Size UnTransformSize(int w, int h)
{
if (mySourceRect.Width != myDescRect.Width && myDescRect.Width != 0f)
{
w = (int)((float)w * mySourceRect.Width / myDescRect.Width);
}
if (mySourceRect.Height != myDescRect.Height && myDescRect.Height != 0f)
{
h = (int)((float)h * mySourceRect.Height / myDescRect.Height);
}
return new Size(w, h);
}
public override SizeF UnTransformSizeF(float w, float h)
{
if (mySourceRect.Width != myDescRect.Width && myDescRect.Width != 0f)
{
w = w * mySourceRect.Width / myDescRect.Width;
}
if (mySourceRect.Height != myDescRect.Height && myDescRect.Height != 0f)
{
h = h * mySourceRect.Height / myDescRect.Height;
}
return new SizeF(w, h);
}
}
}
| 19.953737 | 129 | 0.639914 |
[
"MIT"
] |
h1213159982/HDF
|
Example/WinForm/Editor/ZYTextDocumentLib/XDesignerGUI/SimpleRectangleTransform.cs
| 5,607 |
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CxSolution.CxRouRou.Expands;
using CxSolution.CxRouRou.Net.Sockets;
using CxSolution.CxRouRou.Net.Sockets.Udp;
namespace CxSolution.CxRouRouTest.Net.Sockets.Udp
{
/// <summary>
/// 网络测试(Udp)
/// </summary>
public class CxNetTest : CxTestBase
{
/// <summary>
/// 初始化
/// </summary>
/// <param name="testName"></param>
public CxNetTest(string testName) : base(testName)
{
}
/// <summary>
/// 释放非托管资源
/// </summary>
public override void Dispose()
{
throw new NotImplementedException();
}
/// <summary>
/// 测试内容
/// </summary>
/// <returns></returns>
public override bool Test()
{
var result = true;
string localHost = "127.0.0.1";
ushort serverPort = 60001;
ushort clientPort = 60002;
var serverNet = new TestNet();
serverNet.StartListen(serverPort);
var serverTestBytes = CxArray.CreateRandomByte(1000);
var serverTestMsg = new CxMsgPacket(1024);
serverTestMsg.Push(serverTestBytes);
var clientNet = new TestNet();
clientNet.StartListen(clientPort);
var clientTestBytes = CxArray.CreateRandomByte(1000);
var clientTestMsg = new CxMsgPacket(1024);
clientTestMsg.Push(clientTestBytes);
var testCount = 0;
var testMaxCount = 5;
var isCheckOver = false;
serverNet.OnReceiveDataAction = (endPoint, data) =>
{
PrintL("收到客户端数据 Length:{0}", data.Length);
var isOk = clientTestBytes.EqualsEx(data);
result = isOk ? result : isOk;
PrintL("数据校验结果:{0}", isOk);
Thread.Sleep(1000);
PrintL("向客户端发送数据 Length:{0}", serverTestMsg.Length);
clientNet.SendMsgPacket(endPoint, serverTestMsg);
};
clientNet.OnReceiveDataAction = (endPoint, data) =>
{
PrintL("收到服务器数据 Length:{0}", data.Length);
var isOk = clientTestBytes.EqualsEx(data);
result = isOk ? result : isOk;
PrintL("数据校验结果:{0}", isOk);
if (++testCount >= testMaxCount)
{
isCheckOver = true;
return;
}
Thread.Sleep(1000);
PrintL("向服务器发送数据 Length:{0}", clientTestMsg.Length);
clientNet.SendMsgPacket(endPoint, clientTestMsg);
};
PrintL("向服务器发送数据 Length:{0}", clientTestMsg.Length);
clientNet.SendMsgPacket(localHost, serverPort, clientTestMsg);
Stopwatch sw = new Stopwatch();
sw.Start();
while (true)
{
if (isCheckOver)
{
break;
}
if (sw.ElapsedMilliseconds > 20 * 1000)
{
PrintL("测试超时,视为失败");
break;
}
Thread.Sleep(1);
}
return result;
}
class TestNet : CxNet
{
public Action<EndPoint, byte[]> OnReceiveDataAction;
public TestNet()
{
}
protected override void OnReceiveMsgPacket(EndPoint endPoint, CxMsgPacket msgPacket)
{
base.OnReceiveMsgPacket(endPoint, msgPacket);
OnReceiveDataAction?.Invoke(endPoint, msgPacket.Pop_bytes());
}
}
}
}
| 30.023256 | 96 | 0.513555 |
[
"MIT"
] |
zengliugen/CxSolution
|
CxRouRouTest/Net/Sockets/Udp/CxNetTest.cs
| 4,027 |
C#
|
using Foundation;
using UIKit;
namespace SharpConstraintLayout.Maui.Native.Example
{
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
//protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
public override UIWindow? Window
{
get;
set;
}
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// create a new window instance based on the screen size
Window = new UIWindow(UIScreen.MainScreen.Bounds);
// create a UIViewController with a single UILabel
var vc = new MainController(Window);
Window.RootViewController = vc;
// make the window visible
Window.MakeKeyAndVisible();
return true;
}
}
}
| 27.5625 | 101 | 0.619048 |
[
"Apache-2.0"
] |
xtuzy/SharpConstraintLayout
|
SharpConstraintLayout.Maui.Native.Example/Platforms/MacCatalyst/AppDelegate.cs
| 884 |
C#
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ContactCenterInsights.V1.Snippets
{
// [START contactcenterinsights_v1_generated_ContactCenterInsights_GetView_async_flattened]
using Google.Cloud.ContactCenterInsights.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedContactCenterInsightsClientSnippets
{
/// <summary>Snippet for GetViewAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetViewAsync()
{
// Create client
ContactCenterInsightsClient contactCenterInsightsClient = await ContactCenterInsightsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/views/[VIEW]";
// Make the request
View response = await contactCenterInsightsClient.GetViewAsync(name);
}
}
// [END contactcenterinsights_v1_generated_ContactCenterInsights_GetView_async_flattened]
}
| 41.857143 | 118 | 0.718999 |
[
"Apache-2.0"
] |
AlexandrTrf/google-cloud-dotnet
|
apis/Google.Cloud.ContactCenterInsights.V1/Google.Cloud.ContactCenterInsights.V1.GeneratedSnippets/ContactCenterInsightsClient.GetViewAsyncSnippet.g.cs
| 1,758 |
C#
|
#region License
//
// MIT License
//
// CoiniumServ - Crypto Currency Mining Pool Server Software
//
// Copyright (C) 2013 - 2017, CoiniumServ Project
// Copyright (C) 2017 - 2021 The Merit Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#endregion
namespace CoiniumServ.Configuration
{
public interface IConfig
{
bool Valid { get; }
}
}
| 39.918919 | 85 | 0.708192 |
[
"MIT"
] |
meritlabs/CoiniumServ
|
src/CoiniumServ/Configuration/IConfig.cs
| 1,479 |
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
// ReSharper disable UnassignedGetOnlyAutoProperty
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable MemberCanBePrivate.Local
namespace Microsoft.EntityFrameworkCore
{
public class SqlServerDatabaseCreatorTest
{
[ConditionalFact]
public Task Create_checks_for_existence_and_retries_if_no_proccess_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(233, async: false);
}
[ConditionalFact]
public Task Create_checks_for_existence_and_retries_if_timeout_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(-2, async: false);
}
[ConditionalFact]
public Task Create_checks_for_existence_and_retries_if_cannot_open_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(4060, async: false);
}
[ConditionalFact]
public Task Create_checks_for_existence_and_retries_if_cannot_attach_file_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(1832, async: false);
}
[ConditionalFact]
public Task Create_checks_for_existence_and_retries_if_cannot_open_file_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(5120, async: false);
}
[ConditionalFact]
public Task CreateAsync_checks_for_existence_and_retries_if_no_proccess_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(233, async: true);
}
[ConditionalFact]
public Task CreateAsync_checks_for_existence_and_retries_if_timeout_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(-2, async: true);
}
[ConditionalFact]
public Task CreateAsync_checks_for_existence_and_retries_if_cannot_open_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(4060, async: true);
}
[ConditionalFact]
public Task CreateAsync_checks_for_existence_and_retries_if_cannot_attach_file_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(1832, async: true);
}
[ConditionalFact]
public Task CreateAsync_checks_for_existence_and_retries_if_cannot_open_file_until_it_passes()
{
return Create_checks_for_existence_and_retries_until_it_passes(5120, async: true);
}
private async Task Create_checks_for_existence_and_retries_until_it_passes(int errorNumber, bool async)
{
var customServices = new ServiceCollection()
.AddScoped<ISqlServerConnection, FakeSqlServerConnection>()
.AddScoped<IRelationalCommandBuilderFactory, FakeRelationalCommandBuilderFactory>()
.AddScoped<IExecutionStrategyFactory, ExecutionStrategyFactory>();
var contextServices = SqlServerTestHelpers.Instance.CreateContextServices(customServices);
var connection = (FakeSqlServerConnection)contextServices.GetRequiredService<ISqlServerConnection>();
connection.ErrorNumber = errorNumber;
connection.FailureCount = 2;
var creator = (SqlServerDatabaseCreator)contextServices.GetRequiredService<IRelationalDatabaseCreator>();
creator.RetryDelay = TimeSpan.FromMilliseconds(1);
creator.RetryTimeout = TimeSpan.FromMinutes(5);
if (async)
{
await creator.CreateAsync();
}
else
{
creator.Create();
}
Assert.Equal(2, connection.OpenCount);
}
[ConditionalFact]
public Task Create_checks_for_existence_and_ultimately_gives_up_waiting()
{
return Create_checks_for_existence_and_ultimately_gives_up_waiting_test(async: false);
}
[ConditionalFact]
public Task CreateAsync_checks_for_existence_and_ultimately_gives_up_waiting()
{
return Create_checks_for_existence_and_ultimately_gives_up_waiting_test(async: true);
}
private async Task Create_checks_for_existence_and_ultimately_gives_up_waiting_test(bool async)
{
var customServices = new ServiceCollection()
.AddScoped<ISqlServerConnection, FakeSqlServerConnection>()
.AddScoped<IRelationalCommandBuilderFactory, FakeRelationalCommandBuilderFactory>()
.AddScoped<IExecutionStrategyFactory, ExecutionStrategyFactory>();
var contextServices = SqlServerTestHelpers.Instance.CreateContextServices(customServices);
var connection = (FakeSqlServerConnection)contextServices.GetRequiredService<ISqlServerConnection>();
connection.ErrorNumber = 233;
connection.FailureCount = 100;
connection.FailDelay = 50;
var creator = (SqlServerDatabaseCreator)contextServices.GetRequiredService<IRelationalDatabaseCreator>();
creator.RetryDelay = TimeSpan.FromMilliseconds(5);
creator.RetryTimeout = TimeSpan.FromMilliseconds(100);
if (async)
{
await Assert.ThrowsAsync<SqlException>(() => creator.CreateAsync());
}
else
{
Assert.Throws<SqlException>(() => creator.Create());
}
}
private class FakeSqlServerConnection : SqlServerConnection
{
private readonly IDbContextOptions _options;
public FakeSqlServerConnection(IDbContextOptions options, RelationalConnectionDependencies dependencies)
: base(dependencies)
{
_options = options;
}
public int ErrorNumber { get; set; }
public int FailureCount { get; set; }
public int FailDelay { get; set; }
public int OpenCount { get; set; }
public override bool Open(bool errorsExpected = false)
{
if (++OpenCount < FailureCount)
{
Thread.Sleep(FailDelay);
throw SqlExceptionFactory.CreateSqlException(ErrorNumber);
}
return true;
}
public override async Task<bool> OpenAsync(CancellationToken cancellationToken, bool errorsExpected = false)
{
if (++OpenCount < FailureCount)
{
await Task.Delay(FailDelay, cancellationToken);
throw SqlExceptionFactory.CreateSqlException(ErrorNumber);
}
return await Task.FromResult(true);
}
public override ISqlServerConnection CreateMasterConnection()
=> new FakeSqlServerConnection(_options, Dependencies);
}
private class FakeRelationalCommandBuilderFactory : IRelationalCommandBuilderFactory
{
public IRelationalCommandBuilder Create()
=> new FakeRelationalCommandBuilder();
}
private class FakeRelationalCommandBuilder : IRelationalCommandBuilder
{
private readonly List<IRelationalParameter> _parameters = new List<IRelationalParameter>();
public IndentedStringBuilder Instance { get; } = new IndentedStringBuilder();
public IReadOnlyList<IRelationalParameter> Parameters
=> _parameters;
public IRelationalCommandBuilder AddParameter(IRelationalParameter parameter)
{
_parameters.Add(parameter);
return this;
}
public IRelationalTypeMappingSource TypeMappingSource
=> null;
public IRelationalCommand Build()
=> new FakeRelationalCommand();
public IRelationalCommandBuilder Append(string value)
{
Instance.Append(value);
return this;
}
public IRelationalCommandBuilder AppendLine()
{
Instance.AppendLine();
return this;
}
public IRelationalCommandBuilder IncrementIndent()
{
Instance.IncrementIndent();
return this;
}
public IRelationalCommandBuilder DecrementIndent()
{
Instance.DecrementIndent();
return this;
}
public int CommandTextLength
=> Instance.Length;
}
private class FakeRelationalCommand : IRelationalCommand
{
public string CommandText { get; }
public IReadOnlyList<IRelationalParameter> Parameters { get; }
public IReadOnlyDictionary<string, object> ParameterValues
=> throw new NotImplementedException();
public int ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
{
return 0;
}
public Task<int> ExecuteNonQueryAsync(
RelationalCommandParameterObject parameterObject,
CancellationToken cancellationToken = default)
=> Task.FromResult(0);
public RelationalDataReader ExecuteReader(RelationalCommandParameterObject parameterObject)
{
throw new NotImplementedException();
}
public Task<RelationalDataReader> ExecuteReaderAsync(
RelationalCommandParameterObject parameterObject,
CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public object ExecuteScalar(RelationalCommandParameterObject parameterObject)
{
throw new NotImplementedException();
}
public Task<object> ExecuteScalarAsync(
RelationalCommandParameterObject parameterObject,
CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
}
}
}
| 36.455446 | 120 | 0.649013 |
[
"Apache-2.0"
] |
0b01/efcore
|
test/EFCore.SqlServer.Tests/SqlServerDatabaseCreatorTest.cs
| 11,046 |
C#
|
using Reactive.Bindings;
using System;
using System.ComponentModel;
namespace SandBeige.MealRecipes.Composition.Settings {
/// <summary>
/// ウィンドウ状態
/// </summary>
public interface IWindowState : INotifyPropertyChanged, IDisposable {
/// <summary>
/// 幅
/// </summary>
IReactiveProperty<double> Width {
get;
set;
}
/// <summary>
/// 高さ
/// </summary>
IReactiveProperty<double> Height {
get;
set;
}
/// <summary>
/// 縦位置
/// </summary>
IReactiveProperty<double> Top {
get;
set;
}
/// <summary>
/// 横位置
/// </summary>
IReactiveProperty<double> Left {
get;
set;
}
}
}
| 14.222222 | 70 | 0.601563 |
[
"MIT"
] |
southernwind/Gohan
|
MealRecipes.Composition/Settings/IWindowState.cs
| 672 |
C#
|
namespace Spect.Net.SpectrumEmu.Abstraction.Discovery
{
/// <summary>
/// This interface defines the operations that support debugging the call stack
/// </summary>
public interface IStackDebugSupport
{
/// <summary>
/// Resets the debug support
/// </summary>
void Reset();
/// <summary>
/// Records a stack pointer manipulation event
/// </summary>
/// <param name="ev">Event information</param>
void RecordStackPointerManipulationEvent(StackPointerManipulationEvent ev);
/// <summary>
/// Records a stack content manipulation event
/// </summary>
/// <param name="ev">Event information</param>
void RecordStackContentManipulationEvent(StackContentManipulationEvent ev);
/// <summary>
/// Checks if the Step-Out stack contains any information
/// </summary>
/// <returns></returns>
bool HasStepOutInfo();
/// <summary>
/// The depth of the Step-Out stack
/// </summary>
int StepOutStackDepth { get; }
/// <summary>
/// Clears the content of the Step-Out stack
/// </summary>
void ClearStepOutStack();
/// <summary>
/// Pushes the specified return address to the Step-Out stack
/// </summary>
/// <param name="address"></param>
void PushStepOutAddress(ushort address);
/// <summary>
/// Pops a Step-Out return point address from the stack
/// </summary>
/// <returns>Address popped from the stack</returns>
/// <returns>Zeor, if the Step-Out stack is empty</returns>
ushort PopStepOutAddress();
/// <summary>
/// Indicates that the last instruction executed by the CPU was a CALL
/// </summary>
bool CallExecuted { get; set; }
/// <summary>
/// Indicates that the last instruction executed by the CPU was a RET
/// </summary>
bool RetExecuted { get; set; }
/// <summary>
/// Gets the last popped Step-Out address
/// </summary>
ushort? StepOutAddress { get; set; }
}
}
| 31.942029 | 83 | 0.571688 |
[
"MIT"
] |
Dotneteer/spectnetide
|
Core/Spect.Net.SpectrumEmu/Abstraction/Discovery/IStackDebugSupport.cs
| 2,206 |
C#
|
namespace SlackNet.Events
{
/// <summary>
/// Sent when the purpose for a private group is changed.
/// </summary>
public class GroupPurpose : MessageEvent
{
public string Purpose { get; set; }
}
}
| 23 | 61 | 0.608696 |
[
"MIT"
] |
Cereal-Killa/SlackNet
|
SlackNet/Events/Messages/GroupPurpose.cs
| 232 |
C#
|
using System.Collections;
using System.Reflection;
#pragma warning disable CS8618,CA1822
namespace FastEndpoints.Security;
/// <summary>
/// inherit from this class and define your applications permissions as <c>public const string</c>
/// <para>
/// <code>
/// public const string Inventory_Create_Item = "100";
/// public const string Inventory_Retrieve_Item = "101";
/// public const string Inventory_Update_Item = "102";
/// public const string Inventory_Delete_Item = "103";
/// </code>
/// </para>
/// </summary>
public abstract class Permissions : IEnumerable<(string PermissionName, string PermissionCode)>
{
private static bool isInitialized;
private static IEnumerable<(string PermissionName, string PermissionCode)> permissions;
protected Permissions()
{
if (!isInitialized)
{
isInitialized = true;
permissions = GetType()
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(f => (f.Name, (string)f.GetValue(this)!))
.ToArray()!;
}
}
/// <summary>
/// gets a list of permission names for the given list of permission codes
/// </summary>
/// <param name="codes">the permission codes to get the permission names for</param>
public IEnumerable<string> NamesFor(IEnumerable<string> codes)
{
return permissions
.Where(f => codes.Contains(f.PermissionCode))
.Select(f => f.PermissionName);
}
/// <summary>
/// get a list of permission codes for a given list of permission names
/// </summary>
/// <param name="names">the permission names to get the codes for</param>
public IEnumerable<string> CodesFor(IEnumerable<string> names)
{
return permissions
.Where(f => names.Contains(f.PermissionName))
.Select(f => f.PermissionCode);
}
/// <summary>
/// get the permission tuple using it's name. returns null if not found
/// </summary>
/// <param name="permissionName">name of the permission</param>
public (string PermissionName, string PermissionCode)? PermissionFromName(string permissionName)
=> permissions.SingleOrDefault(p => p.PermissionName == permissionName);
/// <summary>
/// get the permission tuple using it's code. returns null if not found
/// </summary>
/// <param name="permissionCode">code of the permission to get</param>
public (string PermissionName, string PermissionCode)? PermissionFromCode(string permissionCode)
=> permissions.SingleOrDefault(p => p.PermissionCode == permissionCode);
/// <summary>
/// get a list of all permission names
/// </summary>
public IEnumerable<string> AllNames()
=> permissions.Select(f => f.PermissionName);
/// <summary>
/// get a list of all permission codes
/// </summary>
public IEnumerable<string> AllCodes()
=> permissions.Select(f => f.PermissionCode);
/// <inheritdoc/>
public IEnumerator<(string PermissionName, string PermissionCode)> GetEnumerator()
{
return permissions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
| 34.37234 | 100 | 0.655215 |
[
"MIT"
] |
Allann/FastEndpoints
|
Src/Security/Permissions.cs
| 3,233 |
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.EntityFrameworkCore.Query
{
public class FromSqlSprocQuerySqlServerTest : FromSqlSprocQueryTestBase<NorthwindQuerySqlServerFixture<NoopModelCustomizer>>
{
public FromSqlSprocQuerySqlServerTest(
NorthwindQuerySqlServerFixture<NoopModelCustomizer> fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
fixture.TestSqlLoggerFactory.Clear();
}
public override void From_sql_queryable_stored_procedure()
{
base.From_sql_queryable_stored_procedure();
Assert.Equal(
"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_stored_procedure_projection()
{
base.From_sql_queryable_stored_procedure_projection();
Assert.Equal(
"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_stored_procedure_with_parameter()
{
base.From_sql_queryable_stored_procedure_with_parameter();
Assert.Equal(
@"@p0='ALFKI' (Size = 4000)
[dbo].[CustOrderHist] @CustomerID = @p0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void From_sql_queryable_stored_procedure_reprojection()
{
base.From_sql_queryable_stored_procedure_reprojection();
Assert.Equal(
"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_stored_procedure_composed()
{
base.From_sql_queryable_stored_procedure_composed();
Assert.Equal(
"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_stored_procedure_with_parameter_composed()
{
base.From_sql_queryable_stored_procedure_with_parameter_composed();
Assert.Equal(
@"@p0='ALFKI' (Size = 4000)
[dbo].[CustOrderHist] @CustomerID = @p0",
Sql,
ignoreLineEndingDifferences: true);
}
public override void From_sql_queryable_stored_procedure_take()
{
base.From_sql_queryable_stored_procedure_take();
Assert.Equal(
"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_stored_procedure_min()
{
base.From_sql_queryable_stored_procedure_min();
Assert.Equal(
"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_with_multiple_stored_procedures()
{
base.From_sql_queryable_with_multiple_stored_procedures();
Assert.StartsWith(
@"[dbo].[Ten Most Expensive Products]" + EOL +
EOL +
@"[dbo].[Ten Most Expensive Products]" + EOL +
EOL +
@"[dbo].[Ten Most Expensive Products]",
Sql);
}
public override void From_sql_queryable_stored_procedure_and_select()
{
base.From_sql_queryable_stored_procedure_and_select();
Assert.StartsWith(
@"[dbo].[Ten Most Expensive Products]" + EOL +
EOL +
@"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock]" + EOL +
@"FROM (" + EOL +
@" SELECT * FROM ""Products""" + EOL +
@") AS [p]" + EOL +
EOL +
@"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock]" + EOL +
@"FROM (" + EOL +
@" SELECT * FROM ""Products""" + EOL +
@") AS [p]",
Sql);
}
public override void From_sql_queryable_select_and_stored_procedure()
{
base.From_sql_queryable_select_and_stored_procedure();
Assert.StartsWith(
@"SELECT [p].[ProductID], [p].[Discontinued], [p].[ProductName], [p].[SupplierID], [p].[UnitPrice], [p].[UnitsInStock]" + EOL +
@"FROM (" + EOL +
@" SELECT * FROM ""Products""" + EOL +
@") AS [p]" + EOL +
EOL +
@"[dbo].[Ten Most Expensive Products]" + EOL +
EOL +
@"[dbo].[Ten Most Expensive Products]",
Sql);
}
protected override string TenMostExpensiveProductsSproc => "[dbo].[Ten Most Expensive Products]";
protected override string CustomerOrderHistorySproc => "[dbo].[CustOrderHist] @CustomerID = {0}";
private static readonly string EOL = Environment.NewLine;
private string Sql => Fixture.TestSqlLoggerFactory.Sql;
}
}
| 34.727273 | 143 | 0.568811 |
[
"Apache-2.0"
] |
EasonDongH/EntityFrameworkCore
|
test/EFCore.SqlServer.FunctionalTests/Query/FromSqlSprocQuerySqlServerTest.cs
| 5,348 |
C#
|
using System.Collections.Generic;
namespace DropScript.Parsing
{
/// <summary>
/// リストを1つずつ読み取る機能と、巻き戻し機能を提供します。
/// </summary>
/// <typeparam name="T"></typeparam>
public class ListReader<T>
{
/// <summary>
/// 現在の要素を取得します。
/// </summary>
/// <value>現在のポインターが指し示す要素。存在しなければ <see langword="null"/>。</value>
public T? Current => pointer < List.Count ? List[pointer] : default;
/// <summary>
/// 対象とするリストを取得します。
/// </summary>
public List<T> List { get; }
/// <summary>
/// <see cref="ListReader"/> の新しいインスタンスを初期化します。
/// </summary>
/// <param name="list">対象とするリスト。</param>
public ListReader(List<T> list)
{
List = list;
}
/// <summary>
/// ポインターを次に進めます。
/// </summary>
public T? Next()
{
if (pointer < List.Count)
{
pointer++;
}
return Current;
}
/// <summary>
/// ポインターを前に戻します。
/// </summary>
/// <returns>戻した後のポインターが指し示す要素。存在しなければ <see langword="null"/>。</returns>
public T? Previous()
{
if (0 < pointer)
{
pointer--;
}
return Current;
}
/// <summary>
/// ポインターをコミットします。次に <see cref="Rollback"/> メソッドを呼び出すときにこのポインターまで戻します。
/// </summary>
public void Commit()
{
committedPointer = pointer;
}
/// <summary>
/// 前回コミットしたポインターまで戻します。
/// </summary>
public void Rollback()
{
committedPointer = pointer;
}
private int pointer;
private int committedPointer;
}
}
| 23.986667 | 80 | 0.465814 |
[
"MIT"
] |
Xeltica/DropScript
|
DropScript/Parsing/ListReader.cs
| 2,239 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using Newtonsoft.Json.Linq;
namespace Microsoft.Bot.Builder.Dialogs
{
/// <summary>
/// Creates a new prompt that asks the user to sign in using the Bot Frameworks Single Sign On (SSO)
/// service.
/// </summary>
/// <remarks>
/// The prompt will attempt to retrieve the users current token and if the user isn't signed in, it
/// will send them an `OAuthCard` containing a button they can press to signin. Depending on the
/// channel, the user will be sent through one of two possible signin flows:
///
/// - The automatic signin flow where once the user signs in and the SSO service will forward the bot
/// the users access token using either an `event` or `invoke` activity.
/// - The "magic code" flow where once the user signs in they will be prompted by the SSO
/// service to send the bot a six digit code confirming their identity. This code will be sent as a
/// standard `message` activity.
///
/// Both flows are automatically supported by the `OAuthPrompt` and the only thing you need to be
/// careful of is that you don't block the `event` and `invoke` activities that the prompt might
/// be waiting on.
///
/// <blockquote>
/// **Note**:
/// You should avoid persisting the access token with your bots other state. The Bot Frameworks
/// SSO service will securely store the token on your behalf. If you store it in your bots state
/// it could expire or be revoked in between turns.
///
/// When calling the prompt from within a waterfall step you should use the token within the step
/// following the prompt and then let the token go out of scope at the end of your function.
/// </blockquote>
///
/// ## Prompt Usage
///
/// When used with your bot's <see cref="DialogSet"/> you can simply add a new instance of the prompt as a named
/// dialog using <see cref="DialogSet.Add(Dialog)"/>. You can then start the prompt from a waterfall step using either
/// <see cref="DialogContext.BeginDialogAsync(string, object, CancellationToken)"/> or
/// <see cref="DialogContext.PromptAsync(string, PromptOptions, CancellationToken)"/>. The user
/// will be prompted to signin as needed and their access token will be passed as an argument to
/// the callers next waterfall step.
/// </remarks>
public class OAuthPrompt : Dialog
{
private const string PersistedOptions = "options";
private const string PersistedState = "state";
private const string PersistedExpires = "expires";
// regex to check if code supplied is a 6 digit numerical code (hence, a magic code).
private readonly Regex _magicCodeRegex = new Regex(@"(\d{6})");
private readonly OAuthPromptSettings _settings;
private readonly PromptValidator<TokenResponse> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="OAuthPrompt"/> class.
/// </summary>
/// <param name="dialogId">The ID to assign to this prompt.</param>
/// <param name="settings">Additional OAuth settings to use with this instance of the prompt.</param>
/// <param name="validator">Optional, a <see cref="PromptValidator{FoundChoice}"/> that contains additional,
/// custom validation for this prompt.</param>
/// <remarks>The value of <paramref name="dialogId"/> must be unique within the
/// <see cref="DialogSet"/> or <see cref="ComponentDialog"/> to which the prompt is added.</remarks>
public OAuthPrompt(string dialogId, OAuthPromptSettings settings, PromptValidator<TokenResponse> validator = null)
: base(dialogId)
{
if (string.IsNullOrWhiteSpace(dialogId))
{
throw new ArgumentNullException(nameof(dialogId));
}
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_validator = validator;
}
/// <summary>
/// Called when a prompt dialog is pushed onto the dialog stack and is being activated.
/// </summary>
/// <param name="dc">The dialog context for the current turn of the conversation.</param>
/// <param name="options">Optional, additional information to pass to the prompt being started.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <remarks>If the task is successful, the result indicates whether the prompt is still
/// active after the turn has been processed by the prompt.</remarks>
public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (dc == null)
{
throw new ArgumentNullException(nameof(dc));
}
if (options is CancellationToken)
{
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
PromptOptions opt = null;
if (options != null)
{
if (options is PromptOptions)
{
// Ensure prompts have input hint set
opt = options as PromptOptions;
if (opt.Prompt != null && string.IsNullOrEmpty(opt.Prompt.InputHint))
{
opt.Prompt.InputHint = InputHints.AcceptingInput;
}
if (opt.RetryPrompt != null && string.IsNullOrEmpty(opt.RetryPrompt.InputHint))
{
opt.RetryPrompt.InputHint = InputHints.AcceptingInput;
}
}
else
{
throw new ArgumentException(nameof(options));
}
}
// Initialize state
var timeout = _settings.Timeout ?? (int)TurnStateConstants.OAuthLoginTimeoutValue.TotalMilliseconds;
var state = dc.ActiveDialog.State;
state[PersistedOptions] = opt;
state[PersistedState] = new Dictionary<string, object>
{
{ Prompt<int>.AttemptCountKey, 0 },
};
state[PersistedExpires] = DateTime.Now.AddMilliseconds(timeout);
// Attempt to get the users token
if (!(dc.Context.Adapter is ICredentialTokenProvider adapter))
{
throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
}
var output = await adapter.GetUserTokenAsync(dc.Context, _settings.OAuthAppCredentials, _settings.ConnectionName, null, cancellationToken).ConfigureAwait(false);
if (output != null)
{
// Return token
return await dc.EndDialogAsync(output, cancellationToken).ConfigureAwait(false);
}
// Prompt user to login
await SendOAuthCardAsync(dc.Context, opt?.Prompt, cancellationToken).ConfigureAwait(false);
return EndOfTurn;
}
/// <summary>
/// Called when a prompt dialog is the active dialog and the user replied with a new activity.
/// </summary>
/// <param name="dc">The dialog context for the current turn of conversation.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <remarks>If the task is successful, the result indicates whether the dialog is still
/// active after the turn has been processed by the dialog.
/// <para>The prompt generally continues to receive the user's replies until it accepts the
/// user's reply as valid input for the prompt.</para></remarks>
public override async Task<DialogTurnResult> ContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
{
if (dc == null)
{
throw new ArgumentNullException(nameof(dc));
}
// Recognize token
var recognized = await RecognizeTokenAsync(dc.Context, cancellationToken).ConfigureAwait(false);
// Check for timeout
var state = dc.ActiveDialog.State;
var expires = (DateTime)state[PersistedExpires];
var isMessage = dc.Context.Activity.Type == ActivityTypes.Message;
var hasTimedOut = isMessage && (DateTime.Compare(DateTime.Now, expires) > 0);
if (hasTimedOut)
{
// if the token fetch request times out, complete the prompt with no result.
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var promptState = state[PersistedState].CastTo<IDictionary<string, object>>();
var promptOptions = state[PersistedOptions].CastTo<PromptOptions>();
// Increment attempt count
// Convert.ToInt32 For issue https://github.com/Microsoft/botbuilder-dotnet/issues/1859
promptState[Prompt<int>.AttemptCountKey] = Convert.ToInt32(promptState[Prompt<int>.AttemptCountKey]) + 1;
// Validate the return value
var isValid = false;
if (_validator != null)
{
var promptContext = new PromptValidatorContext<TokenResponse>(dc.Context, recognized, promptState, promptOptions);
isValid = await _validator(promptContext, cancellationToken).ConfigureAwait(false);
}
else if (recognized.Succeeded)
{
isValid = true;
}
// Return recognized value or re-prompt
if (isValid)
{
return await dc.EndDialogAsync(recognized.Value, cancellationToken).ConfigureAwait(false);
}
if (!dc.Context.Responded && isMessage && promptOptions?.RetryPrompt != null)
{
await dc.Context.SendActivityAsync(promptOptions.RetryPrompt, cancellationToken).ConfigureAwait(false);
}
return EndOfTurn;
}
/// <summary>
/// Attempts to get the user's token.
/// </summary>
/// <param name="turnContext">Context for the current turn of conversation with the user.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A task that represents the work queued to execute.</returns>
/// <remarks>If the task is successful and user already has a token or the user successfully signs in,
/// the result contains the user's token.</remarks>
public async Task<TokenResponse> GetUserTokenAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (!(turnContext.Adapter is ICredentialTokenProvider adapter))
{
throw new InvalidOperationException("OAuthPrompt.GetUserToken(): not supported by the current adapter");
}
return await adapter.GetUserTokenAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Signs out the user.
/// </summary>
/// <param name="turnContext">Context for the current turn of conversation with the user.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A task that represents the work queued to execute.</returns>
public async Task SignOutUserAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (!(turnContext.Adapter is ICredentialTokenProvider adapter))
{
throw new InvalidOperationException("OAuthPrompt.SignOutUser(): not supported by the current adapter");
}
// Sign out user
await adapter.SignOutUserAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, turnContext.Activity?.From?.Id, cancellationToken).ConfigureAwait(false);
}
private static bool IsTokenResponseEvent(ITurnContext turnContext)
{
var activity = turnContext.Activity;
return activity.Type == ActivityTypes.Event && activity.Name == "tokens/response";
}
private static bool IsTeamsVerificationInvoke(ITurnContext turnContext)
{
var activity = turnContext.Activity;
return activity.Type == ActivityTypes.Invoke && activity.Name == "signin/verifyState";
}
private static bool ChannelSupportsOAuthCard(string channelId)
{
switch (channelId)
{
case Channels.Msteams:
case Channels.Cortana:
case Channels.Skype:
case Channels.Skypeforbusiness:
return false;
}
return true;
}
private async Task SendOAuthCardAsync(ITurnContext turnContext, IMessageActivity prompt, CancellationToken cancellationToken = default(CancellationToken))
{
BotAssert.ContextNotNull(turnContext);
if (!(turnContext.Adapter is ICredentialTokenProvider adapter))
{
throw new InvalidOperationException("OAuthPrompt.Prompt(): not supported by the current adapter");
}
// Ensure prompt initialized
if (prompt == null)
{
prompt = Activity.CreateMessageActivity();
}
if (prompt.Attachments == null)
{
prompt.Attachments = new List<Attachment>();
}
// Append appropriate card if missing
if (!ChannelSupportsOAuthCard(turnContext.Activity.ChannelId))
{
if (!prompt.Attachments.Any(a => a.Content is SigninCard))
{
var link = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
prompt.Attachments.Add(new Attachment
{
ContentType = SigninCard.ContentType,
Content = new SigninCard
{
Text = _settings.Text,
Buttons = new[]
{
new CardAction
{
Title = _settings.Title,
Value = link,
Type = ActionTypes.Signin,
},
},
},
});
}
}
else if (!prompt.Attachments.Any(a => a.Content is OAuthCard))
{
var cardActionType = ActionTypes.Signin;
string signInLink = null;
if (turnContext.Activity.IsFromStreamingConnection())
{
signInLink = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
}
else if (turnContext.TurnState.Get<ClaimsIdentity>("BotIdentity") is ClaimsIdentity botIdentity && SkillValidation.IsSkillClaim(botIdentity.Claims))
{
// Force magic code for Skills (to be addressed in R8)
signInLink = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
cardActionType = ActionTypes.OpenUrl;
}
prompt.Attachments.Add(new Attachment
{
ContentType = OAuthCard.ContentType,
Content = new OAuthCard
{
Text = _settings.Text,
ConnectionName = _settings.ConnectionName,
Buttons = new[]
{
new CardAction
{
Title = _settings.Title,
Text = _settings.Text,
Type = cardActionType,
Value = signInLink
}
}
}
});
}
// Add the login timeout specified in OAuthPromptSettings to TurnState so it can be referenced if polling is needed
if (!turnContext.TurnState.ContainsKey(TurnStateConstants.OAuthLoginTimeoutKey) && _settings.Timeout.HasValue)
{
turnContext.TurnState.Add<object>(TurnStateConstants.OAuthLoginTimeoutKey, TimeSpan.FromMilliseconds(_settings.Timeout.Value));
}
// Set input hint
if (string.IsNullOrEmpty(prompt.InputHint))
{
prompt.InputHint = InputHints.AcceptingInput;
}
await turnContext.SendActivityAsync(prompt, cancellationToken).ConfigureAwait(false);
}
private async Task<PromptRecognizerResult<TokenResponse>> RecognizeTokenAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
var result = new PromptRecognizerResult<TokenResponse>();
if (IsTokenResponseEvent(turnContext))
{
var tokenResponseObject = turnContext.Activity.Value as JObject;
var token = tokenResponseObject?.ToObject<TokenResponse>();
result.Succeeded = true;
result.Value = token;
}
else if (IsTeamsVerificationInvoke(turnContext))
{
var magicCodeObject = turnContext.Activity.Value as JObject;
var magicCode = magicCodeObject.GetValue("state")?.ToString();
if (!(turnContext.Adapter is ICredentialTokenProvider adapter))
{
throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
}
// Getting the token follows a different flow in Teams. At the signin completion, Teams
// will send the bot an "invoke" activity that contains a "magic" code. This code MUST
// then be used to try fetching the token from Botframework service within some time
// period. We try here. If it succeeds, we return 200 with an empty body. If it fails
// with a retriable error, we return 500. Teams will re-send another invoke in this case.
// If it failes with a non-retriable error, we return 404. Teams will not (still work in
// progress) retry in that case.
try
{
var token = await adapter.GetUserTokenAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, magicCode, cancellationToken).ConfigureAwait(false);
if (token != null)
{
result.Succeeded = true;
result.Value = token;
await turnContext.SendActivityAsync(new Activity { Type = ActivityTypesEx.InvokeResponse }, cancellationToken).ConfigureAwait(false);
}
else
{
await turnContext.SendActivityAsync(new Activity { Type = ActivityTypesEx.InvokeResponse, Value = new InvokeResponse { Status = 404 } }, cancellationToken).ConfigureAwait(false);
}
}
catch
{
await turnContext.SendActivityAsync(new Activity { Type = ActivityTypesEx.InvokeResponse, Value = new InvokeResponse { Status = 500 } }, cancellationToken).ConfigureAwait(false);
}
}
else if (turnContext.Activity.Type == ActivityTypes.Message)
{
var matched = _magicCodeRegex.Match(turnContext.Activity.Text);
if (matched.Success)
{
if (!(turnContext.Adapter is ICredentialTokenProvider adapter))
{
throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
}
var token = await adapter.GetUserTokenAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, matched.Value, cancellationToken).ConfigureAwait(false);
if (token != null)
{
result.Succeeded = true;
result.Value = token;
}
}
}
return result;
}
}
}
| 49.230435 | 203 | 0.58284 |
[
"MIT"
] |
kvbreddy/botbuilder-dotnet
|
libraries/Microsoft.Bot.Builder.Dialogs/Prompts/OAuthPrompt.cs
| 22,648 |
C#
|
using Microsoft.AspNetCore.Mvc;
namespace HayleesThreads.Controllers
{
public class OrderController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
| 17 | 45 | 0.637255 |
[
"Unlicense"
] |
calliestump/HayleesThreads.Solution
|
HayleesThreads/Controllers/OrderController.cs
| 204 |
C#
|
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
/// <seealso cref="XunitConfiguration.SerialCollectionDefinition"/>
[Collection("Serial unit tests collection")]
public class MemoryTests
{
[Fact]
public async Task AbsoluteExpirationRelativeToNowExpiresCorrectlyAsync()
{
// This should be buggy but it seems to work for us: https://github.com/alastairtree/LazyCache/issues/84
using var cache = new MemoryCache(new MemoryCacheOptions());
var result = await cache.AtomicGetOrCreateAsync(
"key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(20) },
() => Task.FromResult("foo"));
Assert.Equal("foo", result);
result = await cache.AtomicGetOrCreateAsync(
"key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(20) },
() => Task.FromResult("bar"));
Assert.Equal("foo", result);
await Task.Delay(TimeSpan.FromMilliseconds(21));
result = await cache.AtomicGetOrCreateAsync(
"key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(20) },
() => Task.FromResult("bar"));
Assert.Equal("bar", result);
}
[Fact]
public async Task MultiplesCachesAsync()
{
var invoked = 0;
string ExpensiveComputation(string argument)
{
invoked++;
return "Hello " + argument;
}
using var cache1 = new MemoryCache(new MemoryCacheOptions());
using var cache2 = new MemoryCache(new MemoryCacheOptions());
var result0 = await cache1.AtomicGetOrCreateAsync(
"the-same-key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("World!")));
var result1 = await cache2.AtomicGetOrCreateAsync(
"the-same-other-key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("Loving Wife!")));
var result2 = await cache1.AtomicGetOrCreateAsync(
"the-same-key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("World!")));
Assert.Equal(result0, result2);
Assert.Equal(2, invoked);
// Make sure AtomicGetOrCreateAsync doesn't fail because another cache is disposed.
cache2.Dispose();
var result3 = await cache1.AtomicGetOrCreateAsync(
"the-same-key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("Foo!")));
Assert.Equal("Hello World!", result3);
Assert.Equal(2, invoked);
// Make sure cache2 call will fail.
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await cache2.AtomicGetOrCreateAsync(
"the-same-key",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("Foo!"))));
Assert.Equal(2, invoked);
}
[Fact]
public async Task CacheBasicBehaviorAsync()
{
var invoked = 0;
string ExpensiveComputation(string argument)
{
invoked++;
return "Hello " + argument;
}
using var cache = new MemoryCache(new MemoryCacheOptions());
using var expireKey1 = new CancellationTokenSource();
var options = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) };
options.AddExpirationToken(new CancellationChangeToken(expireKey1.Token));
var result0 = await cache.AtomicGetOrCreateAsync(
"key1",
options,
() => Task.FromResult(ExpensiveComputation("World!")));
var result1 = await cache.AtomicGetOrCreateAsync(
"key2",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("Loving Wife!")));
var result2 = await cache.AtomicGetOrCreateAsync(
"key1",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("World!")));
Assert.Equal(result0, result2);
Assert.NotEqual(result0, result1);
Assert.Equal(2, invoked);
// Make sure key1 expired.
expireKey1.Cancel();
var result3 = await cache.AtomicGetOrCreateAsync(
"key1",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("Foo!")));
var result4 = await cache.AtomicGetOrCreateAsync(
"key2",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
() => Task.FromResult(ExpensiveComputation("Bar!")));
Assert.Equal(result1, result4);
Assert.NotEqual(result0, result3);
Assert.Equal(3, invoked);
}
[Fact]
public async Task ExpirationTestsAsync()
{
const string Key = "key";
const string Value1 = "This will be expired";
const string Value2 = "Foo";
const string Value3 = "Should not change to this";
using var cache = new MemoryCache(new MemoryCacheOptions());
// First value should expire in 20 ms.
string result0 = await cache.AtomicGetOrCreateAsync(
Key,
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(20) },
() => Task.FromResult(Value1));
Stopwatch stopwatch = Stopwatch.StartNew();
// Wait 30 ms to let first value expire.
await Task.Delay(30);
// Measure how long we have waited.
long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
// Set Value2 to be in the cache.
string result1 = await cache.AtomicGetOrCreateAsync(
Key,
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) },
() => Task.FromResult(Value2));
// Value3 is not supposed to be used as Value2 could not expire.
string result2 = await cache.AtomicGetOrCreateAsync(
Key,
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) },
() => Task.FromResult(Value3));
if (result2 != Value2)
{
Assert.False(
true,
$"{nameof(result2)} value is '{result2}' instead of '{Value2}'. Debug info: Wait time was: {elapsedMilliseconds} ms. Previous values: {nameof(result0)}='{result0}', {nameof(result1)}='{result1}'");
}
}
[Fact]
public async Task CacheTaskTestAsync()
{
using var cache = new MemoryCache(new MemoryCacheOptions());
var greatCalled = 0;
var leeCalled = 0;
async Task<string> Greet(MemoryCache cache, string who) =>
await cache.AtomicGetOrCreateAsync(
$"{nameof(Greet)}{who}",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromTicks(1) }, // expires really soon
() =>
{
greatCalled++;
return Task.FromResult($"Hello Mr. {who}");
});
async Task<string> GreetMrLee(MemoryCache cache) =>
await cache.AtomicGetOrCreateAsync(
"key1",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) },
() =>
{
leeCalled++;
return Greet(cache, "Lee");
});
for (var i = 0; i < 10; i++)
{
await GreetMrLee(cache);
}
Assert.Equal(1, greatCalled);
Assert.Equal(1, leeCalled);
}
[Fact]
public async Task LockTestsAsync()
{
TimeSpan timeout = TimeSpan.FromSeconds(10);
using SemaphoreSlim trigger = new(0, 1);
using SemaphoreSlim signal = new(0, 1);
async Task<string> WaitUntilTrigger(string argument)
{
signal.Release();
if (!await trigger.WaitAsync(timeout))
{
throw new TimeoutException();
}
return argument;
}
using var cache = new MemoryCache(new MemoryCacheOptions());
var task0 = cache.AtomicGetOrCreateAsync(
"key1",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) },
() => WaitUntilTrigger("World!"));
if (!await signal.WaitAsync(timeout))
{
throw new TimeoutException();
}
var task1 = cache.AtomicGetOrCreateAsync(
"key1",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(60) },
() => Task.FromResult("Should not change to this"));
var task2 = cache.AtomicGetOrCreateAsync(
"key1",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(60) },
() => Task.FromResult("Should not change to this either"));
var task3 = cache.AtomicGetOrCreateAsync(
"key2",
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(60) },
() => Task.FromResult("Key2"));
// Different key should immediately added.
await task3.WithAwaitCancellationAsync(timeout);
Assert.True(task3.IsCompletedSuccessfully);
// Tasks are waiting for the factory method.
Assert.False(task0.IsCompleted);
Assert.False(task1.IsCompleted);
Assert.False(task2.IsCompleted);
// Let the factory method finish.
trigger.Release();
string result0 = await task0.WithAwaitCancellationAsync(timeout);
Assert.Equal(TaskStatus.RanToCompletion, task0.Status);
string result1 = await task1.WithAwaitCancellationAsync(timeout);
string result2 = await task2.WithAwaitCancellationAsync(timeout);
Assert.Equal(TaskStatus.RanToCompletion, task1.Status);
Assert.Equal(TaskStatus.RanToCompletion, task2.Status);
Assert.Equal(result0, result1);
Assert.Equal(result0, result2);
}
}
}
| 33.58885 | 202 | 0.712241 |
[
"MIT"
] |
0racl3z/WalletWasabi
|
WalletWasabi.Tests/UnitTests/MemoryTests.cs
| 9,640 |
C#
|
/*
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, 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.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net;
using System.Configuration;
using Minio.Exceptions;
using Minio;
namespace Minio.Tests
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class UrlTests
{
public UrlTests()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
var minio = new MinioClient("play.min.io:9000",
"Q3AM3UQ867SPQQA43P2F",
"zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void TestWithUrl()
{
new MinioClient(endpoint:"localhost:9000");
}
[TestMethod]
public void TestWithoutPort()
{
new MinioClient("localhost");
}
[TestMethod]
public void TestWithTrailingSlash()
{
new MinioClient("localhost:9000/");
}
[TestMethod]
[ExpectedException(typeof(InvalidEndpointException))]
public void TestUrlFailsWithMalformedScheme()
{
new MinioClient("http://localhost:9000");
}
[TestMethod]
[ExpectedException(typeof(InvalidEndpointException))]
public void TestUrlFailsWithPath()
{
new MinioClient("localhost:9000/foo");
}
[TestMethod]
[ExpectedException(typeof(InvalidEndpointException))]
public void TestUrlFailsWithQuery()
{
new MinioClient("localhost:9000/?foo=bar");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestSetAppInfoFailsNullApp()
{
var client = new MinioClient("localhost:9000");
client.SetAppInfo(null, "1.2.2");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestSetAppInfoFailsNullVersion()
{
var client = new MinioClient("localhost:9000");
client.SetAppInfo("Hello-App", null);
}
[TestMethod]
public void TestSetAppInfoSuccess()
{
var client = new MinioClient("localhost:9000");
client.SetAppInfo("Hello-App", "1.2.1");
}
[TestMethod]
public void TestEndpointSuccess()
{
new MinioClient("s3.amazonaws.com");
}
[TestMethod]
public void TestEndpointSuccess2()
{
new MinioClient("s3-us-west-1.amazonaws.com");
}
}
}
| 28.864198 | 85 | 0.582977 |
[
"Apache-2.0"
] |
krisis/minio-dotnet
|
Minio.Tests/UrlTests.cs
| 4,678 |
C#
|
using System;
using System.Collections.Generic;
using System.Reflection;
using Katahdin.Grammars;
using Katahdin.CodeTree;
namespace Katahdin.Base
{
public class ModuleStatement : Statement
{
public new static Pattern pattern;
public Name name;
public Statement body;
private static MethodInfo defineMethod;
public ModuleStatement(Source source, object name,
object body)
: base(source)
{
this.name = (Name) name;
this.body = (Statement) body;
}
public new static void SetUp(Module module, Grammar grammar)
{
if (pattern == null)
{
string expression = "s('module' l(name 0) l(body 1))";
Pattern[] patterns = {Name.pattern, Statement.pattern};
ParseGraphNode parseGraph = BootstrapParser.Parse(expression, patterns);
pattern = new ConcretePattern(null, "ModuleStatement", parseGraph);
pattern.SetType(typeof(ModuleStatement));
Statement.pattern.AddAltPattern(pattern);
}
module.SetName("ModuleStatement", typeof(ModuleStatement));
grammar.PatternDefined(pattern);
}
public override CodeTreeNode BuildCodeTree(RuntimeState state)
{
if (defineMethod == null)
{
Type[] parameterTypes = new Type[]{typeof(RuntimeState)};
defineMethod = GetType().GetMethod("Define", parameterTypes);
if (defineMethod == null)
throw new Exception();
}
CodeTreeNode callable = new ValueNode(
Source,
new ClrObjectMethodBinding(
this,
defineMethod));
return new GetToRunNode(
Source,
new CallNode(
Source,
callable,
null));
}
public void Define(RuntimeState state)
{
Module parent = (Module) state.Scope;
Module module = new Module(parent, name.name);
state.Scope.SetName(name.name, module);
state.Scope = module;
body.Run(state);
state.Scope = parent;
if (state.Returning != null)
throw new Exception("Statement within a module block returned");
}
}
}
| 30.505747 | 88 | 0.504145 |
[
"Unlicense"
] |
chrisseaton/katahdin
|
Katahdin/Base/statements/ModuleStatement.cs
| 2,654 |
C#
|
using System;
using System.Linq;
using NUnit.Framework;
using HP.LFT.Report;
using HP.LFT.UnitTesting;
using NUnit.Framework.Interfaces;
/// <summary>
/// Runs before all classes and tests in the current project.
/// <remarks>This class must remain outside any namespace in order to provide setup and tear down for the entire assembly.
/// To get more information follow this link: https://github.com/nunit/docs/wiki/SetUpFixture-Attribute
/// </remarks>
/// </summary>
[SetUpFixture]
public class SetupFixture : UnitTestSuiteBase
{
[OneTimeSetUp]
public void AssemblySetUp()
{
TestSuiteSetup(TestContext.CurrentContext.WorkDirectory);
}
[OneTimeTearDown]
public void AssemblyTearDown()
{
TestSuiteTearDown();
Reporter.GenerateReport();
}
}
namespace LeanFtTestProject2
{
[TestFixture]
public abstract class UnitTestClassBase : UnitTestBase
{
[OneTimeSetUp]
public void GlobalSetup()
{
TestSuiteSetup();
}
[SetUp]
public void BasicSetUp()
{
TestSetUp();
}
[TearDown]
public void BasicTearDown()
{
TestTearDown();
}
protected override string GetClassName()
{
return TestContext.CurrentContext.Test.FullName;
}
protected override string GetTestName()
{
return TestContext.CurrentContext.Test.Name;
}
protected override Status GetFrameworkTestResult()
{
switch (TestContext.CurrentContext.Result.Outcome.Status)
{
case TestStatus.Failed:
return Status.Failed;
case TestStatus.Inconclusive:
case TestStatus.Skipped:
return Status.Warning;
case TestStatus.Passed:
return Status.Passed;
default:
return Status.Passed;
}
}
}
}
| 24.707317 | 122 | 0.5923 |
[
"BSD-3-Clause"
] |
adamdthomas/CSharp_Selenium_Examples
|
LeanFtTestProject2/LeanFtTestProject2/UnitTestClassBase.cs
| 2,028 |
C#
|
/*******************************************************************************
* Copyright 2008-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Amazon.Runtime;
using Amazon.Util;
namespace Amazon.S3
{
/// <summary>
/// The file format used when exporting data to Amazon S3.
/// </summary>
public sealed class AnalyticsS3ExportFileFormat : ConstantClass
{
/// <summary>
/// CSV file format.
/// </summary>
public static readonly AnalyticsS3ExportFileFormat CSV = new AnalyticsS3ExportFileFormat("CSV");
/// <summary>
/// Construct instance of AnalyticsS3ExportFileFormat.
/// </summary>
/// <param name="value"></param>
public AnalyticsS3ExportFileFormat(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static AnalyticsS3ExportFileFormat FindValue(string value)
{
return FindValue<AnalyticsS3ExportFileFormat>(value);
}
/// <summary>
/// Converts the string to an AnalyticsS3ExportFileFormat.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator AnalyticsS3ExportFileFormat(string value)
{
return FindValue<AnalyticsS3ExportFileFormat>(value);
}
}
/// <summary>
/// Represents the accelerate status for a bucket.
/// </summary>
public sealed class BucketAccelerateStatus : ConstantClass
{
/// <summary>
/// Bucket acceleration is enabled.
/// </summary>
public static readonly BucketAccelerateStatus Enabled = new BucketAccelerateStatus("Enabled");
/// <summary>
/// Bucket acceleration is suspended.
/// </summary>
public static readonly BucketAccelerateStatus Suspended = new BucketAccelerateStatus("Suspended");
/// <summary>
/// Construct instance of BucketAccelerateStatus. It is not intended for this constructor to be called. Instead users should call the FindValue.
/// </summary>
/// <param name="value"></param>
public BucketAccelerateStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static BucketAccelerateStatus FindValue(string value)
{
return FindValue<BucketAccelerateStatus>(value);
}
/// <summary>
/// Converts the string to an BucketAccelerateStatus
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator BucketAccelerateStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The status of the delete marker replication.
/// </summary>
public sealed class DeleteMarkerReplicationStatus : ConstantClass
{
/// <summary>
/// Delete marker replication is enabled.
/// </summary>
public static readonly DeleteMarkerReplicationStatus Enabled = new DeleteMarkerReplicationStatus("Enabled");
/// <summary>
/// Delete marker replication is disabled.
/// </summary>
public static readonly DeleteMarkerReplicationStatus Disabled = new DeleteMarkerReplicationStatus("Disabled");
/// <summary>
/// Construct instance of DeleteMarkerReplicationStatus. It is not intended for this constructor to be called. Instead users should call the FindValue.
/// </summary>
/// <param name="value"></param>
public DeleteMarkerReplicationStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static DeleteMarkerReplicationStatus FindValue(string value)
{
return FindValue<DeleteMarkerReplicationStatus>(value);
}
/// <summary>
/// Converts the string to a DeleteMarkerReplicationStatus
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator DeleteMarkerReplicationStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all possible CannedACLs that can be used
/// for S3 Buckets or S3 Objects. For more information about CannedACLs, refer to
/// <see href="http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html#RESTCannedAccessPolicies"/>.
/// </summary>
public sealed class S3CannedACL : ConstantClass
{
/// <summary>
/// Owner gets FULL_CONTROL.
/// No one else has access rights (default).
/// </summary>
public static readonly S3CannedACL NoACL = new S3CannedACL("NoACL");
/// <summary>
/// Owner gets FULL_CONTROL.
/// No one else has access rights (default).
/// </summary>
public static readonly S3CannedACL Private = new S3CannedACL("private");
/// <summary>
/// Owner gets FULL_CONTROL and the anonymous principal is granted READ access.
/// If this policy is used on an object, it can be read from a browser with no authentication.
/// </summary>
public static readonly S3CannedACL PublicRead = new S3CannedACL("public-read");
/// <summary>
/// Owner gets FULL_CONTROL, the anonymous principal is granted READ and WRITE access.
/// This can be a useful policy to apply to a bucket, but is generally not recommended.
/// </summary>
public static readonly S3CannedACL PublicReadWrite = new S3CannedACL("public-read-write");
/// <summary>
/// Owner gets FULL_CONTROL, and any principal authenticated as a registered Amazon
/// S3 user is granted READ access.
/// </summary>
public static readonly S3CannedACL AuthenticatedRead = new S3CannedACL("authenticated-read");
/// <summary>
/// Owner gets FULL_CONTROL. Amazon EC2 gets READ access to GET an
/// Amazon Machine Image (AMI) bundle from Amazon S3.
/// </summary>
public static readonly S3CannedACL AWSExecRead = new S3CannedACL("aws-exec-read");
/// <summary>
/// Object Owner gets FULL_CONTROL, Bucket Owner gets READ
/// This ACL applies only to objects and is equivalent to private when used with PUT Bucket.
/// You use this ACL to let someone other than the bucket owner write content (get full control)
/// in the bucket but still grant the bucket owner read access to the objects.
/// </summary>
public static readonly S3CannedACL BucketOwnerRead = new S3CannedACL("bucket-owner-read");
/// <summary>
/// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL.
/// This ACL applies only to objects and is equivalent to private when used with PUT Bucket.
/// You use this ACL to let someone other than the bucket owner write content (get full control)
/// in the bucket but still grant the bucket owner full rights over the objects.
/// </summary>
public static readonly S3CannedACL BucketOwnerFullControl = new S3CannedACL("bucket-owner-full-control");
/// <summary>
/// The LogDelivery group gets WRITE and READ_ACP permissions on the bucket.
/// </summary>
public static readonly S3CannedACL LogDeliveryWrite = new S3CannedACL("log-delivery-write");
/// <summary>
/// Construct instance of S3CannedACL. It is not intended for this constructor to be called. Instead users should call the FindValue.
/// </summary>
/// <param name="value"></param>
public S3CannedACL(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static S3CannedACL FindValue(string value)
{
return FindValue<S3CannedACL>(value);
}
/// <summary>
/// Converts the string to an S3CannedACL
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator S3CannedACL(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all possible S3 Bucket region possibilities. For
/// more information, refer to
/// <see href="http://docs.amazonwebservices.com/AmazonS3/latest/BucketConfiguration.html#LocationSelection"/>.
/// </summary>
public sealed partial class S3Region : ConstantClass
{
/// <summary>
/// Specifies that the S3 Bucket should use US locality.
/// This is the default value.
/// </summary>
public static readonly S3Region US = new S3Region("");
/// <summary>
/// Specifies that the S3 Bucket should use US-EAST-2 locality.
/// </summary>
public static readonly S3Region USE2 = new S3Region("us-east-2");
/// <summary>
/// Specifies that the S3 Bucket should use EU locality which defaults to EU-WEST-1
/// </summary>
public static readonly S3Region EU = new S3Region("EU");
/// <summary>
/// Specifies that the S3 Bucket should use the EU-NORTH-1 locality.
/// </summary>
public static readonly S3Region EUN1 = new S3Region("eu-north-1");
/// <summary>
/// Specifies that the S3 Bucket should use the EU-WEST-1 locality.
/// </summary>
public static readonly S3Region EUW1 = new S3Region("eu-west-1");
/// <summary>
/// Specifies that the S3 Bucket should use the EU-WEST-2 locality.
/// </summary>
public static readonly S3Region EUW2 = new S3Region("eu-west-2");
/// <summary>
/// Specifies that the S3 Bucket should use the EU-WEST-3 locality.
/// </summary>
public static readonly S3Region EUW3 = new S3Region("eu-west-3");
/// <summary>
/// Specifies that the S3 Bucket should use the EU-CENTRAL-1 locality.
/// </summary>
public static readonly S3Region EUC1 = new S3Region("eu-central-1");
/// <summary>
/// Specifies that the S3 Bucket should use US-WEST-1 locality.
/// </summary>
public static readonly S3Region USW1 = new S3Region("us-west-1");
/// <summary>
/// Specifies that the S3 Bucket should use US-WEST-2 locality.
/// </summary>
public static readonly S3Region USW2 = new S3Region("us-west-2");
/// <summary>
/// Specifies that the S3 Bucket should use US-GOV-EAST-1 locality.
/// </summary>
public static readonly S3Region GOVE1 = new S3Region("us-gov-east-1");
/// <summary>
/// Specifies that the S3 Bucket should use US-GOV-WEST-1 locality.
/// </summary>
public static readonly S3Region GOVW1 = new S3Region("us-gov-west-1");
/// <summary>
/// Specifies that the S3 Bucket should use the AP-SOUTHEAST-1 locality.
/// </summary>
public static readonly S3Region APS1 = new S3Region("ap-southeast-1");
/// <summary>
/// Specifies that the S3 Bucket should use the AP-SOUTHEAST-2 locality.
/// </summary>
public static readonly S3Region APS2 = new S3Region("ap-southeast-2");
/// <summary>
/// Specifies that the S3 Bucket should use the AP-NORTHEAST-1 locality.
/// </summary>
public static readonly S3Region APN1 = new S3Region("ap-northeast-1");
/// <summary>
/// Specifies that the S3 Bucket should use the AP-NORTHEAST-2 locality.
/// </summary>
public static readonly S3Region APN2 = new S3Region("ap-northeast-2");
/// <summary>
/// Specifies that the S3 Bucket should use the AP-NORTHEAST-3 locality.
/// </summary>
public static readonly S3Region APN3 = new S3Region("ap-northeast-3");
/// <summary>
/// Specifies that the S3 Bucket should use the AP-SOUTH-1 locality.
/// </summary>
public static readonly S3Region APS3 = new S3Region("ap-south-1");
/// <summary>
/// Specifies that the S3 Bucket should use the SA-EAST-1 locality.
/// </summary>
public static readonly S3Region SAE1 = new S3Region("sa-east-1");
/// <summary>
/// Specifies that the S3 Bucket should use CN-NORTH-1 locality.
/// </summary>
public static readonly S3Region CN1 = new S3Region("cn-north-1");
/// <summary>
/// Specifies that the S3 Bucket should use CN-NORTHWEST-1 locality.
/// </summary>
public static readonly S3Region CNW1 = new S3Region("cn-northwest-1");
/// <summary>
/// Specifies that the S3 Bucket should use CA-CENTRAL-1 locality.
/// </summary>
public static readonly S3Region CAN1 = new S3Region("ca-central-1");
/// <summary>
/// Specifies that the S3 Bucket should use US-WEST-1 locality.
/// </summary>
[Obsolete("This constant is obsolete. Usags of this property should be migrated to the USW1 constant")]
public static readonly S3Region SFO = new S3Region("us-west-1");
/// <summary>
/// Specifies that the S3 Bucket should use CN-NORTH-1 locality.
/// </summary>
[Obsolete("This constant is obsolete. Usags of this property should be migrated to the CN1 constant")]
public static readonly S3Region CN = new S3Region("cn-north-1");
/// <summary>
/// Specifies that the S3 Bucket should use US-GOV-WEST-1 locality.
/// </summary>
[Obsolete("This constant is obsolete. Usags of this property should be migrated to the GOVW1 constant")]
public static readonly S3Region GOV = new S3Region("us-gov-west-1");
/// <summary>
/// Construct instance of S3Region. It is not intended for this constructor to be called. Instead users should call the FindValue.
/// </summary>
/// <param name="value"></param>
public S3Region(string value)
: base(value) { }
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static S3Region FindValue(string value)
{
if (value == null)
return S3Region.US;
return FindValue<S3Region>(value);
}
/// <summary>
/// Converts the string to the S3Region class
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator S3Region(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all ACL permissions. For more information, refer to
/// <see href="http://docs.amazonwebservices.com/AmazonS3/latest/S3_ACLs.html#S3_ACLs_Permissions"/>.
/// </summary>
public sealed class S3Permission : ConstantClass
{
/// <summary>
/// When applied to a bucket, grants permission to list the bucket.
/// When applied to an object, this grants permission to read the
/// object data and/or metadata.
/// </summary>
public static readonly S3Permission READ = new S3Permission("READ", "x-amz-grant-read");
/// <summary>
/// When applied to a bucket, grants permission to create, overwrite,
/// and delete any object in the bucket. This permission is not
/// supported for objects.
/// </summary>
public static readonly S3Permission WRITE = new S3Permission("WRITE", "x-amz-grant-write");
/// <summary>
/// Grants permission to read the ACL for the applicable bucket or object.
/// The owner of a bucket or object always has this permission implicitly.
/// </summary>
public static readonly S3Permission READ_ACP = new S3Permission("READ_ACP", "x-amz-grant-read-acp");
/// <summary>
/// Gives permission to overwrite the ACP for the applicable bucket or object.
/// The owner of a bucket or object always has this permission implicitly.
/// Granting this permission is equivalent to granting FULL_CONTROL because
/// the grant recipient can make any changes to the ACP.
/// </summary>
public static readonly S3Permission WRITE_ACP = new S3Permission("WRITE_ACP", "x-amz-grant-write-acp");
/// <summary>
/// Provides READ, WRITE, READ_ACP, and WRITE_ACP permissions.
/// It does not convey additional rights and is provided only for convenience.
/// </summary>
public static readonly S3Permission FULL_CONTROL = new S3Permission("FULL_CONTROL", "x-amz-grant-full-control");
/// <summary>
/// Gives permission to restore an object that is currently stored in Amazon Glacier
/// for archival storage.
/// </summary>
public static readonly S3Permission RESTORE_OBJECT = new S3Permission("RESTORE", "x-amz-grant-restore-object");
/// <summary>
/// Construct S3Permission.
/// </summary>
/// <param name="value"></param>
public S3Permission(string value)
: this(value, null) { }
/// <summary>
/// Construct instance of S3Permission. It is not intended for this constructor to be called. Instead users should call the FindValue.
/// </summary>
/// <param name="value"></param>
/// <param name="headerName"></param>
public S3Permission(string value, string headerName)
: base(value)
{
this.HeaderName = headerName;
}
/// <summary>
/// Gets and sets the HeaderName property.
/// </summary>
public string HeaderName
{
get;
private set;
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static S3Permission FindValue(string value)
{
return FindValue<S3Permission>(value);
}
/// <summary>
/// Converts the string to an S3Permission
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator S3Permission(string value)
{
return FindValue(value);
}
}
/// <summary>
/// An enumeration of all Metadata directives that
/// can be used for the CopyObject operation.
/// </summary>
public enum S3MetadataDirective
{
/// <summary>
/// Specifies that the metadata is copied from the source object.
/// </summary>
COPY,
/// <summary>
/// Specifies that the metadata is replaced with metadata provided in the request.
/// All original metadata is replaced by the metadata you specify.
/// </summary>
REPLACE
}
/// <summary>
/// An enumeration of all protocols that the pre-signed
/// URL can be created against.
/// </summary>
public enum Protocol
{
/// <summary>
/// https protocol will be used in the pre-signed URL.
/// </summary>
HTTPS,
/// <summary>
/// http protocol will be used in the pre-signed URL.
/// </summary>
HTTP
}
/// <summary>
/// An enumeration of supported HTTP verbs
/// </summary>
public enum HttpVerb
{
/// <summary>
/// The GET HTTP verb.
/// </summary>
GET,
/// <summary>
/// The HEAD HTTP verb.
/// </summary>
HEAD,
/// <summary>
/// The PUT HTTP verb.
/// </summary>
PUT,
/// <summary>
/// The DELETE HTTP verb.
/// </summary>
DELETE
}
/// <summary>
/// S3 Storage Class Definitions
/// </summary>
public sealed class S3StorageClass : ConstantClass
{
/// <summary>
/// The STANDARD storage class, which is the default
/// storage class for S3.
/// <para></para>
/// Durability 99.999999999%; Availability 99.99% over a given year.
/// </summary>
public static readonly S3StorageClass Standard = new S3StorageClass("STANDARD");
/// <summary>
/// REDUCED_REDUNDANCY provides the same availability as standard, but at a lower durability.
/// <para></para>
/// Durability 99.99%; Availability 99.99% over a given year.
/// </summary>
public static readonly S3StorageClass ReducedRedundancy = new S3StorageClass("REDUCED_REDUNDANCY");
/// <summary>
/// The GLACIER storage is for object that are stored in Amazon Glacier.
/// This storage class is for objects that are for archival purpose and
/// get operations are rare.
/// <para></para>
/// Durability 99.999999999%
/// </summary>
public static readonly S3StorageClass Glacier = new S3StorageClass("GLACIER");
/// <summary>
/// The STANDARD_IA storage is for infrequently accessed objects.
/// This storage class is for objects that are long-lived and less frequently accessed,
/// like backups and older data.
/// <para></para>
/// Durability 99.999999999%; Availability 99.9% over a given year.
/// </summary>
public static readonly S3StorageClass StandardInfrequentAccess = new S3StorageClass("STANDARD_IA");
/// <summary>
/// The ONEZONE_IA storage is for infrequently accessed objects. It is similiar to STANDARD_IA, but
/// only stores object data within one Availablity Zone in a given region.
/// <para></para>
/// Durability 99.999999999%; Availability 99% over a given year.
/// </summary>
public static readonly S3StorageClass OneZoneInfrequentAccess = new S3StorageClass("ONEZONE_IA");
/// <summary>
/// IntelligentTiering makes it easy to lower your overall cost of storage by automatically placing data in the storage
/// class that best matches the access patterns for the storage. With IntelligentTiering, you don’t need to define
/// and manage individual policies for lifecycle data management or write code to transition objects
/// between storage classes. Instead, you can use IntelligentTiering to manage transitions between Standard and
/// S-IA without writing any application code. IntelligentTiering also manages transitions automatically to
/// Glacier for long term archive in addition to S3 storage classes.
/// </summary>
public static readonly S3StorageClass IntelligentTiering = new S3StorageClass("INTELLIGENT_TIERING");
/// <summary>
/// Construct an instance of S3StorageClass.
/// </summary>
/// <param name="value"></param>
public S3StorageClass(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static S3StorageClass FindValue(string value)
{
return FindValue<S3StorageClass>(value);
}
/// <summary>
/// Convert string to S3StorageClass.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator S3StorageClass(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The constants for the known event names used by S3 notification. S3 might add new
/// events before the SDK is updated. In which case the names listed in the S3 documentation
/// will work as well as these constants.
/// </summary>
public sealed class NotificationEvents
{
/// <summary>
/// An event that says an object has been lost in the reduced redundancy storage.
/// </summary>
public static readonly string ReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject";
private NotificationEvents()
{
}
}
/// <summary>
/// A list of all server-side encryption methods for customer provided encryption keys.
/// </summary>
public sealed class ServerSideEncryptionCustomerMethod : ConstantClass
{
/// <summary>
/// No server side encryption to be used.
/// </summary>
public static readonly ServerSideEncryptionCustomerMethod None = new ServerSideEncryptionCustomerMethod("");
/// <summary>
/// Use AES 256 server side encryption.
/// </summary>
public static readonly ServerSideEncryptionCustomerMethod AES256 = new ServerSideEncryptionCustomerMethod("AES256");
/// <summary>
/// Constructs an instance of ServerSideEncryptionCustomerMethod.
/// </summary>
/// <param name="value"></param>
public ServerSideEncryptionCustomerMethod(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static ServerSideEncryptionCustomerMethod FindValue(string value)
{
return FindValue<ServerSideEncryptionCustomerMethod>(value);
}
/// <summary>
/// Converts string to ServerSideEncryptionCustomerMethod.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator ServerSideEncryptionCustomerMethod(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all server-side encryption methods.
/// </summary>
public sealed class ServerSideEncryptionMethod : ConstantClass
{
/// <summary>
/// No server side encryption to be used.
/// </summary>
public static readonly ServerSideEncryptionMethod None = new ServerSideEncryptionMethod("");
/// <summary>
/// Use AES 256 server side encryption.
/// </summary>
public static readonly ServerSideEncryptionMethod AES256 = new ServerSideEncryptionMethod("AES256");
/// <summary>
/// Use AWS Key Management Service for server side encryption.
/// </summary>
public static readonly ServerSideEncryptionMethod AWSKMS = new ServerSideEncryptionMethod("aws:kms");
/// <summary>
/// Construct instance of ServerSideEncryptionMethod.
/// </summary>
/// <param name="value"></param>
public ServerSideEncryptionMethod(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static ServerSideEncryptionMethod FindValue(string value)
{
return FindValue<ServerSideEncryptionMethod>(value);
}
/// <summary>
/// Convert string to ServerSideEncryptionCustomerMethod.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator ServerSideEncryptionMethod(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all grantee types.
/// </summary>
public sealed class GranteeType : ConstantClass
{
/// <summary>
/// The predefined group.
/// </summary>
public static readonly GranteeType Group = new GranteeType("Group");
/// <summary>
/// The email address of an AWS account
/// </summary>
public static readonly GranteeType Email = new GranteeType("AmazonCustomerByEmail");
/// <summary>
/// The canonical user ID of an AWS account
/// </summary>
public static readonly GranteeType CanonicalUser = new GranteeType("CanonicalUser");
/// <summary>
/// Construct an instance of GranteeType.
/// </summary>
/// <param name="value"></param>
public GranteeType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static GranteeType FindValue(string value)
{
return FindValue<GranteeType>(value);
}
/// <summary>
/// Convert a string to GranteeType.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator GranteeType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all lifecycle statuses.
/// </summary>
public sealed class LifecycleRuleStatus : ConstantClass
{
/// <summary>
/// The rule is enabled.
/// </summary>
public static readonly LifecycleRuleStatus Enabled = new LifecycleRuleStatus("Enabled");
/// <summary>
/// The rule is disabled.
/// </summary>
public static readonly LifecycleRuleStatus Disabled = new LifecycleRuleStatus("Disabled");
/// <summary>
/// Constructs an instance LifecycleRuleStatus.
/// </summary>
/// <param name="value"></param>
public LifecycleRuleStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static LifecycleRuleStatus FindValue(string value)
{
return FindValue<LifecycleRuleStatus>(value);
}
/// <summary>
/// Convert string to LifecycleRuleStatus.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator LifecycleRuleStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all version statuses.
/// </summary>
public sealed class VersionStatus : ConstantClass
{
/// <summary>
/// The rule is off.
/// </summary>
public static readonly VersionStatus Off = new VersionStatus("Off");
/// <summary>
/// The rule is suspended.
/// </summary>
public static readonly VersionStatus Suspended = new VersionStatus("Suspended");
/// <summary>
/// The rule is enabled.
/// </summary>
public static readonly VersionStatus Enabled = new VersionStatus("Enabled");
/// <summary>
/// Construct an instance of VersionStatus.
/// </summary>
/// <param name="value"></param>
public VersionStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static VersionStatus FindValue(string value)
{
return FindValue<VersionStatus>(value);
}
/// <summary>
/// Convert string to VersionStatus.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator VersionStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// A list of all encoding types.
/// </summary>
public sealed class EncodingType : ConstantClass
{
/// <summary>
/// Url encoding.
/// </summary>
public static readonly EncodingType Url = new EncodingType("Url");
/// <summary>
/// Constructs intance of EncodingType
/// </summary>
/// <param name="value"></param>
public EncodingType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static EncodingType FindValue(string value)
{
return FindValue<EncodingType>(value);
}
/// <summary>
/// Converts string to EncodingType
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator EncodingType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The bucket event for which to send notifications.
/// </summary>
public sealed class EventType : ConstantClass
{
/// <summary>
/// The event encapsulates all the object create events
/// </summary>
public static readonly EventType ObjectCreatedAll = new EventType("s3:ObjectCreated:*");
/// <summary>
/// Event for put operations
/// </summary>
public static readonly EventType ObjectCreatedPut = new EventType("s3:ObjectCreated:Put");
/// <summary>
/// Event for post operations
/// </summary>
public static readonly EventType ObjectCreatedPost = new EventType("s3:ObjectCreated:Post");
/// <summary>
/// Event for copy operations
/// </summary>
public static readonly EventType ObjectCreatedCopy = new EventType("s3:ObjectCreated:Copy");
/// <summary>
/// Event for completing a multi part upload
/// </summary>
public static readonly EventType ObjectCreatedCompleteMultipartUpload = new EventType("s3:ObjectCreated:CompleteMultipartUpload");
/// <summary>
/// This event encapsulates all the object removed events
/// </summary>
public static readonly EventType ObjectRemovedAll = new EventType("s3:ObjectRemoved:*");
/// <summary>
/// Event for object removed, delete operation.
/// </summary>
public static readonly EventType ObjectRemovedDelete = new EventType("s3:ObjectRemoved:Delete");
/// <summary>
/// Event for object removed, delete marker created operation.
/// </summary>
public static readonly EventType ObjectRemovedDeleteMarkerCreated = new EventType("s3:ObjectRemoved:DeleteMarkerCreated");
/// <summary>
/// Event for objects stored in reduced redundancy and S3 detects the object is lost
/// </summary>
public static readonly EventType ReducedRedundancyLostObject = new EventType("s3:ReducedRedundancyLostObject");
/// <summary>
/// Event for restore post operations.
/// </summary>
public static readonly EventType ObjectRestorePost = new EventType("s3:ObjectRestore:Post");
/// <summary>
/// Event for when object restore is completed.
/// </summary>
public static readonly EventType ObjectRestoreCompleted = new EventType("s3:ObjectRestore:Completed");
/// <summary>
/// Constructs instance of EventType.
/// </summary>
/// <param name="value"></param>
public EventType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static EventType FindValue(string value)
{
return FindValue<EventType>(value);
}
/// <summary>
/// Convert string to EventType.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator EventType(string value)
{
return FindValue(value);
}
/// <summary>
/// Compares if the ConstantClass instances are equals.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(ConstantClass obj)
{
if(obj == null)
{
return false;
}
return this.Equals(obj.Value);
}
/// <summary>
/// Compares if the ConstantClass instances are equals. This is ovewritten to handle the
/// discrepancy with S3 events coming from Lambda that don't have the prefix "s3:".
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected override bool Equals(string value)
{
if (value == null)
{
return false;
}
var thisValue = this.Value;
if (!thisValue.StartsWith("s3:", StringComparison.OrdinalIgnoreCase))
thisValue = "s3:" + thisValue;
if (!value.StartsWith("s3:", StringComparison.OrdinalIgnoreCase))
value = "s3:" + value;
return StringComparer.OrdinalIgnoreCase.Equals(thisValue, value);
}
}
/// <summary>
/// A list of all Inventory Formats.
/// </summary>
public sealed class InventoryFormat : ConstantClass
{
/// <summary>
/// CSV inventory format
/// </summary>
public static readonly InventoryFormat CSV = new InventoryFormat("CSV");
/// <summary>
/// ORC inventory format
/// </summary>
public static readonly InventoryFormat ORC = new InventoryFormat("ORC");
/// <summary>
/// Parquet inventory format
/// </summary>
public static readonly InventoryFormat Parquet = new InventoryFormat("Parquet");
/// <summary>
/// Construct instance of InventoryFormat.
/// </summary>
/// <param name="value"></param>
public InventoryFormat(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the InventoryFormat.</param>
/// <returns>The InventoryFormat object for that string.</returns>
public static InventoryFormat FindValue(string value)
{
return FindValue<InventoryFormat>(value);
}
/// <summary>
/// Convert string to InventoryFormat.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator InventoryFormat(string value)
{
return FindValue<InventoryFormat>(value);
}
}
/// <summary>
/// A list of inventory included object versions.
/// </summary>
public sealed class InventoryIncludedObjectVersions : ConstantClass
{
/// <summary>
/// All Inventory Included Object Versions
/// </summary>
public static readonly InventoryIncludedObjectVersions All = new InventoryIncludedObjectVersions("All");
/// <summary>
/// Current Inventory Included Object Versions
/// </summary>
public static readonly InventoryIncludedObjectVersions Current = new InventoryIncludedObjectVersions("Current");
/// <summary>
/// Construct instance of InventoryIncludedObjectVersions.
/// </summary>
/// <param name="value"></param>
public InventoryIncludedObjectVersions(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the InventoryIncludedObjectVersions.</param>
/// <returns>The InventoryIncludedObjectVersions object for that string.</returns>
public static InventoryIncludedObjectVersions FindValue(string value)
{
return FindValue<InventoryIncludedObjectVersions>(value);
}
/// <summary>
/// Convert string to InventoryIncludedObjectVersions.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator InventoryIncludedObjectVersions(string value)
{
return FindValue<InventoryIncludedObjectVersions>(value);
}
}
/// <summary>
/// A list of inventory frequencies.
/// </summary>
public sealed class InventoryFrequency : ConstantClass
{
/// <summary>
/// Daily Inventory Frequency
/// </summary>
public static readonly InventoryFrequency Daily = new InventoryFrequency("Daily");
/// <summary>
/// Weekly Inventory Frequency
/// </summary>
public static readonly InventoryFrequency Weekly = new InventoryFrequency("Weekly");
/// <summary>
/// Construct instance of InventoryFrequency.
/// </summary>
/// <param name="value"></param>
public InventoryFrequency(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the InventoryFrequency.</param>
/// <returns>The InventoryFrequency object for that string.</returns>
public static InventoryFrequency FindValue(string value)
{
return FindValue<InventoryFrequency>(value);
}
/// <summary>
/// Convert string to InventoryFrequency.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator InventoryFrequency(string value)
{
return FindValue<InventoryFrequency>(value);
}
}
/// <summary>
/// A list of inventory optional fields.
/// </summary>
public sealed class InventoryOptionalField : ConstantClass
{
/// <summary>
/// InventoryOptionalField for Size
/// </summary>
public static readonly InventoryOptionalField Size = new InventoryOptionalField("Size");
/// <summary>
/// InventoryOptionalField for LastModifiedDate
/// </summary>
public static readonly InventoryOptionalField LastModifiedDate = new InventoryOptionalField("LastModifiedDate");
/// <summary>
/// InventoryOptionalField for StorageClass
/// </summary>
public static readonly InventoryOptionalField StorageClass = new InventoryOptionalField("StorageClass");
/// <summary>
/// InventoryOptionalField for ETag
/// </summary>
public static readonly InventoryOptionalField ETag = new InventoryOptionalField("ETag");
/// <summary>
/// InventoryOptionalField for IsMultipartUploaded
/// </summary>
public static readonly InventoryOptionalField IsMultipartUploaded = new InventoryOptionalField("IsMultipartUploaded");
/// <summary>
/// InventoryOptionalField for ReplicationStatus
/// </summary>
public static readonly InventoryOptionalField ReplicationStatus = new InventoryOptionalField("ReplicationStatus");
/// <summary>
/// InventoryOptionalField for EncryptionStatus
/// </summary>
public static readonly InventoryOptionalField EncryptionStatus = new InventoryOptionalField("EncryptionStatus");
/// <summary>
/// InventoryOptionalField for ObjectLockRetainUntilDate
/// </summary>
public static readonly InventoryOptionalField ObjectLockRetainUntilDate = new InventoryOptionalField("ObjectLockRetainUntilDate");
/// <summary>
/// InventoryOptionalField for ObjectLockMode
/// </summary>
public static readonly InventoryOptionalField ObjectLockMode = new InventoryOptionalField("ObjectLockMode");
/// <summary>
/// InventoryOptionalField for ObjectLockLegalHoldStatus
/// </summary>
public static readonly InventoryOptionalField ObjectLockLegalHoldStatus = new InventoryOptionalField("ObjectLockLegalHoldStatus");
/// <summary>
/// Construct instance of InventoryOptionalField.
/// </summary>
/// <param name="value"></param>
public InventoryOptionalField(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the InventoryOptionalField.</param>
/// <returns>The InventoryIncludedObjectVersions object for that string.</returns>
public static InventoryOptionalField FindValue(string value)
{
return FindValue<InventoryOptionalField>(value);
}
/// <summary>
/// Convert string to InventoryOptionalField.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator InventoryOptionalField(string value)
{
return FindValue<InventoryOptionalField>(value);
}
}
/// <summary>
/// The status of the replication job associated with this source object.
/// </summary>
public sealed class ReplicationStatus : ConstantClass
{
/// <summary>
/// The object is pending replication.
/// </summary>
public static readonly ReplicationStatus Pending = new ReplicationStatus("PENDING");
/// <summary>
/// The object has been replicated.
/// </summary>
public static readonly ReplicationStatus Completed = new ReplicationStatus("COMPLETED");
/// <summary>
/// The object was created as a result of replication.
/// </summary>
public static readonly ReplicationStatus Replica = new ReplicationStatus("REPLICA");
/// <summary>
/// The object replication has failed due to a customer-attributable reason, and the replication will not be attempted again.
/// </summary>
public static readonly ReplicationStatus Failed = new ReplicationStatus("FAILED");
/// <summary>
/// Construct instance of ReplicationStatus.
/// </summary>
/// <param name="value"></param>
public ReplicationStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the ReplicationStatus.</param>
/// <returns>The ReplicationStatus object for that string.</returns>
public static ReplicationStatus FindValue(string value)
{
return FindValue<ReplicationStatus>(value);
}
/// <summary>
/// Convert string to ReplicationStatus.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator ReplicationStatus(string value)
{
return FindValue<ReplicationStatus>(value);
}
}
/// <summary>
/// Whether a replication rule is applied or ignored.
/// </summary>
public sealed class ReplicationRuleStatus : ConstantClass
{
/// <summary>
/// The rule will be applied.
/// </summary>
public static readonly ReplicationRuleStatus Enabled = new ReplicationRuleStatus("Enabled");
/// <summary>
/// The rule will be ignored.
/// </summary>
public static readonly ReplicationRuleStatus Disabled = new ReplicationRuleStatus("Disabled");
/// <summary>
/// Construct instance of ReplicationRuleStatus
/// </summary>
/// <param name="value"></param>
public ReplicationRuleStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the ReplicationRuleStatus.</param>
/// <returns>The ReplicationRuleStatus object for that string.</returns>
public static ReplicationRuleStatus FindValue(string value)
{
return FindValue<ReplicationRuleStatus>(value);
}
/// <summary>
/// Convert string to ReplicationRuleStatus.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator ReplicationRuleStatus(string value)
{
return FindValue<ReplicationRuleStatus>(value);
}
}
/// <summary>
/// Specifies whether the object tag-set are copied from the source object or replaced with tag-set provided in the request.
/// </summary>
internal sealed class TaggingDirective : ConstantClass
{
/// <summary>
/// The object tag-set is copied from the source object.
/// </summary>
public static readonly TaggingDirective COPY = new TaggingDirective("COPY");
/// <summary>
/// The object tag-set is replaced with tag-set provided in the request.
/// </summary>
public static readonly TaggingDirective REPLACE = new TaggingDirective("REPLACE");
/// <summary>
/// Construct instance of TaggingDirective
/// </summary>
public TaggingDirective(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the TaggingDirective.</param>
/// <returns>The TaggingDirective object for that string.</returns>
public static TaggingDirective FindValue(string value)
{
return FindValue<TaggingDirective>(value);
}
/// <summary>
/// Convert string to TaggingDirective.
/// </summary>
public static implicit operator TaggingDirective(string value)
{
return FindValue<TaggingDirective>(value);
}
}
/// <summary>
/// All enumerations type for retrieval tier for Glacier restore.
/// </summary>
public sealed class GlacierJobTier : ConstantClass
{
/// <summary>
/// Standard Tier for Glacier restore.
/// </summary>
public static readonly GlacierJobTier Standard = new GlacierJobTier("Standard");
/// <summary>
/// Bulk Tier for Glacier restore.
/// </summary>
public static readonly GlacierJobTier Bulk = new GlacierJobTier("Bulk");
/// <summary>
/// Expedited Tier for Glacier restore.
/// </summary>
public static readonly GlacierJobTier Expedited = new GlacierJobTier("Expedited");
/// <summary>
/// Construct instance of RestoreObjectRequestGlacierJobTier
/// </summary>
/// <param name="value"></param>
private GlacierJobTier(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the RestoreObjectRequestGlacierJobTier.</param>
/// <returns>The RestoreObjectRequestGlacierJobTier object for that string.</returns>
public static GlacierJobTier FindValue(string value)
{
return FindValue<GlacierJobTier>(value);
}
/// <summary>
/// Convert string to RestoreObjectRequestGlacierJobTier.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator GlacierJobTier(string value)
{
return FindValue<GlacierJobTier>(value);
}
}
/// <summary>
/// The version of the output schema to use when exporting data.
/// </summary>
public sealed class StorageClassAnalysisSchemaVersion : ConstantClass
{
/// <summary>
/// The schema output version V_1.
/// </summary>
public static readonly StorageClassAnalysisSchemaVersion V_1 = new StorageClassAnalysisSchemaVersion("V_1");
/// <summary>
/// Construct instance of StorageClassAnalysisSchemaVersion
/// </summary>
/// <param name="value"></param>
public StorageClassAnalysisSchemaVersion(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The string representation of the StorageClassAnalysisSchemaVersion.</param>
/// <returns>The StorageClassAnalysisSchemaVersion object for that string.</returns>
public static StorageClassAnalysisSchemaVersion FindValue(string value)
{
return FindValue<StorageClassAnalysisSchemaVersion>(value);
}
/// <summary>
/// Convert string to StorageClassAnalysisSchemaVersion.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator StorageClassAnalysisSchemaVersion(string value)
{
return FindValue<StorageClassAnalysisSchemaVersion>(value);
}
}
internal enum S3QueryParameter
{
Action,
Authorization,
BucketVersion,
CanonicalizedResource,
ContentBody,
ContentLength,
ContentType,
DestinationBucket,
Expires,
Key,
Query,
QueryToSign,
Range,
RequestAddress,
RequestTimeout,
RequestReadWriteTimeout,
Url,
Verb,
VerifyChecksum,
MaxUploads,
KeyMarker,
UploadIdMarker
}
/// <summary>
/// Acknowledges that requester pays for the operation.
/// </summary>
public sealed class RequestPayer : ConstantClass
{
/// <summary>
/// Requester pays for the operation.
/// </summary>
public static readonly RequestPayer Requester = new RequestPayer("requester");
private RequestPayer(string value)
: base(value)
{
}
/// <summary>
/// Finds the RequestPayer instance for the string value.
/// </summary>
public static RequestPayer FindValue(string value)
{
return FindValue<RequestPayer>(value);
}
/// <summary>
/// Converts string to RequestPayer instance
/// </summary>
public static implicit operator RequestPayer(string value)
{
return FindValue<RequestPayer>(value);
}
}
/// <summary>
/// The response from S3 that it confirms that requester pays.
/// </summary>
public sealed class RequestCharged : ConstantClass
{
/// <summary>
/// S3 acknowledges that the requester pays.
/// </summary>
public static readonly RequestCharged Requester = new RequestCharged("requester");
private RequestCharged(string value)
: base(value)
{
}
/// <summary>
/// Finds the RequestCharged instance for the string value
/// </summary>
public static RequestCharged FindValue(string value)
{
return FindValue<RequestCharged>(value);
}
/// <summary>
/// converts the string to RequestCharged instance
/// </summary>
public static implicit operator RequestCharged(string value)
{
return FindValue<RequestCharged>(value);
}
}
/// <summary>
/// The override value for the owner of the replica object.
/// </summary>
public sealed class OwnerOverride : ConstantClass
{
/// <summary>
/// Overrides destination bucket's owner.
/// </summary>
public static readonly OwnerOverride Destination = new OwnerOverride("Destination");
public OwnerOverride(string value)
: base(value)
{
}
/// <summary>
/// Finds the OwnerOverride instance for the string value
/// </summary>
public static OwnerOverride FindValue(string value)
{
return FindValue<OwnerOverride>(value);
}
/// <summary>
/// converts the string to OwnerOverride instance
/// </summary>
public static implicit operator OwnerOverride(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The replication for KMS encrypted S3 objects is disabled if status is not Enabled.
/// </summary>
public sealed class SseKmsEncryptedObjectsStatus : ConstantClass
{
/// <summary>
/// The replication for KMS encrypted S3 objects is enabled.
/// </summary>
public static readonly SseKmsEncryptedObjectsStatus Enabled = new SseKmsEncryptedObjectsStatus("Enabled");
/// <summary>
/// The replication for KMS encrypted S3 objects is disabled.
/// </summary>
public static readonly SseKmsEncryptedObjectsStatus Disabled = new SseKmsEncryptedObjectsStatus("Disabled");
/// <summary>
/// </summary>
/// <param name="value"></param>
public SseKmsEncryptedObjectsStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the SseKmsEncryptedObjectsStatus instance for the string value
/// </summary>
public static SseKmsEncryptedObjectsStatus FindValue(string value)
{
return FindValue<SseKmsEncryptedObjectsStatus>(value);
}
/// <summary>
/// Converts the string to SseKmsEncryptedObjectsStatus instance
/// </summary>
public static implicit operator SseKmsEncryptedObjectsStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Specify how headers will be handled.
/// </summary>
public sealed class FileHeaderInfo : ConstantClass
{
/// <summary>
/// Headers will be usable in SELECT clause.
/// </summary>
public static readonly FileHeaderInfo Use = new FileHeaderInfo("USE");
/// <summary>
/// Headers will be skipped
/// </summary>
public static readonly FileHeaderInfo Ignore = new FileHeaderInfo("IGNORE");
/// <summary>
/// No header is present.
/// </summary>
public static readonly FileHeaderInfo None = new FileHeaderInfo("NONE");
private FileHeaderInfo(string value)
: base(value)
{
}
/// <summary>
/// Finds the FileHeaderInfo instance for the string value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static FileHeaderInfo FindValue(string value)
{
return FindValue<FileHeaderInfo>(value);
}
/// <summary>
/// Converts the string to FileHeaderInfo instance
/// </summary>
public static implicit operator FileHeaderInfo(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Describes when fields in output should be surrounded with quotes.
/// </summary>
public sealed class QuoteFields : ConstantClass
{
/// <summary>
/// Specifies that fields in output should always be surrounded in quotes.
/// </summary>
public static readonly QuoteFields Always = new QuoteFields("ALWAYS");
/// <summary>
/// Specifies that fields in output should be surrounded in quotes as necessary.
/// </summary>
public static readonly QuoteFields AsNeeded = new QuoteFields("ASNEEDED");
private QuoteFields(string value)
: base(value)
{
}
/// <summary>
/// Finds the QuoteFields instance for the string value
/// </summary>
/// <param name="value">string value that maps to QuoteFields enum</param>
/// <returns>QuoteFields enum</returns>
public static QuoteFields FindValue(string value)
{
return FindValue<QuoteFields>(value);
}
/// <summary>
/// Converts the string to QuoteFields instance
/// </summary>
public static implicit operator QuoteFields(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Type of the expression provided in the Expression member.
/// </summary>
public sealed class ExpressionType : ConstantClass
{
/// <summary>
/// SQL expression
/// </summary>
public static readonly ExpressionType SQL = new ExpressionType("SQL");
private ExpressionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the ExpressionType instance for the string value
/// </summary>
/// <param name="value">string value that maps to ExpressionType enum</param>
/// <returns>ExpressionType enum</returns>
public static ExpressionType FindValue(string value)
{
return FindValue<ExpressionType>(value);
}
/// <summary>
/// Converts the string to ExpressionType instance
/// </summary>
public static implicit operator ExpressionType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Indicates what type of job is being initiated.
/// </summary>
public sealed class RestoreRequestType : ConstantClass
{
public static readonly RestoreRequestType SELECT = new RestoreRequestType("SELECT");
private RestoreRequestType(string value)
: base(value)
{
}
/// <summary>
/// Finds the RestoreRequestType instance for the string value
/// </summary>
public static RestoreRequestType FindValue(string value)
{
return FindValue<RestoreRequestType>(value);
}
/// <summary>
/// Converts the string to RestoreRequestType instance
/// </summary>
public static implicit operator RestoreRequestType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The type of JSON.
/// </summary>
public sealed class JsonType : ConstantClass
{
public static readonly JsonType Document = new JsonType("DOCUMENT");
public static readonly JsonType Lines = new JsonType("LINES");
private JsonType(string value)
: base(value)
{
}
/// <summary>
/// Finds the JsonType instance for the string value
/// </summary>
public static JsonType FindValue(string value)
{
return FindValue<JsonType>(value);
}
/// <summary>
/// Converts the string to JsonType instance
/// </summary>
public static implicit operator JsonType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Specifies object's compression format.
/// </summary>
public sealed class CompressionType : ConstantClass
{
public static readonly CompressionType None = new CompressionType("NONE");
public static readonly CompressionType Gzip = new CompressionType("GZIP");
public static readonly CompressionType Bzip2 = new CompressionType("BZIP2");
private CompressionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the CompressionType instance for the string value
/// </summary>
public static CompressionType FindValue(string value)
{
return FindValue<CompressionType>(value);
}
/// <summary>
/// Converts the string to CompressionType instance
/// </summary>
public static implicit operator CompressionType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The type of ObjectLockEnabled
/// </summary>
public sealed class ObjectLockEnabled : ConstantClass
{
public static readonly ObjectLockEnabled Enabled = new ObjectLockEnabled("Enabled");
public ObjectLockEnabled(string value)
: base(value)
{
}
/// <summary>
/// Finds the ObjectLockEnabled instance for the string value
/// </summary>
public static ObjectLockEnabled FindValue(string value)
{
return FindValue<ObjectLockEnabled>(value);
}
/// <summary>
/// Converts the string to ObjectLockEnabled instance
/// </summary>
public static implicit operator ObjectLockEnabled(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The type of ObjectLockLegalHoldStatus
/// </summary>
public sealed class ObjectLockLegalHoldStatus : ConstantClass
{
public static readonly ObjectLockLegalHoldStatus On = new ObjectLockLegalHoldStatus("ON");
public static readonly ObjectLockLegalHoldStatus Off = new ObjectLockLegalHoldStatus("OFF");
public ObjectLockLegalHoldStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the ObjectLockLegalHoldStatus instance for the string value
/// </summary>
public static ObjectLockLegalHoldStatus FindValue(string value)
{
return FindValue<ObjectLockLegalHoldStatus>(value);
}
/// <summary>
/// Converts the string to ObjectLockLegalHoldStatus instance
/// </summary>
public static implicit operator ObjectLockLegalHoldStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The type of ObjectLockRetentionMode
/// </summary>
public sealed class ObjectLockRetentionMode : ConstantClass
{
public static readonly ObjectLockRetentionMode Governance = new ObjectLockRetentionMode("GOVERNANCE");
public static readonly ObjectLockRetentionMode Compliance = new ObjectLockRetentionMode("COMPLIANCE");
public ObjectLockRetentionMode(string value)
: base(value)
{
}
/// <summary>
/// Finds the ObjectLockRetentionMode instance for the string value
/// </summary>
public static ObjectLockRetentionMode FindValue(string value)
{
return FindValue<ObjectLockRetentionMode>(value);
}
/// <summary>
/// Converts the string to ObjectLockRetentionMode instance
/// </summary>
public static implicit operator ObjectLockRetentionMode(string value)
{
return FindValue(value);
}
}
/// <summary>
/// The type of ObjectLockMode
/// </summary>
public sealed class ObjectLockMode : ConstantClass
{
public static readonly ObjectLockMode Governance = new ObjectLockMode("GOVERNANCE");
public static readonly ObjectLockMode Compliance = new ObjectLockMode("COMPLIANCE");
public ObjectLockMode(string value)
: base(value)
{
}
/// <summary>
/// Finds the ObjectLockMode instance for the string value
/// </summary>
public static ObjectLockMode FindValue(string value)
{
return FindValue<ObjectLockMode>(value);
}
/// <summary>
/// Converts the string to ObjectLockMode instance
/// </summary>
public static implicit operator ObjectLockMode(string value)
{
return FindValue(value);
}
}
}
| 34.90552 | 159 | 0.59188 |
[
"Apache-2.0"
] |
Bio2hazard/aws-sdk-net
|
sdk/src/Services/S3/Custom/S3Enumerations.cs
| 70,197 |
C#
|
using System.Collections.Generic;
using CodingProblems.Other;
using FluentAssertions;
using Xunit;
namespace CodingProblemsTests.Other;
public class AnagramFinder_FindAnagrams
{
[Theory]
[InlineData("cbac", "abc", new[] {0,1})]
[InlineData("cbaebabacd", "abc", new[] {0,6})]
[InlineData("abab", "ab", new[] {0,1,2})]
[InlineData("aa", "a", new[] {0,1})]
[InlineData("af", "be", new int[] {})]
[InlineData("aaabb", "aabbb", new int[] {})]
[InlineData("aac", "abb", new int[] {})]
[InlineData("aaaaaaaaaa", "aaaaaaaaaaaaa", new int[] {})]
[InlineData("oumgfmlrbivgnrvsfslnheghnbhhicbvaddqadwicekguhjairhpqtebqvzyxdfodntxmoqtffgmsomnhndbrffxmuyjvqazwfvugyvmshxignfenmkihorjkshwyuxxkxidpkalqmdnxxmnovhangcwggjwjrletxhelehcipflvqyueptgjxugyipegamjbweqdfeswrjepjjlviuhfikfaojbhrujdfpnenrvajrdplwaevpbzkcdkyhidbgizwofjoxfvnkzhmwvegnfipgmnikljmmcrleffceqsxrxgsjmjmaflnxtigfoeaafsrjaxaqumhatpdeueridyxfjajsjkcrfwkwguclqtrefwevwalmcvoiragprwwnxpwgqoyulsadfhstduevikkkwmofklomdvpdcnxxsotudmkjgakbzopzengbfrvhiikzrsmmurewnnquydhntpqprtyvouatjevvoerbnzunwtdiigohcctulnvpgfbtdjmjsvszphulflmolunohifxsycaiifkngpuycnlihebmhaapureljxlqozydijsbcitfrdjhbdppvhpfjfuxujwfkcezyvhbityajxcccbuyvoluzndgjsyvrbluvagqtuujpsxjcgdtkbhaxsatmellmotdeoxsxjsywuavjqpzjkcpsrowqgogovcouosjhblhdmbkeidafpimjaiypownlcilpahbszmmcwbqmztpdmbqeuizjwdifruojquahdtdukydxgehpourjytveajjvtpiphihkmgqpmnuukpqtjyyqhfsiezugszdbjsseaxxdxomhouvetgcvfeuvwszmhgpkkorubvahxoufpfcukgchdubddpijsolrkvgiizhqefdhvpzvpmuxnwpcaepnpuicgvoxdqfcaabhsxgnorbpkboueplrpztqehrufldndxuenmvynranzqontfihfwvtxmiadbogsawlpmyycaztkyrqxwoxocbtngrmaiyafqqornrknnsmulglzyjnydvwpfefbuwhcocvyczklwywgwergmboqagcsngavorldbpsefoaynkmfqrjzdtbylibwwhhuhfqkoorihjewpcpuxhjnbeiegpplsyrzzyxsnnslvbkslzhwqjzrijdyucnnoshkxbagqdzxwnarwbzivhjpzgvaqrtywqwdetcqtsxviebsnpeflvegyjgxaskwuesfaqdjfdvuklayyekvumbuciranyvymtwshowdxyxbtpuchskraonnwvvvbdehhjdqiluauesssredqoeypadjsahxjqrgxmguppwrydbsiuvhjxyvsseeisbymztpaxclvxsvypdnabnhcnlzelogrfcvvzpwrujkdvwvzlgdbdqgiruxygolkamiluvmfuoaslakmsaehubjxlcfvonmcnqenxwjgypqfedszrisegdtlwhxdsqeyhkynmtdyrjwwslwwtucbtuxxlkymelgqumhgyjnnjtqvaatmcfpbupfszdcuwgbyudffdpxszrqskmnpdqeauilbwnojibjfqwaalwnmevjbbzvptawuemsvlqfmonxycnfnzmgfmwpmjcyvhjfjpyhywjqbtjwhxudqhuclhyfbiuazzvnklkjfiupntduclftpddhfkioqkptklhynubibyjwllgexbjafcgubnelxzdapnxsqtmnqcdscrgpawigubbugtnxvebnrlujkxranwzbiemsvykjlmnyyfkrplutmpohohtqntxmkdfmlwvspedxlgylwbqfbhtolkfbfjfmvbhxafbwmlolagckjeffnwsiesgkhpyeupuyvcmfhlxygrmkkvuarjviqxfgkwturzkzwquefcyelduecwqrachowsxbdcgrvtkmlkyloqjjlyctuzsztafqearzuiogjrfqbseqibzddpabbfhbkeiorgslhecyicrvxvlzynxctnydzpgghjocuqimuxlvwymkhvbaqyljurieblfffxplmfwszrhvqiyzaqruihxvabytqvhmauzmrgcxtiotlkhtqcrugthgerkvixykexnlyxntpgagigdepzchsplujazcqabzvjcvutxriirzeydvffvzhhhihlfwewusmuzeecuytcwermdxpcffsewvyfearxirlmdwqfxsaljqnyvfiibqgxpfgkuoqadxcbdgcrhhrhvrdluzlefeerwhwinuqzuwuvairwqraajnifdihhzuqtciqmkrxafiuixbqacmgxfybmdghunmgwbidvanucokddovmznczycruztcayuwafcvjnqxhzarfvdqfounjciebxngwfwjknqmrappyuiewzdjshsbespzfcrwswtpayqaldwdvwiyoullwxshgzdluqbwecxkiyrqrguyepbcqzgafvjfxkzvglnghbmogenghozxncfenobraxqrhybxcoyovwreawnxiurnggbecnybohhicmvxlexizgvskafbxabzkzuvbrksbanikuewjgbkwcxoqibcpissudhljplgqifaebgxueiukmqxfcjwkysjjyuamlcatwqfhltyrwjdutbqoclvpcyhczybrmsatuwaswlziqqasyedtoxhmhktrjfwytfhxhncwiovjbpimtjpkwmxkalmxdjkwqhtakjraqiykrrmgncirghthsyfuhubmkhduibikgkorispskluycaepxdgxsodeqstbreyfuxtwksqqyqlvzvqtnoirjujqeltakrbiubuoqzyorkgcdkormvctirrowpemxtfgiqpzkadbpxaghodshuxorilbjxfigpcixuhcbaoulyxaoweiaojcbmbptwcfzgvylwcfyvmhoepvexcmkqvlrbknbhvctplytkqjjvmfadhksevedhfhmbhhqzgooudgxuazdskajgvuejhpvgngpfsayyyvupptpjvveuwrsrdwewhwivpmojlvvhnahpqwvrspjpradwkylbsketjriqqpvhhedbhkkvswcvwadunencyxtxmindabykaqoaoeifqdwihohbueikhixdfumrldazczdlorgtcwrrylwjxyxzgmdujwiapwpzrikupdeijmqrarvwhfcgzrkysnwsjeqhqtembrwkcjxtvjwwwkarolvbeczwinodvtgvbbqdwipckezgxwdizrnaxfexnjoafnrqxgywruytmfktkoygmbdwogjfjdvohglnxngnijysafyrlzofdovuslmcnhxfjjitvbdvwbluorpwtmtynrmzjrbiaqvzcqrxppojxnqfebtwpmfvuhigbahvjraidtmmceaxctnbtolhuiqcforksdbypcvjagrvsqguhgbyqgqiruvvqszezfmlntffbdrlcwyjcgriqycabijkokoqzntelifjxzyvytnbfflkoiipilzafyicgniewbuapmfzqcaximlfjhvuurfscozgpgghvsuvpqqtsojdphbumqrluvgnbhlymulcmqziytcampdpdrqvfwxygwbysofektetfrwedzklwgtjytibpdzakxjfvczcfxtdjpbngqzrmvyudslvlqsezwkqkkcbxoipifopzynllvbuujssspdsycqbyvdlgoauisrkvahwipcwukmvllgsaijkdrpuxlzyzsjabsatdgzmbebovnlydvqgjphwxqgfzaqyxadgfdmtbbqlpvciucjdrhlluumnqubughdaauyhkvdekpoamoliyttnyondnmphcesvowghyktattrxhvlbdlrsfjssflnvtyltawmuqoofhvvobkistzasjhmbkessjtditkmxpzlskojwokiatbwhdzjbzbsqkzmnzvdpyaxygrehqgfqqaxnnerizmarbooohufcdhwpvsulsstmcoivxapufjqtnaviffihkpyrbrzfjenqtxlxfqkfjvazubkrdqluffwaluvqilsfrqrdmnhdhrjkbpkgtkznoqnvpswoyndtqqckqqtcubtutrbxrforaitavuazzugvgczvsyfvqnuakykuwczsithogunmpejpmrxcjjvvzbxzyrltihlsirevhjohihonylwsekburnndcwxkybjifubalefhmiiitpqqzjjazsbfgtxopdjvbdgdmcfrfiebeopggbukfxxxcjotbiltihiddnuwrlzvrzsfmgkrulvcwbeqnkkhgobokkkspdzomfgvodqvzrvajlanwbyeioxtxbyfrapsjtgqvqzdoerwkfvzmsbzhumuotznpiozkvodscfaffpgiapftqlrthudvgvenfzyaxaummpmyhyuswvegysoppwnysdpqyzzrubdrenplyiqmmvthtfreynmltqbizpycniwwnunqynfyeigduomqqulemmdjqpndhuxvmizutfzxztrbavfopefglqyvrqwggjnrpnkcyghelmcnmtmtzsepopwzoirjcdjenpuqpvutueinapitkhsmmraytgftzpjlekyhcwdltjjxsycydcvfmzwgbcxcoboqcbxzkszwlhxgpnpynjjhaqucnwhxhoyhqrkeeqgggqliogjuqyxgzcfvhmtkevipopxmowjotswevzmsxngshovradrjxihwbnqqpuhobnmlfassydwmlcgirrhrlxhkchzwrokrllbibjecgqfpttvuerckuegvooxssxvdcemgbuuirzfckxnxwsszrpcuogfuusrplrielkgvhvygnjkfzfzxsqhifoxctfhuipqxctdlvgdkewprxfuxsgfvfqtclxgzsadtvhuvpqrxjjjjrrxqgovoyuipqnhosvoufbqvugpplwzrphrjrnrllxpoxtuwlwkzotpebuamennaapntnneyvhahgxdbhtbqplduxaodhsskkpqynrzonhagrwxcoeagawjvcucsvbotsaelkywjoyeehsbfdwgoqnyyaunvhqdjvtsbxbbbpgfxnngxmikrrgsdbsokwdpyevqoplxqudieqpisrsbfxugybymbjwzoyevpigikboxhdntktxmzvjzywtbvcjrhuhwosrijcqmkfjcqxbitntabzbroolnxjllqfnznkaystntwegkkofkxsyxuamsxpubavzwfoixtjlluujjwifajginhtcywidlmkkhysmulzvzldxwyopdodzryxpkqrdukecragplzfysuwqcqaoqqfjuyfqliwkmvwvfubcklvdhzutgtgumayojpvovumxemspycidbnnmcxyarkxttcvqqhomkilqaqoovnrqlvubeeofiwxjqyayzcycgoiircgxgzhnqrbcgkrofcotpkqouabcqbdrouxxageejbjlfuzmbmfckrqbbyyhzvjrrpzbefamvoufqogovzaokciuzmevfyuaaypyjqggwipkgzkbmlbafbzlljsfmhscsodcrbbfylkfyqxokfgolmosuxpdsjspfciammxqirioodfxngosyzlkltpmsxpafmabupevthayfxdbiovsqxkrenmfkoctidrdqinrqojnelptkuzrcebddkboyxkhrfwrgvikyrvjihcfitdhdtexfnxtcsgmxkntaimhvdrndqprsddtqctysmzounvmsvxxhwgoxegqjqtouwapoxuvbkmpriuanvqoxorjcpprofqdspoosgmmlnztpaubosqqknbbqnhpyyubonpkwmlowfjgpmtgzlqujxljdadtosbhnmngepkjlmvuescozvzclobocahnkyplhqstopknrhufneybwebebhgxvwyydolesgbojzvvndmsgbhxhoybgakgdesrsmvrzhmijyjytdmpdxehxrhgsyiedfrxlgvxpxwyjaxjowwnuujnabjqcylypgduzrwituqvwckkworwlkcluicfwgydzothrmcisvfrhgpnpecbhxisfzchndxftawqybqnfuxetoupeplgxatqxytnfmokteeqmxjemgwrufklkwaxazzgelzfgglhirzjffkoqxmbtwkhhbodamujvwljmlivdbbirtubccsgrvkylyfmppilsxezcdozjpbdfjtnuwgfsreodmpafkzclgtzrgvbewdbaoephgkmwwidfcvzjkvrcafkzfdxxxdpgbqrybzejaaezxrwpxbeziscdwfbfahiefzokbnhgfqxkbcuixenmmnvolepkzkpeasrygpyoummmsoticswegyqyxkaqscmrtsnoblraczloiqcznabchbatdicakdpulzkddhcagdeogibasyddubcezmztaukusexmsjymljapvllrqfhpgkfudyedlcbhwpfimlplclrcxpttnxamzucpfagisbajnyrzvxxlzjolxxisexrojzwcratimkamjliplucbdejtcgwryaweatwbkqardkbmrdbdseggojlslcjhmcumhxikgdzxjuyyjcyyvkvseyvqjewdlrrpnwxltnnedjupeclekzyvoormnowjkrpuwfavricrvjoqqbjqijpqlmsnwmonmbjxvbpokumfvdfnxbhxxsfzxcozwhzmgrwkdczrcigxbuvlnyyuvsraobwuznkxdizyqifjwgtwnmxunhukoeqpxafupdxwzfymwsblpvyyktdspctcxmwsxfqgsgedimmhcqjztpmrbavhogwuhzbngycbggsoakrvuceiditgcwxaopcirtivcibqpxbqdstcokmypyuzlaowongknpzitpdhjkoszoqvdgrtqvckyjmduketumefixobawbekqfrnwebsijgvihedwmegkssznkwgwqgavcakfhdwesqyjvotcevhgltzcknzqrindzbywgiibjsnvsttugwizaxayngnmfsmjopzqygphvxdhdwnrnksdqwnahecbzpxeetihclinvbxmrpoiynuxsyabdmhtaqnjtsiearotujspwgmnjoqgeqbcrbrmssjtbuqciflfjjfxkiapfttwymziapbxjenhwrzcdrjtjudhcztpwqungqidwzjhsgwlxlujrpeepubglthkbnhbdqwwlbjbnndfjupllxyluagyieeurajyhdqcinkmosympawgreeihdjcfggtomoeooqbklqfxoavtpcdhrlcsezabwufygrghnmtdvisfrzfjmmgnqwnxdyvidbxizsunzosikevlwzgrybbidzyytsaspbgbgzrmgimcmmulodqbqljxeusveynagjkphulpqnqkfrbjcvtntzmjwsfifmhsphicrtchdydlklhrdghmtacbjfktgvphhlhhkkcqkytcfgjuoblfdjpkuocherhufixafdbgotxrxrcuohgpxpogfggvkdrkixzfkahtnwhvbntqbrpqxvutbldhrfirzxfupybrvolteycfjkdcaubwtqomzfepcevmpecqpteevaubtbchlaakgqpzvjwqxzbcneektiwhvyoexdufbirqhukdmtlfqtjhboncqciumvxccncrjpecyuctxfdsekblmnpmjkotsfopoeakeetsvagoayijofejkjixevcvopuymjxdpgrjupgbpjpqacdbbcpzuqwaztmxfriypcfdybjamjxflzinuxcszriqnsokpegxzfzgidrjsbfftnzxgcxtbrordopldbrtxqeeeeiixdnedgoaohbadmrnstciefemzhepbfwccdulrgduxhebifzivhzgiueajetcrwqvmeailiyyjclgfeizotkkjiaedwsqsngsoqrpekysgzlmtijsxdrcpjchecchkxhjuyevtdlohohbgrkyfsmygplztmvrgeuqjuenepnsarcopkadsbvvpzmcacliqagsfvsfylfoinibat",
"vxqakfyaqahufxfizupjrkkifjlbfqfeprqrfjvxnubntdtlvz", new [] {4000})]
public void Works(string s, string p, int[] expected)
{
IList<int> result = AnagramFinder.FindAnagrams(s, p);
result.Should().BeEquivalentTo(expected);
}
}
| 329.925926 | 8,069 | 0.964189 |
[
"MIT"
] |
LevYas/CodingProblems
|
CodingProblemsTests/Other/AnagramFinder_FindAnagrams.cs
| 8,910 |
C#
|
using GVFS.Common;
using GVFS.Common.FileSystem;
using GVFS.Common.Tracing;
using System;
using System.IO;
namespace GVFS.Platform.Linux
{
public class ProjFSLib : IKernelDriver
{
public bool EnumerationExpandsDirectories { get; } = true;
public bool EmptyPlaceholdersRequireFileSize { get; } = true;
/* TODO(Linux): check for kernel fuse, libfuse v3, libprojfs;
* flesh out all methods below
*/
public string LogsFolderPath
{
get
{
return Path.Combine(System.IO.Path.GetTempPath(), "ProjFSLib");
}
}
public bool IsGVFSUpgradeSupported()
{
return false;
}
public bool IsSupported(string normalizedEnlistmentRootPath, out string warning, out string error)
{
warning = null;
error = null;
return true;
}
public bool TryFlushLogs(out string error)
{
Directory.CreateDirectory(this.LogsFolderPath);
error = string.Empty;
return true;
}
public bool IsReady(JsonTracer tracer, string enlistmentRoot, TextWriter output, out string error)
{
error = null;
return true;
}
public bool RegisterForOfflineIO()
{
return true;
}
public bool UnregisterForOfflineIO()
{
return true;
}
public bool TryPrepareFolderForCallbacks(string folderPath, out string error, out Exception exception)
{
error = null;
exception = null;
return true;
}
}
}
| 24.826087 | 110 | 0.556334 |
[
"MIT"
] |
Personalhomeman/VFSForGit
|
GVFS/GVFS.Platform.Linux/ProjFSLib.cs
| 1,713 |
C#
|
// MIT License - Copyright (c) Callum McGing
// This file is subject to the terms and conditions defined in
// LICENSE, which is part of this source code package
using System;
namespace LibreLancer
{
public delegate void MouseWheelEventHandler(int amount);
public delegate void MouseEventHandler(MouseEventArgs e);
public class Mouse
{
public int X { get; internal set; }
public int Y { get; internal set; }
public MouseButtons Buttons { get; internal set; }
public event MouseWheelEventHandler MouseWheel;
public event MouseEventHandler MouseMove;
public event MouseEventHandler MouseDown;
public event MouseEventHandler MouseUp;
public int MouseDelta = 0;
internal Mouse ()
{
}
public bool IsButtonDown(MouseButtons b)
{
return (Buttons & b) == b;
}
internal void OnMouseMove()
{
if (MouseMove != null)
MouseMove (new MouseEventArgs (X, Y, Buttons));
}
internal void OnMouseDown(MouseButtons b)
{
if (MouseDown != null)
MouseDown (new MouseEventArgs (X, Y, b));
}
internal void OnMouseUp (MouseButtons b)
{
if (MouseUp != null)
MouseUp (new MouseEventArgs (X, Y, b));
}
internal void OnMouseWheel(int amount)
{
MouseDelta += amount;
if (MouseWheel != null)
MouseWheel (amount);
}
}
}
| 21.830508 | 62 | 0.697205 |
[
"MIT"
] |
HaydnTrigg/Librelancer
|
src/LibreLancer.Base/Input/Mouse.cs
| 1,290 |
C#
|
using EntityG.BusinessLogic.Interfaces.Services.Account;
using EntityG.Contracts.Requests.Identity;
using EntityG.EntityFramework.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace EntityG.Server.Controllers.Identity
{
[Authorize]
[Route("api/identity/account")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly IAccountService _accountService;
private readonly ICurrentUserService _currentUser;
public AccountController(IAccountService accountService, ICurrentUserService currentUser)
{
_accountService = accountService;
_currentUser = currentUser;
}
[HttpPut(nameof(UpdateProfile))]
public async Task<ActionResult> UpdateProfile(UpdateProfileRequest model)
{
var response = await _accountService.UpdateProfileAsync(model, _currentUser.UserId);
return Ok(response);
}
[HttpPut(nameof(ChangePassword))]
public async Task<ActionResult> ChangePassword(ChangePasswordRequest model)
{
var response = await _accountService.ChangePasswordAsync(model, _currentUser.UserId);
return Ok(response);
}
[HttpGet("profile-picture/{userId}")]
public async Task<IActionResult> GetProfilePictureAsync(string userId)
{
return Ok(await _accountService.GetProfilePictureAsync(userId));
}
[HttpPost("profile-picture/{userId}")]
public async Task<IActionResult> UpdateProfilePictureAsync(UpdateProfilePictureRequest request)
{
return Ok(await _accountService.UpdateProfilePictureAsync(request, _currentUser.UserId));
}
}
}
| 36.08 | 103 | 0.701774 |
[
"MIT"
] |
jackiesphan1996/EntityG-HRM
|
EntityG/Server/Controllers/Identity/AccountController.cs
| 1,806 |
C#
|
using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
namespace S22.Mail {
[Serializable]
public class SerializableLinkedResource {
public static implicit operator LinkedResource(SerializableLinkedResource resource) {
if (resource == null)
return null;
LinkedResource r = new LinkedResource(resource.ContentStream);
r.ContentId = resource.ContentId;
r.ContentType = resource.ContentType;
r.TransferEncoding = resource.TransferEncoding;
return null;
}
public static implicit operator SerializableLinkedResource(LinkedResource resource) {
if (resource == null)
return null;
return new SerializableLinkedResource(resource);
}
private SerializableLinkedResource(LinkedResource resource) {
ContentLink = resource.ContentLink;
ContentId = resource.ContentId;
ContentStream = new MemoryStream();
resource.ContentStream.CopyTo(ContentStream);
resource.ContentStream.Position = 0;
ContentType = resource.ContentType;
TransferEncoding = resource.TransferEncoding;
}
public Uri ContentLink { get; set; }
public string ContentId { get; set; }
public Stream ContentStream { get; private set; }
public SerializableContentType ContentType { get; set; }
public TransferEncoding TransferEncoding { get; set; }
}
}
| 30.325581 | 87 | 0.759202 |
[
"MIT"
] |
albertospelta/S22.Mail
|
SerializableMailMessage/SerializableLinkedResource.cs
| 1,306 |
C#
|
namespace Umbraco.Core.Migrations.PostMigrations
{
/// <summary>
/// Rebuilds the published snapshot.
/// </summary>
public class RebuildPublishedSnapshot : IMigration
{
private readonly IPublishedSnapshotRebuilder _rebuilder;
/// <summary>
/// Initializes a new instance of the <see cref="RebuildPublishedSnapshot"/> class.
/// </summary>
public RebuildPublishedSnapshot(IPublishedSnapshotRebuilder rebuilder)
{
_rebuilder = rebuilder;
}
/// <inheritdoc />
public void Migrate()
{
_rebuilder.Rebuild();
}
}
}
| 25.96 | 91 | 0.600924 |
[
"MIT"
] |
0Neji/Umbraco-CMS
|
src/Umbraco.Core/Migrations/PostMigrations/RebuildPublishedSnapshot.cs
| 651 |
C#
|
// Basic example on how to work with R&S RsSmab driver package
// The example does the following:
// - Initializes the session - see the commented lines on how to initialize the session with the specified VISA or no VISA at all
// - Reads the standard information of the instrument
// - Does couple of standard RF settings
// - Shows the standard SCPI write / query communication
// Make sure you:
// - Install the RsSmab driver package over Packet Manager from Nuget.org
// - Adjust the IP address the match your instrument
using System;
using RohdeSchwarz.RsSmab;
namespace RsSmab_Example
{
class Program
{
static void Main()
{
var smab = new RsSmab("TCPIP::10.112.1.64::INSTR", true, true);
//var smab = new RsSmab("TCPIP::10.112.1.73::INSTR", true, true, "SelectVisa=RsVisa"); // Forcing R&S VISA
//var smab = new RsSmab("TCPIP::10.112.1.73::5025::SOCKET", true, true, "SelectVisa=SocketIo"); // No VISA needed
Console.WriteLine("Driver Info: " + smab.Utilities.Identification.DriverVersion);
Console.WriteLine($"Selected Visa: {smab.Utilities.Identification.VisaManufacturer}, DLL: {smab.Utilities.Identification.VisaDllName}");
Console.WriteLine("Instrument: " + smab.Utilities.Identification.IdnString);
Console.WriteLine("Instrument options: " + string.Join(",", smab.Utilities.Identification.InstrumentOptions));
// Driver's instrument status checking ( SYST:ERR? ) after each command (default value is true):
smab.Utilities.InstrumentStatusChecking = true;
smab.Utilities.Reset();
// Set the output -21.3 dBm, 224 MHz
smab.Output.State.Value = true;
smab.Source.Power.Level.Immediate.Amplitude = -21.3;
smab.Source.Frequency.Fixed.Value = 234E6;
// Direct SCPI interface:
var response = smab.Utilities.QueryString("*IDN?");
Console.WriteLine($"Direct SCPI response on *IDN?: {response}");
// Closing the session
smab.Dispose();
Console.Write("\n\nPress any key...");
Console.ReadKey();
}
}
}
| 44.857143 | 148 | 0.647862 |
[
"MIT"
] |
Rohde-Schwarz/Examples
|
SignalGenerators/Csharp/RsSmab_ScpiPackage/RsSmab_Simple_RFsettings_Example/Program.cs
| 2,200 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace sly.parser.syntax
{
public class TerminalClause<T> : IClause<T>
{
public T ExpectedToken {get; set;}
public bool Discarded { get; set; }
public TerminalClause(T token) {
ExpectedToken = token;
}
public TerminalClause(T token, bool discard) : this(token)
{
Discarded = discard;
}
public bool Check(T nextToken) {
return nextToken.Equals(ExpectedToken);
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.Append(ExpectedToken.ToString());
if (Discarded)
{
b.Append("[d]");
}
return b.ToString();
}
public bool MayBeEmpty()
{
return false;
}
}
}
| 21.545455 | 66 | 0.506329 |
[
"MIT"
] |
dotted/csly
|
sly/parser/syntax/TerminalClause.cs
| 948 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using AutoRest.Core.Model;
using Newtonsoft.Json;
namespace AutoRest.Ruby.Model
{
/// <summary>
/// The model for method group template.
/// </summary>
public class MethodGroupRb : MethodGroup
{
/// <summary>
/// Initializes a new instance of the class MethodGroupTemplateModel.
/// </summary>
/// <param name="name">The method group name.</param>
public MethodGroupRb(string name):base(name)
{
}
public MethodGroupRb() : base()
{
}
[JsonIgnore]
public IEnumerable<MethodRb> MethodTemplateModels => Methods.Cast<MethodRb>();
/// <summary>
/// Gets the list of modules/classes which need to be included.
/// </summary>
public virtual IEnumerable<string> Includes => Enumerable.Empty<string>();
}
}
| 30.527778 | 96 | 0.614195 |
[
"MIT"
] |
Azure/autorest.ruby
|
src/vanilla/Model/MethodGroupRb.cs
| 1,101 |
C#
|
namespace Machete.X12Schema.V5010
{
using System;
using X12;
public interface BPR :
X12Segment
{
Value<string> TransactionHandlingCode { get; }
Value<decimal> TotalActualProviderPaymentAmount { get; }
Value<string> CreditOrDebitFlagCode { get; }
Value<string> PaymentMethodCode { get; }
Value<string> PaymentFormatCode { get; }
Value<string> SenderDfiIdNumberQualifier { get; }
Value<string> SenderDfiIdNumber { get; }
Value<string> SenderAccountNumberQualifier { get; }
Value<string> SenderAccountNumber { get; }
Value<string> OriginatingCompanyId { get; }
Value<string> OriginatingCompanySupplementalCode { get; }
Value<string> ReceiverDfiIdNumberQualifier { get; }
Value<string> ReceiverDfiIdNumber { get; }
Value<string> ReceiverAccountNumberQualifier { get; }
Value<string> ReceiverAccountNumber { get; }
Value<DateTime> CheckIssueOrEftEffectiveDate { get; }
}
}
| 25.833333 | 66 | 0.630415 |
[
"Apache-2.0"
] |
AreebaAroosh/Machete
|
src/Machete.X12Schema/Generated/V5010/Segments/BPR.cs
| 1,085 |
C#
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for DisksOperations.
/// </summary>
public static partial class DisksOperationsExtensions
{
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DiskInner> CreateOrUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskInner disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DiskInner> UpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdateInner disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DiskInner> GetAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponseInner> DeleteAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DiskInner>> ListByResourceGroupAsync(this IDisksOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DiskInner>> ListAsync(this IDisksOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessUriInner> GrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessDataInner grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponseInner> RevokeAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RevokeAccessWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DiskInner> BeginCreateOrUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskInner disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DiskInner> BeginUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdateInner disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponseInner> BeginDeleteAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessUriInner> BeginGrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessDataInner grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the managed disk that is being created. The name can't be
/// changed after the disk is created. Supported characters for the name are
/// a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponseInner> BeginRevokeAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRevokeAccessWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DiskInner>> ListByResourceGroupNextAsync(this IDisksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DiskInner>> ListNextAsync(this IDisksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 48.906091 | 255 | 0.564015 |
[
"MIT"
] |
abharath27/azure-libraries-for-net
|
src/ResourceManagement/Compute/Generated/DisksOperationsExtensions.cs
| 19,269 |
C#
|
using AutoMapper;
using Sample.Common.Dto;
using Sample.WebApi.Controllers.Parameters;
using Sample.WebApi.Controllers.ViewModels;
namespace Sample.WebApi.Infrastructure
{
/// <summary>
/// Controller Mapping 定義檔
/// </summary>
/// <seealso cref="AutoMapper.Profile" />
public class ControllerProfile : Profile
{
/// <summary>
/// Initializes a new instance of the <see cref="ControllerProfile"/> class.
/// </summary>
public ControllerProfile()
{
this.CreateMap<BlogParameter, BlogDto>();
this.CreateMap<BlogDto, BlogViewModel>();
this.CreateMap<BlogQueryParameter, BlogQueryDto>();
}
}
}
| 29.291667 | 84 | 0.634424 |
[
"MIT"
] |
raychiutw/webapi-dotnet
|
src/Sample.WebApi/Infrastructure/ControllerProfile.cs
| 711 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MasterPageEduc_mehman : System.Web.UI.MasterPage
{
Class1 c1 = new Class1();
protected void Page_Load(object sender, EventArgs e)
{
//تعداد بازدید ها
//Label1.Text = Application["c"].ToString();
//تعداد افراد آنلااین
//Label2.Text = Application["OnlineUsers"].ToString();
//Label3.Text = Class1.GetClockShamsi();
// Label4.Text = DateTime.Now.ToLongTimeString();
if (int.Parse(Class1.Count_login_rpt()) >= 50)
{
c1.CmdSqlDataBaesAccess("Delete From rpt_log");
}
else
{
c1.CmdSqlDataBaesAccess("insert into rpt_log(us,date_login,ip_login,contry,city)values('مهمان','" + Class1.date_login_logout + "','" + Class1.GetUsersIP() + "','','')");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string lbl_6 = "";
int r_b1 = 0, r_b2 = 0, r_b3 = 0, r_b4 = 0;
Button btn = sender as Button;
GridViewRow row = btn.NamingContainer as GridViewRow;
RadioButton rb1 = row.FindControl("RadioButton1") as RadioButton;
RadioButton rb2 = row.FindControl("RadioButton2") as RadioButton;
RadioButton rb3 = row.FindControl("RadioButton3") as RadioButton;
RadioButton rb4 = row.FindControl("RadioButton4") as RadioButton;
Label lbl6 = row.FindControl("Label6") as Label;
lbl_6 = lbl6.Text;
if (rb1.Checked == true) r_b1 = 1;
if (rb2.Checked == true) r_b2 = 1;
if (rb3.Checked == true) r_b3 = 1;
if (rb4.Checked == true) r_b4 = 1;
c1.CmdSqlDataBaesAccess("update nazarsanji set a=a+'" + r_b1 + "',b=b+'" + r_b2 + "',c=c+'" + r_b3 + "',d=d+'" + r_b4 + "' where code='" + lbl_6 + "' ");
if (Class1.statue_insert_Data_DB == "insert_succes")
{
Response.Write("<script> alert('عملیات ثبت با موفقیت انجام شد'); window.location = location.href;</script>");
}
else if (Class1.statue_insert_Data_DB == "insert_error")
{
Response.Write("<script> alert('خطا دارد: لطفا دوباره امتحان کنید'); window.location = location.href;</script>");
}
}
}
| 26.44086 | 182 | 0.577064 |
[
"MIT"
] |
JeloH/Jelodar
|
MasterPageEduc_mehman.master.cs
| 2,549 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using LodeRunner.API.Models;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace LodeRunner.API
{
/// <summary>
/// Cosmos Health Check.
/// </summary>
public partial class CosmosHealthCheck : IHealthCheck
{
private const int MaxResponseTime = 200;
private readonly Stopwatch stopwatch = new ();
/// <summary>
/// Build the response.
/// </summary>
/// <param name="uri">string.</param>
/// <param name="targetDurationMs">double (ms).</param>
/// <param name="ex">Exception (default = null).</param>
/// <param name="data">Dictionary(string, object).</param>
/// <param name="testName">Test Name.</param>
/// <returns>HealthzCheck.</returns>
private HealthzCheck BuildHealthzCheck(string uri, double targetDurationMs, Exception ex = null, Dictionary<string, object> data = null, string testName = null)
{
this.stopwatch.Stop();
// create the result
HealthzCheck result = new ()
{
Endpoint = uri,
Status = HealthStatus.Healthy,
Duration = this.stopwatch.Elapsed,
TargetDuration = new System.TimeSpan(0, 0, 0, 0, (int)targetDurationMs),
ComponentId = testName,
ComponentType = "datastore",
};
// check duration
if (result.Duration.TotalMilliseconds > targetDurationMs)
{
result.Status = HealthStatus.Degraded;
result.Message = HealthzCheck.TimeoutMessage;
}
// add the exception
if (ex != null)
{
result.Status = HealthStatus.Unhealthy;
result.Message = ex.Message;
}
// add the results to the dictionary
if (data != null && !string.IsNullOrEmpty(testName))
{
data.Add(testName + ":responseTime", result);
}
return result;
}
/// <summary>
/// Get Client by ClientStatus Id Healthcheck.
/// </summary>
/// <returns>HealthzCheck.</returns>
private async Task<HealthzCheck> GetClientStatusByClientStatusIdAsync(string clientStatusId, Dictionary<string, object> data = null)
{
const string name = "getClientByClientStatusId";
string path = "/api/clients/" + clientStatusId;
this.stopwatch.Restart();
try
{
await this.clientStatusService.Get(clientStatusId);
return this.BuildHealthzCheck(path, MaxResponseTime / 2, null, data, name);
}
catch (Exception ex)
{
this.BuildHealthzCheck(path, MaxResponseTime / 2, ex, data, name);
// throw the exception so that HealthCheck logs
throw;
}
}
/// <summary>
/// Get Clients Healthcheck.
/// </summary>
/// <returns>HealthzCheck.</returns>
private async Task<HealthzCheck> GetClientStatusesAsync(Dictionary<string, object> data = null)
{
const string name = "getClients";
string path = "/api/clients";
this.stopwatch.Restart();
try
{
await this.clientStatusService.GetMostRecent(1);
return this.BuildHealthzCheck(path, MaxResponseTime, null, data, name);
}
catch (Exception ex)
{
this.BuildHealthzCheck(path, MaxResponseTime, ex, data, name);
// throw the exception so that HealthCheck logs
throw;
}
}
}
}
| 33.139344 | 168 | 0.557012 |
[
"MIT"
] |
cloudatx/loderunner
|
src/LodeRunner.API/src/HealthChecks/CosmosHealthCheckDetails.cs
| 4,043 |
C#
|
using System;
using System.Collections.Generic;
namespace GoogleMapsApi
{
public interface IRectangle
{
/// <summary>
/// This event is fired when the DOM click event is fired on the Rectangle.
/// </summary>
event Action<IRectangle, GeographicLocation> Click;
/// <summary>
/// This event is fired when the Rectangle is right-clicked on.
/// </summary>
event Action<IRectangle, GeographicLocation> RightClick;
/// <summary>
/// This event is fired when the DOM dblclick event is fired on the Rectangle.
/// </summary>
event Action<IRectangle, GeographicLocation> DoubleClick;
/// <summary>
/// The ID of the Rectangle
/// </summary>
int RectangleId { get; }
/// <summary>
/// The bounds of this rectangle.
/// </summary>
GeographicBounds Bounds { get; }
/// <summary>
/// Visibility of the Rectangle
/// </summary>
bool Visible { get; set; }
/// <summary>
/// Whether this shape can be edited by the user.
/// </summary>
bool Editable { get; set; }
}
}
| 27.837209 | 86 | 0.562239 |
[
"MIT"
] |
kellerw/WindowCakeGraphs
|
GoogleMapsApi/Interfaces/IRectangle.cs
| 1,199 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour {
public string _name;
public Slot[] _slots;
private Notification _notification;
private InfoPanel _infoPanel;
private int _secondsElapsed = 0;
public struct Slot {
public GameObject slotObject;
public Image icon;
public Text amountText;
public int amount;
public Item item;
public byte level;
public bool hasProfession;
public string profession;
}
private void Start() {
_notification = GameObject.FindObjectOfType<Notification>();
_infoPanel = GameObject.FindObjectOfType<InfoPanel>();
_slots = new Slot[transform.childCount];
for (int i = 0; i < _slots.Length; i++) {
int j = i; //VEGCONV
_slots[i].slotObject = transform.GetChild(i).gameObject;
_slots[i].slotObject.GetComponent<Button>().onClick.AddListener(() => _infoPanel.CheckForDoubleClick(_name, j));
_slots[i].icon = transform.GetChild(i).GetChild(0).GetComponent<Image>();
_slots[i].amountText = transform.GetChild(i).GetChild(1).GetComponent<Text>();
}
StartCoroutine(ProductDistributionTimer());
}
private IEnumerator ProductDistributionTimer() {
while (true) {
yield return new WaitForSeconds(1);
_secondsElapsed++;
for (int i = 0; i < _slots.Length; i++) {
if (_slots[i].item && _slots[i].item.type == Item.Type.CHICKEN) {
if (_secondsElapsed % _slots[i].item.rate == 0) {
AddItems(_slots[i].item.product, 1);
_notification.AddNotification(_slots[i].item.itemName + " added 1 " + _slots[i].item.product, 0);
}
}
}
}
}
public void UpdateSlotUI(int index) {
Slot curSlot = _slots[index];
if (!curSlot.item) {
curSlot.icon.color = new Color(0, 0, 0, 0);
curSlot.icon.sprite = null;
curSlot.amountText.text = string.Empty;
}
else {
curSlot.icon.color = new Color(1, 1, 1, 1);
curSlot.icon.sprite = curSlot.item.icon;
if (curSlot.amount > 1)
curSlot.amountText.text = curSlot.amount.ToString();
}
}
public void UpdateInventoryUI() {
for (int i = 0; i < _slots.Length; i++)
UpdateSlotUI(i);
}
public void AddItems(Item item, int amount) {
StartCoroutine(AddItemsEnumerator(item, amount));
}
public IEnumerator AddItemsEnumerator(Item item, int amount) {
bool availableSlot = false;
for (int a = 0; a < amount; a++) {
for (int i = 0; i < _slots.Length; i++) {
if (_slots[i].item == item && _slots[i].amount < _slots[i].item.maxStack) {
_slots[i].amount++;
if (_slots[i].amount < _slots[i].item.maxStack) availableSlot = true;
UpdateSlotUI(i);
break;
} else if (i == _slots.Length - 1)
availableSlot = false;
}
if (!availableSlot) {
for (int i = 0; i < _slots.Length; i++) {
if (!_slots[i].item) {
_slots[i].item = item;
_slots[i].amount++;
UpdateSlotUI(i);
break;
}
}
}
}
yield return null;
}
public void RemoveAllItems() {
for (int i = 0; i < _slots.Length; i++) {
_slots[i].amount = 0;
_slots[i].item = null;
_slots[i].level = 0;
UpdateSlotUI(i);
}
}
public void RemoveItemsInSlot(int slotIndex, int amount) {
if (amount < 0 || amount >= _slots[slotIndex].amount) {
_slots[slotIndex].amount = 0;
_slots[slotIndex].item = null;
_slots[slotIndex].level = 0;
} else _slots[slotIndex].amount -= amount;
UpdateSlotUI(slotIndex);
}
}
| 27.804878 | 115 | 0.660526 |
[
"MIT"
] |
Tuccster/chickens-game
|
Assets/Scripts/Inventory.cs
| 3,422 |
C#
|
using ITGlobal.MarkDocs.Cache.Model;
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ITGlobal.MarkDocs.Source
{
/// <summary>
/// Page anchor list
/// </summary>
[PublicAPI]
public sealed class PageAnchors : IReadOnlyList<PageAnchor>
{
private readonly PageAnchor[] _array;
private readonly Dictionary<string, PageAnchor> _byId
= new Dictionary<string, PageAnchor>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// .ctor
/// </summary>
public PageAnchors([CanBeNull] PageAnchorModel[] array)
: this(array?.Select(PageAnchor.FromModel).ToArray() ?? System.Array.Empty<PageAnchor>())
{
}
/// <summary>
/// .ctor
/// </summary>
public PageAnchors([NotNull] PageAnchor[] array)
{
_array = array;
foreach (var a in array)
{
Walk(a);
}
void Walk(PageAnchor anchor)
{
_byId[anchor.Id] = anchor;
if (anchor.Nested != null)
{
foreach (var a in anchor.Nested)
{
Walk(a);
}
}
}
}
/// <inheritdoc />
public int Count => _array.Length;
/// <inheritdoc />
[NotNull]
public PageAnchor this[int index] => _array[index];
/// <summary>
/// Gets an anchor by its href
/// </summary>
[CanBeNull]
public PageAnchor this[string id]
{
get
{
_byId.TryGetValue(id, out var anchor);
return anchor;
}
}
/// <inheritdoc />
public IEnumerator<PageAnchor> GetEnumerator()
{
foreach (var a in _array)
{
yield return a;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| 25.440476 | 101 | 0.486664 |
[
"MIT"
] |
ITGlobal/MarkDocs
|
src/ITGlobal.MarkDocs.Core/Source/PageAnchors.cs
| 2,139 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition
{
using Microsoft.Azure.Management.AppService.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
/// <summary>
/// The stage of contact definition allowing 2nd line of address to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithAddressLine2<ParentT> :
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithCity<ParentT>
{
/// <summary>
/// Specifies the 2nd line of the address.
/// </summary>
/// <param name="addressLine2">The 2nd line of the address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithCity<ParentT> WithAddressLine2(string addressLine2);
}
/// <summary>
/// The final stage of the domain contact definition.
/// At this stage, any remaining optional settings can be specified, or the domain contact definition
/// can be attached to the parent domain definition using WithAttach.attach().
/// </summary>
/// <typeparam name="ParentT">The return type of WithAttach.attach().</typeparam>
public interface IWithAttach<ParentT> :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithOrganization<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithJobTitle<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithFaxNumber<ParentT>
{
Microsoft.Azure.Management.AppService.Fluent.Models.Contact Build { get; }
}
/// <summary>
/// The stage of contact definition allowing city to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithCity<ParentT>
{
/// <summary>
/// Specifies the city of the address.
/// </summary>
/// <param name="city">The city of the address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithStateOrProvince<ParentT> WithCity(string city);
}
/// <summary>
/// The stage of contact definition allowing country to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithCountry<ParentT>
{
/// <summary>
/// Specifies the country of the address.
/// </summary>
/// <param name="country">The country of the address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithPostalCode<ParentT> WithCountry(CountryISOCode country);
}
/// <summary>
/// The stage of contact definition allowing phone number to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithPhoneNumber<ParentT>
{
/// <summary>
/// Specifies the phone number.
/// </summary>
/// <param name="phoneNumber">Phone number.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAttach<ParentT> WithPhoneNumber(string phoneNumber);
}
/// <summary>
/// The entirety of a domain contact definition.
/// </summary>
/// <typeparam name="ParentT">The return type of the final Attachable.attach().</typeparam>
public interface IDefinition<ParentT> :
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IBlank<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithFirstName<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithMiddleName<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAddressLine1<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAddressLine2<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithCity<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithStateOrProvince<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithCountry<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithPostalCode<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithEmail<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithPhoneCountryCode<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithPhoneNumber<ParentT>,
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of contact definition allowing email to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithEmail<ParentT>
{
/// <summary>
/// Specifies the email.
/// </summary>
/// <param name="email">Contact's email address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAddressLine1<ParentT> WithEmail(string email);
}
/// <summary>
/// The stage of contact definition allowing organization to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithOrganization<ParentT>
{
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAttach<ParentT> WithOrganization(string organziation);
}
/// <summary>
/// The stage of contact definition allowing job title to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithJobTitle<ParentT>
{
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAttach<ParentT> WithJobTitle(string jobTitle);
}
/// <summary>
/// The stage of contact definition allowing first name to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithFirstName<ParentT>
{
/// <summary>
/// Specifies the first name.
/// </summary>
/// <param name="firstName">The first name.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithMiddleName<ParentT> WithFirstName(string firstName);
}
/// <summary>
/// The stage of contact definition allowing middle name to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithMiddleName<ParentT> :
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithLastName<ParentT>
{
/// <summary>
/// Specifies the middle name.
/// </summary>
/// <param name="middleName">The middle name.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithLastName<ParentT> WithMiddleName(string middleName);
}
/// <summary>
/// The stage of contact definition allowing fax number to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithFaxNumber<ParentT>
{
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAttach<ParentT> WithFaxNumber(string faxNumber);
}
/// <summary>
/// The first stage of a domain contact definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IBlank<ParentT> :
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithFirstName<ParentT>
{
}
/// <summary>
/// The stage of contact definition allowing phone country code to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithPhoneCountryCode<ParentT>
{
/// <summary>
/// Specifies the country code of the phone number.
/// </summary>
/// <param name="code">The country code.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithPhoneNumber<ParentT> WithPhoneCountryCode(CountryPhoneCode code);
}
/// <summary>
/// The stage of contact definition allowing last name to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithLastName<ParentT>
{
/// <summary>
/// Specifies the last name.
/// </summary>
/// <param name="lastName">The last name.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithEmail<ParentT> WithLastName(string lastName);
}
/// <summary>
/// The stage of contact definition allowing 1st line of address to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithAddressLine1<ParentT>
{
/// <summary>
/// Specifies the 1st line of the address.
/// </summary>
/// <param name="addressLine1">The 1st line of the address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithAddressLine2<ParentT> WithAddressLine1(string addressLine1);
}
/// <summary>
/// The stage of contact definition allowing postal/zip code to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithPostalCode<ParentT>
{
/// <summary>
/// Specifies the postal code or zip code of the address.
/// </summary>
/// <param name="postalCode">The postal code of the address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithPhoneCountryCode<ParentT> WithPostalCode(string postalCode);
}
/// <summary>
/// The stage of contact definition allowing state/province to be set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching.</typeparam>
public interface IWithStateOrProvince<ParentT>
{
/// <summary>
/// Specifies the state or province of the address.
/// </summary>
/// <param name="stateOrProvince">The state or province of the address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.AppService.Fluent.DomainContact.Definition.IWithCountry<ParentT> WithStateOrProvince(string stateOrProvince);
}
}
| 49.936 | 148 | 0.696572 |
[
"MIT"
] |
AntoineGa/azure-libraries-for-net
|
src/ResourceManagement/AppService/Domain/DomainContact/Definition/IDefinition.cs
| 12,484 |
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.