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 |
|---|---|---|---|---|---|---|---|---|
// 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 Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
namespace Unicord.Universal.Controls.Markdown.Render
{
/// <summary>
/// An interface used to handle links in the markdown.
/// </summary>
public interface ILinkRegister
{
/// <summary>
/// Registers a Hyperlink with a LinkUrl.
/// </summary>
/// <param name="newHyperlink">Hyperlink to Register.</param>
/// <param name="linkUrl">Url to Register.</param>
void RegisterNewHyperLink(Hyperlink newHyperlink, string linkUrl);
/// <summary>
/// Registers a Hyperlink with a LinkUrl.
/// </summary>
/// <param name="newImagelink">ImageLink to Register.</param>
/// <param name="linkUrl">Url to Register.</param>
/// <param name="isHyperLink">Is Image an IsHyperlink.</param>
void RegisterNewHyperLink(Image newImagelink, string linkUrl, bool isHyperLink);
}
} | 38.433333 | 88 | 0.658283 | [
"MIT"
] | UnicordDev/Unicord | Unicord.Universal/Controls/MarkdownTextBlock/Render/ILinkRegister.cs | 1,153 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace Microsoft.Diagnostics.Runtime.ICorDebug
{
[ComImport]
[Guid("3D6F5F61-7538-11D3-8D5B-00104B35E7EF")]
[CoClass(typeof(EmbeddedCLRCorDebugClass))]
public interface EmbeddedCLRCorDebug : ICorDebug
{
}
} | 31.733333 | 71 | 0.754202 | [
"MIT"
] | DamirAinullin/clrmd | src/Microsoft.Diagnostics.Runtime/src/ICorDebug/CorDebugWrappers/EmbeddedCLRCorDebug.cs | 476 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediatR;
namespace TestData.Interface.MediatR
{
public class MediatRDispatcher: IDispatcher
{
private readonly IMediator _mediator;
public MediatRDispatcher(IMediator mediator)
{
_mediator = mediator;
}
public Task<IEnumerable<string>> DispatchAsync(IDataSetRequest request)
{
var newRequest = new DataSetRequest
{
DataSet = request.DataSet,
Properties = request.Properties
};
return _mediator.SendAsync(newRequest);
}
}
}
| 23.633333 | 79 | 0.624824 | [
"MIT"
] | kiandra-it/test-data | src/TestData.Interface.MediatR/MediatRDispatcher.cs | 711 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalUInt641()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalUInt641
{
private struct TestStruct
{
public Vector128<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalUInt641 testClass)
{
var result = Sse2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector128<UInt64> _clsVar;
private Vector128<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalUInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalUInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftLeftLogical(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftLeftLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt641();
var result = Sse2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ulong)(firstOp[0] << 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(firstOp[i] << 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<UInt64>(Vector128<UInt64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 38.744898 | 188 | 0.581117 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/X86/Sse2/ShiftLeftLogical.UInt64.1.cs | 15,188 | C# |
using System;
namespace WaterOverflow
{
class Program
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
int capacity = 255;
int sum = 0;
for (int i = 0; i < number; i++)
{
int litersToPour = int.Parse(Console.ReadLine());
if (sum + litersToPour > capacity)
{
Console.WriteLine("Insufficient capacity!");
}
else
{
sum += litersToPour;
}
}
Console.WriteLine(sum);
}
}
}
| 21.774194 | 65 | 0.407407 | [
"MIT"
] | hidden16/SoftUni-Fundamentals | DataTypesAndVariables/WaterOverflow/Program.cs | 677 | C# |
namespace WebApp.Etc.EF
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
public abstract class Repository<TEntity, TDbType> : IRepository<TEntity, TDbType>, IIdentifiable where TEntity : class, IIdentifiable, new() where TDbType : DbContext, new()
{
[Key]
public Guid UID { get; set; }
private TDbType Context
{
get
{
lock (Guarder)
{
return _clrDbType ?? (_clrDbType = new TDbType());
}
}
}
#region Repository Implementation
public bool Insert()
{
Context.Attach(this);
Context.Entry(this).State = EntityState.Added;
var result = Context.SaveChanges();
Trace.WriteLine($"{this} ef:delete result: {result}");
return result > 0;
}
public bool Update()
{
try
{
Context.Attach(this);
Context.Entry(this).State = EntityState.Modified;
var result = Context.SaveChangesAsync().Result;
Trace.WriteLine($"{this} ef:update result: {result}");
return result > 0;
}
catch (Exception e)
{
Trace.WriteLine($"{this} ef:update fault {e}");
return default;
}
}
public bool Remove()
{
try
{
Context.Attach(this);
Context.Entry(this).State = EntityState.Deleted;
var result = Context.SaveChanges();
Trace.WriteLine($"{this} ef:delete result: {result}");
return result > 0;
}
catch (Exception e)
{
Trace.WriteLine($"{this} ef:remove fault {e}");
return default;
}
}
#endregion
#region Static
public static List<TEntity> GetAll() => getQuery().ToList();
public static TEntity GetByID(Guid id) => getQuery().FirstOrDefault(x => x.UID == id);
public static TEntity FirstOrDefault(Func<TEntity, bool> predicate) => getQuery().FirstOrDefault(predicate);
public static IEnumerable<TEntity> Where(Func<TEntity, bool> predicate) => getQuery().AsEnumerable().Where(predicate);
public static int Count(Func<TEntity, bool> predicate = null) => predicate != null ?
getQuery().Count(predicate) :
getQuery().Count();
public static bool Any(Func<TEntity, bool> predicate = null) => predicate != null ?
getQuery().Any(predicate) :
getQuery().Any();
public static IQueryable<TResult> Select<TResult>(Expression<Func<TEntity, TResult>> selector) =>
getQuery().Select(selector);
private static IQueryable<TEntity> getQuery() =>
(new TEntity() as IRepository<TEntity, TDbType>)?.getContext().Set<TEntity>().AsNoTracking();
public TDbType getContext() => Context;
public void Dispose() => Context.Dispose();
#endregion
[NonSerialized]
private static readonly object Guarder = new object();
[NonSerialized]
private TDbType _clrDbType;
}
} | 33.798077 | 178 | 0.549929 | [
"MIT"
] | 0xF6/aspcore-example | WebApp/Etc/EF/Repository.cs | 3,517 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipayAssetPointOrderCreateResponse.
/// </summary>
public class AlipayAssetPointOrderCreateResponse : AopResponse
{
/// <summary>
/// 支付宝集分宝发放流水号
/// </summary>
[XmlElement("alipay_order_no")]
public string AlipayOrderNo { get; set; }
}
}
| 23.055556 | 67 | 0.59759 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Response/AlipayAssetPointOrderCreateResponse.cs | 437 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace DisplayQort
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public int Area() => (Right - Left) * (Top - Bottom);
public RECT(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public override String ToString() => $"[({Left}, {Top}), ({Right}, {Bottom})]";
}
[Serializable]
public struct RECTSIZE
{
public int Width;
public int Height;
public int Area() => Width * Height;
public RECTSIZE(int w, int h)
{
Width = w;
Height = h;
}
public static explicit operator RECTSIZE(RECT rect) => new RECTSIZE(rect.Right - rect.Left, rect.Bottom - rect.Top);
public override String ToString() => $"w={Width}, h={Height}";
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
public override String ToString() => $"({X}, {Y})";
}
[Serializable]
public enum SW
{
HIDE = 0,
SHOWNORMAL = 1,
SHOWMINIMIZED = 2,
SHOWMAXIMIZED = 3,
SHOWNOACTIVATE = 4,
SHOW = 5,
MINIMIZE = 6,
SHOWMINNOACTIVE = 7,
SHOWNA = 8,
RESTORE = 9,
SHOWDEFAULT = 10,
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPLACEMENT
{
public int length;
public int flags;
public SW showCmd;
public POINT minPosition;
public POINT maxPosition;
public RECT normalPosition;
public override String ToString() =>
$"SW{showCmd}Min{minPosition}Max{maxPosition}N{normalPosition}";
}
/// <summary>
/// 包含関係を表す
/// 含まれる、左上が含まれる、その他一部が含まれる、含まれない
/// </summary>
[Serializable]
public enum Relation
{
Include, UpperLeftInclude, OtherInclude, NotInclude
}
public class Common
{
public const double UpperLeftConst = 0.2;
public static bool IsInclude(RECT baseObj, POINT targetObj) =>
baseObj.Left < targetObj.X && targetObj.X < baseObj.Right && baseObj.Top < targetObj.Y && targetObj.Y < baseObj.Bottom;
public static Relation ExtraInclude(RECT baseObj, RECT targetObj)
{
POINT upperLeft = new POINT(targetObj.Left, targetObj.Top);
POINT lowerRight = new POINT(targetObj.Right, targetObj.Bottom);
if (IsInclude(baseObj, upperLeft) && IsInclude(baseObj, lowerRight))
{
return Relation.Include;
}
RECTSIZE upperLeftSize = (RECTSIZE)targetObj;
POINT upperLeftSpecial = new POINT(
targetObj.Left + (int)(upperLeftSize.Width * UpperLeftConst),
targetObj.Top + (int)(upperLeftSize.Height * UpperLeftConst)
);
if (IsInclude(baseObj, upperLeft) && IsInclude(baseObj, upperLeftSpecial))
{
return Relation.UpperLeftInclude;
}
POINT upperRight = new POINT(targetObj.Right, targetObj.Top);
POINT lowerLeft = new POINT(targetObj.Left, targetObj.Bottom);
if (IsInclude(baseObj, upperLeft) || IsInclude(baseObj, lowerRight)
|| IsInclude(baseObj, upperRight) || IsInclude(baseObj, lowerLeft))
{
return Relation.OtherInclude;
}
return Relation.NotInclude;
}
public static bool IsInclude(RECT baseObj, RECT targetObj)
{
var relation = ExtraInclude(baseObj, targetObj);
return relation == Relation.Include || relation == Relation.UpperLeftInclude;
}
// ウィンドウの列挙
public delegate bool EnumWindowsDelegate(IntPtr hWnd, IntPtr lparam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public extern static bool EnumWindows(EnumWindowsDelegate lpEnumFunc, IntPtr lparam);
// ウィンドウテキストを取得
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd,
StringBuilder lpString, int nMaxCount);
// ウィンドウテキストの長さを取得
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowTextLength(IntPtr hWnd);
// ウィンドウのクラスネームを取得
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
// ウィンドウ座標を取得
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr HWND, out RECT rect);
public bool Getwindowrect(IntPtr hwnd, out RECT rc)
{
bool tf = GetWindowRect(hwnd, out rc);
return tf;
}
// ウインドウ情報を取得する
[DllImport("user32.dll")]
public static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
// ウインドウ情報をセットする
[DllImport("user32.dll")]
public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
// ウインドウ情報を取得する
[DllImport("user32.dll")]
public static extern long GetWindowLong(IntPtr hWnd, int nIndex);
public static long GetWindowLongStyle(IntPtr hWnd) => GetWindowLong(hWnd, GWL_STYLE);
public static long GetWindowLongExStyle(IntPtr hWnd) => GetWindowLong(hWnd, GWL_EXSTYLE);
// ウィンドウと指定された関係( またはオーナー)にあるウィンドウのハンドルを返します
[DllImport("user32.dll")]
public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
public const int GWL_STYLE = -16; // ウインドウスタイルを取得
public const int GWL_EXSTYLE = -20; // 拡張ウインドウスタイルを取得
public const long WS_VISIBLE = 0x10000000L;
public const long WS_EX_NOREDIRECTIONBITMAP = 0x00200000L;
public const long WS_EX_TOOLWINDOW = 0x00000080L;
public const uint GW_OWNER = 4;
}
}
| 33.010152 | 131 | 0.604336 | [
"MIT"
] | tibigame/Displayqort | DisplayQort/Common.cs | 6,903 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Ie.V20200304.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class MediaQualityRestorationTaskResult : AbstractModel
{
/// <summary>
/// 画质重生任务ID
/// </summary>
[JsonProperty("TaskId")]
public string TaskId{ get; set; }
/// <summary>
/// 画质重生处理后文件的详细信息。
/// </summary>
[JsonProperty("SubTaskResult")]
public SubTaskResultItem[] SubTaskResult{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TaskId", this.TaskId);
this.SetParamArrayObj(map, prefix + "SubTaskResult.", this.SubTaskResult);
}
}
}
| 30.529412 | 86 | 0.646114 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ie/V20200304/Models/MediaQualityRestorationTaskResult.cs | 1,599 | C# |
namespace P01.OverideOperators
{
public struct Point
{
public Point(decimal x, decimal y)
{
this.X = x;
this.Y = y;
}
public decimal X { get; private set; }
public decimal Y { get; private set; }
public static Point operator +(Point a, Point b)
{
decimal x = a.X + b.X;
decimal y = a.Y + b.Y;
var point = new Point(x, y);
return point;
}
public static Point operator -(Point a, Point b)
{
decimal x = a.X - b.X;
decimal y = a.Y - b.Y;
var point = new Point(x, y);
return point;
}
public static bool operator ==(Point a, Point b)
{
bool isEquals = a.X == b.X && a.Y == b.Y;
return isEquals;
}
public static bool operator !=(Point a, Point b)
{
bool isEquals = a.X != b.X && a.Y != b.Y;
return isEquals;
}
public override int GetHashCode()
{
int hash = ((int)this.X << 2) ^ (int)this.Y;
return hash;
}
public override bool Equals(object obj)
{
bool isInvalid = obj == null || this.GetType().Name != obj.GetType().Name; ;
if (isInvalid)
{
return false;
}
var point = (Point)obj;
bool isEquals = this.X == point.X && this.Y == point.Y;
return isEquals;
}
public override string ToString()
{
string pointAsString = $"({this.X}, {this.Y})";
return pointAsString;
}
}
}
| 21.5125 | 88 | 0.443928 | [
"MIT"
] | PetarKTodorov/CSharp-OOP-Course | 09.Exercise/src/Exercises/P01.OverideOperators/Point.cs | 1,723 | C# |
/*
* Swagger Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter;
namespace IO.Swagger.Model
{
/// <summary>
/// AnimalFarm
/// </summary>
[DataContract]
public partial class AnimalFarm : List<Animal>, IEquatable<AnimalFarm>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="AnimalFarm" /> class.
/// </summary>
public AnimalFarm() : base()
{
}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AnimalFarm {\n");
sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as AnimalFarm);
}
/// <summary>
/// Returns true if AnimalFarm instances are equal
/// </summary>
/// <param name="input">Instance of AnimalFarm to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AnimalFarm input)
{
if (input == null)
return false;
return base.Equals(input);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = base.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 31.287037 | 159 | 0.589819 | [
"Apache-2.0"
] | Cadcorp/swagger-codegen | samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AnimalFarm.cs | 3,379 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
namespace TiendaServicios.Apil.Libro.Tests
{
public class AsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T>
{
public AsyncEnumerable(IEnumerable<T> enumerable) : base(enumerable)
{
}
public AsyncEnumerable(Expression expresion) : base(expresion) { }
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new AsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
IQueryProvider IQueryable.Provider
{
get { return new AsyncQueryProvider<T>(this); }
}
}
}
| 27.214286 | 100 | 0.671916 | [
"MIT"
] | farenasmz/MicroServiceCourse | TiendaServicios/TiendaServicios.Apil.Libro.Tests/AsyncEnumerable.cs | 764 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.DirectX;
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE"]/*' />
public enum D2D1_SPOTDIFFUSE_SCALE_MODE : uint
{
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_NEAREST_NEIGHBOR"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_NEAREST_NEIGHBOR = 0,
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_LINEAR"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_LINEAR = 1,
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_CUBIC"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_CUBIC = 2,
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_MULTI_SAMPLE_LINEAR"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_MULTI_SAMPLE_LINEAR = 3,
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_ANISOTROPIC"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_ANISOTROPIC = 4,
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_HIGH_QUALITY_CUBIC"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_HIGH_QUALITY_CUBIC = 5,
/// <include file='D2D1_SPOTDIFFUSE_SCALE_MODE.xml' path='doc/member[@name="D2D1_SPOTDIFFUSE_SCALE_MODE.D2D1_SPOTDIFFUSE_SCALE_MODE_FORCE_DWORD"]/*' />
D2D1_SPOTDIFFUSE_SCALE_MODE_FORCE_DWORD = 0xffffffff,
}
| 61.15625 | 163 | 0.794584 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/d2d1effects/D2D1_SPOTDIFFUSE_SCALE_MODE.cs | 1,959 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
using TourManagement.API.Services;
namespace TourManagement.API.Migrations
{
[DbContext(typeof(TourManagementContext))]
[Migration("20180109144623_InitialMigration")]
partial class InitialMigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("TourManagement.API.Entities.Band", b =>
{
b.Property<Guid>("BandId")
.ValueGeneratedOnAdd();
b.Property<string>("CreatedBy")
.IsRequired();
b.Property<DateTime>("CreatedOn");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(250);
b.Property<string>("UpdatedBy");
b.Property<DateTime>("UpdatedOn");
b.HasKey("BandId");
b.ToTable("Bands");
});
modelBuilder.Entity("TourManagement.API.Entities.Manager", b =>
{
b.Property<Guid>("ManagerId")
.ValueGeneratedOnAdd();
b.Property<string>("CreatedBy")
.IsRequired();
b.Property<DateTime>("CreatedOn");
b.Property<string>("Name");
b.Property<string>("UpdatedBy");
b.Property<DateTime>("UpdatedOn");
b.HasKey("ManagerId");
b.ToTable("Managers");
});
modelBuilder.Entity("TourManagement.API.Entities.Show", b =>
{
b.Property<Guid>("ShowId")
.ValueGeneratedOnAdd();
b.Property<string>("City")
.IsRequired()
.HasMaxLength(100);
b.Property<string>("Country")
.IsRequired()
.HasMaxLength(100);
b.Property<string>("CreatedBy")
.IsRequired();
b.Property<DateTime>("CreatedOn");
b.Property<DateTimeOffset>("DateAndTime");
b.Property<Guid>("TourId");
b.Property<string>("UpdatedBy");
b.Property<DateTime>("UpdatedOn");
b.Property<string>("Venue")
.IsRequired()
.HasMaxLength(150);
b.HasKey("ShowId");
b.HasIndex("TourId");
b.ToTable("Shows");
});
modelBuilder.Entity("TourManagement.API.Entities.Tour", b =>
{
b.Property<Guid>("TourId")
.ValueGeneratedOnAdd();
b.Property<Guid>("BandId");
b.Property<string>("CreatedBy")
.IsRequired();
b.Property<DateTime>("CreatedOn");
b.Property<string>("Description")
.HasMaxLength(2000);
b.Property<DateTimeOffset>("EndDate");
b.Property<decimal>("EstimatedProfits");
b.Property<Guid>("ManagerId");
b.Property<DateTimeOffset>("StartDate");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200);
b.Property<string>("UpdatedBy");
b.Property<DateTime>("UpdatedOn");
b.HasKey("TourId");
b.HasIndex("BandId");
b.HasIndex("ManagerId");
b.ToTable("Tours");
});
modelBuilder.Entity("TourManagement.API.Entities.Show", b =>
{
b.HasOne("TourManagement.API.Entities.Tour", "Tour")
.WithMany("Shows")
.HasForeignKey("TourId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("TourManagement.API.Entities.Tour", b =>
{
b.HasOne("TourManagement.API.Entities.Band", "Band")
.WithMany()
.HasForeignKey("BandId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("TourManagement.API.Entities.Manager", "Manager")
.WithMany()
.HasForeignKey("ManagerId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 31.60355 | 117 | 0.471447 | [
"MIT"
] | KevinDockx/AngularASPNetCoreBusinessApplications | Finished sample/TourManagement.API/Migrations/20180109144623_InitialMigration.Designer.cs | 5,343 | C# |
using System;
using System.IO;
namespace Microsoft.NetMicroFramework.Tools
{
/// <summary>
/// Summary description for SrecUtility
/// </summary>
public class SrecUtility
{
public static bool CreateSrec(string szfile, string szOutfile, uint nBaseAddress)
{
return CreateSrec(szfile, szOutfile, nBaseAddress, uint.MaxValue);
}
public static bool CreateSrec(string szfile, string szOutfile, uint nBaseAddress, uint nExecuteAddress)
{
FileStream objfsRead = null;
FileStream objfsWrite = null;
int nChunkLength = 16;
bool fRet = true;
try
{
//First Open The file handle
objfsRead = new FileStream(szfile , FileMode.Open , FileAccess.Read, FileShare.ReadWrite);
objfsWrite = new FileStream(szOutfile, FileMode.Create, FileAccess.Write);
//Now read chunk of 16 bytes -
int nRead = 0 ;
byte[] arrByte = new byte[nChunkLength];
uint nCurrentOffSet = nBaseAddress;
while ((nRead = objfsRead.Read(arrByte, 0, nChunkLength))!= 0)
{
char [] arrRecord = ConstructSrecRecord("S3", arrByte, nRead, nCurrentOffSet);
if (arrRecord != null)
{
for (int i=0;i<arrRecord.Length;i++)
{
objfsWrite.WriteByte((byte)arrRecord[i]);
}
objfsWrite.WriteByte((byte)'\r');
objfsWrite.WriteByte((byte)'\n');
}
else
throw new Exception("Problem in Code");
nCurrentOffSet = nCurrentOffSet + 16;
}
if (nExecuteAddress != uint.MaxValue)
{
WriteS7(objfsWrite, nExecuteAddress);
}
}
catch
{
fRet = false;
}
if (objfsRead != null)
{
objfsRead.Close();
}
if (objfsWrite != null)
{
objfsWrite.Close();
}
return fRet;
}
static void WriteS7(FileStream objfsWrite, uint nEndaddress)
{
int nSum = 0;
//Get the address
char [] arrByte = new char[2 + 2 + 8 + 2];
arrByte[0]= 'S';
arrByte[1] = '7';
arrByte[2]= '0';
arrByte[3] = '5';
nSum = 5;
string sHex = String.Format( "{0:X8}", nEndaddress);
for (int j=0;j<sHex.Length;j++)
{
arrByte[j + 4] = sHex[j];
}
//for check sum
for (int j=0;j<4;j++)
{
nSum = (int)(nSum + (nEndaddress & 255));
nEndaddress = nEndaddress >> 8;
}
nSum = int.MaxValue - nSum;
sHex = String.Format( "{0:X8}", nSum);
arrByte[arrByte.Length -2] = sHex[sHex.Length - 2];
arrByte[arrByte.Length -1] = sHex[sHex.Length - 1];
for (int i=0;i<arrByte.Length;i++)
{
objfsWrite.WriteByte((byte)arrByte[i]);
}
objfsWrite.WriteByte((byte)'\r');
objfsWrite.WriteByte((byte)'\n');
}
static char [] ConstructSrecRecord(string szType, byte [] arrByteInput , int nRead, uint nCurrentAddress)
{
int nBaseLength = 2 + 2 + 8 + 2;
char[] arrByte = new char[nBaseLength + (nRead*2)];
if (szType == null || szType.Length != 2)
{
return null;
}
//Put in the type
arrByte[0] = szType[0];
arrByte[1] = szType[1];
string sHex=null;
//Put in the count
byte byCount = (byte)((arrByte.Length - 4) / 2);
sHex = String.Format( "{0:X2}", byCount );
arrByte[2] = sHex[0];
arrByte[3] = sHex[1];
int nSum = 0;
nSum = (int) byCount;
//Get the address
sHex = String.Format( "{0:X8}", nCurrentAddress );
for (int i=0;i<sHex.Length;i++)
{
arrByte[4+i] = sHex[i];
}
//for check sum
for (int j=0;j<4;j++)
{
nSum = (int)(nSum + (nCurrentAddress & 255));
nCurrentAddress = nCurrentAddress >> 8;
}
for (int s=0;s<nRead;s++)
{
nSum = nSum + arrByteInput[s];
}
nSum = int.MaxValue - nSum;
//end check sum
//Put in the Data
ConvertToHexAscii(arrByte, 12, arrByteInput, nRead);
//Check Sum Right now
sHex = String.Format( "{0:X8}", nSum );
arrByte[arrByte.Length - 2] = sHex[sHex.Length - 2];
arrByte[arrByte.Length - 1] = sHex[sHex.Length - 1];
//Then Put in the new line thing
return arrByte;
}
static void ConvertToHexAscii(char[] arrToWriteTo, int nIndexToStart , byte [] arrInput, int nRead)
{
string sHex = null;
for (int i=0;i<nRead;i++)
{
sHex = String.Format( "{0:X2}", arrInput[i] );
arrToWriteTo[nIndexToStart] = sHex[0];
arrToWriteTo[nIndexToStart + 1] = sHex[1];
nIndexToStart = nIndexToStart + 2;
}
}
}
}
| 31.547368 | 114 | 0.432933 | [
"Apache-2.0"
] | AustinWise/Netduino-Micro-Framework | Framework/Tools/SRECUtility/SrecUtility.cs | 5,994 | C# |
// Copyright (c) 2021 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.PlatformServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using Windows.ApplicationModel.Core;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml;
namespace ReactiveUI;
/// <summary>
/// This scheduler forces all dispatching to go to the first window of the <see cref="CoreApplication.Views"/> enumeration.
/// This makes the intended behavior of only supporting single window apps on UWP explicit.
/// If your app creates multiple windows, you should explicitly supply a scheduler which marshals
/// back to that window's <see cref="CoreDispatcher"/>.
/// </summary>
/// <remarks>
/// This follows patterns set out in <see cref="CoreDispatcherScheduler"/> with some minor tweaks
/// for thread-safety and performance.
/// </remarks>
/// <seealso cref="System.Reactive.Concurrency.IScheduler" />
public class SingleWindowDispatcherScheduler : IScheduler
{
private const CoreDispatcherPriority Priority = default;
private static CoreDispatcher? _dispatcher;
/// <summary>
/// Initializes a new instance of the <see cref="SingleWindowDispatcherScheduler"/> class.
/// </summary>
public SingleWindowDispatcherScheduler()
{
if (CoreApplication.Views.Count == 0)
{
return;
}
var coreDispatcher = TryGetDispatcher();
Interlocked.CompareExchange(ref _dispatcher, coreDispatcher, null);
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleWindowDispatcherScheduler"/> class with an explicit dispatcher.
/// </summary>
/// <param name="dispatcher">
/// The explicit <see cref="CoreDispatcher"/> to use. If you supply a dispatcher here then all instances of
/// <see cref="SingleWindowDispatcherScheduler"/> will dispatch to that dispatcher from instantiation on.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// dispatcher - To override the scheduler you must supply a non-null instance of CoreDispatcher.
/// </exception>
public SingleWindowDispatcherScheduler(CoreDispatcher dispatcher) => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher), "To override the scheduler you must supply a non-null instance of CoreDispatcher.");
/// <inheritdoc/>
public DateTimeOffset Now => SystemClock.UtcNow;
/// <inheritdoc/>
public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
if (CoreApplication.Views.Count == 0)
{
return CurrentThreadScheduler.Instance.Schedule(state, action);
}
return ScheduleOnDispatcherNow(state, action);
}
/// <inheritdoc/>
public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
if (CoreApplication.Views.Count == 0)
{
return CurrentThreadScheduler.Instance.Schedule(state, dueTime, action);
}
var dt = Scheduler.Normalize(dueTime);
if (dt.Ticks == 0)
{
return ScheduleOnDispatcherNow(state, action);
}
return ScheduleSlow(state, dt, action);
}
/// <inheritdoc/>
public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
if (CoreApplication.Views.Count == 0)
{
return CurrentThreadScheduler.Instance.Schedule(state, dueTime, action);
}
var dt = Scheduler.Normalize(dueTime - DateTimeOffset.Now);
if (dt.Ticks == 0)
{
return ScheduleOnDispatcherNow(state, action);
}
return ScheduleSlow(state, dt, action);
}
/// <summary>
/// Work-around for the behavior of throwing from "async void" or an <see cref="IAsyncResult"/> not propagating
/// the exception to the <see cref="Application.UnhandledException" /> event as users have come to expect from
/// previous XAML stacks using Rx.
/// </summary>
/// <param name="ex">The exception.</param>
private static void RaiseUnhandledException(Exception ex)
{
var timer = new DispatcherTimer
{
Interval = TimeSpan.Zero
};
timer.Tick += RaiseToDispatcher;
timer.Start();
#pragma warning disable RCS1163 // Unused parameter.
void RaiseToDispatcher(object sender, object e)
#pragma warning restore RCS1163 // Unused parameter.
{
timer.Stop();
timer.Tick -= RaiseToDispatcher;
timer = null;
ExceptionDispatchInfo.Capture(ex).Throw();
}
}
private static CoreDispatcher? TryGetDispatcher()
{
CoreDispatcher? coreDispatcher;
try
{
coreDispatcher = CoreApplication.Views.Count > 0 ? CoreApplication.Views[0].Dispatcher : null;
}
catch
{
// in the XamlIsland case, accessing Views throws. Thus, falling back to the old way. This HAS to be initialized on the MainThread.
coreDispatcher = Window.Current?.Dispatcher;
}
return coreDispatcher;
}
private IDisposable ScheduleOnDispatcherNow<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
try
{
// if _dispatcher is still null (and only then) CompareExchange it with the dispatcher from the first view found
if (_dispatcher is null)
{
var dispatcher = TryGetDispatcher();
Interlocked.CompareExchange(ref _dispatcher, dispatcher, null);
}
}
catch
{
// Ignore
}
if (_dispatcher is null || _dispatcher.HasThreadAccess)
{
return action(this, state);
}
var d = new SingleAssignmentDisposable();
var dispatchResult = _dispatcher.RunAsync(
Priority,
() =>
{
if (!d.IsDisposed)
{
try
{
d.Disposable = action(this, state);
}
catch (Exception ex)
{
RaiseUnhandledException(ex);
}
}
});
return StableCompositeDisposable.Create(
d,
Disposable.Create(() => dispatchResult.Cancel()));
}
private IDisposable ScheduleSlow<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
var d = new MultipleAssignmentDisposable();
// Why ThreadPoolTimer?
// --
// Because, we can't guarantee that DispatcherTimer will dispatch to the correct CoreDispatcher if there are multiple
// so we dispatch explicitly from our own method.
var timer = ThreadPoolTimer.CreateTimer(_ => d.Disposable = ScheduleOnDispatcherNow(state, action), dueTime);
d.Disposable = Disposable.Create(() =>
{
var t = Interlocked.Exchange(ref timer, null!);
if (t is not null)
{
t.Cancel();
action = (_, __) => Disposable.Empty;
}
});
return d;
}
} | 36.47479 | 237 | 0.577583 | [
"MIT"
] | PKRoma/ReactiveUI | src/ReactiveUI.Uwp/SingleWindowDispatcherScheduler.cs | 8,681 | C# |
using System;
namespace BitMiracle.LibTiff.Classic
{
/// <summary>
/// Jpeg Tables Mode.<br/>
/// Possible values for <see cref="TiffTag"/>.JPEGTABLESMODE tag.
/// </summary>
[Flags]
#if EXPOSE_LIBTIFF
public
#endif
enum JpegTablesMode
{
/// <summary>
/// None.
/// </summary>
NONE = 0,
/// <summary>
/// Include quantization tables.
/// </summary>
QUANT = 0x0001,
/// <summary>
/// Include Huffman tables.
/// </summary>
HUFF = 0x0002,
}
}
| 20.096774 | 70 | 0.463884 | [
"MIT"
] | shahareldad/EcoScan | LibTiff/Enums/JpegTablesMode.cs | 625 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\wincodec.h(2097,5)
using System;
using System.Runtime.InteropServices;
using WICPixelFormatGUID = System.Guid;
namespace DirectN
{
[Guid("00000123-a8f2-4877-ba0a-fd2b6645fb94"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IWICBitmapLock
{
[PreserveSig]
HRESULT GetSize(/* [out] __RPC__out */ out uint puiWidth, /* [out] __RPC__out */ out uint puiHeight);
[PreserveSig]
HRESULT GetStride(/* [out] __RPC__out */ out uint pcbStride);
[PreserveSig]
HRESULT GetDataPointer(/* [out] __RPC__out */ out uint pcbBufferSize, /* optional(WICInProcPointer) */ out IntPtr ppbData);
[PreserveSig]
HRESULT GetPixelFormat(/* [out] __RPC__out */ out WICPixelFormatGUID pPixelFormat);
}
}
| 36.666667 | 131 | 0.676136 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IWICBitmapLock.cs | 882 | C# |
using System;
namespace TriangleArea
{
class TriangleArea
{
static void Main()
{
var x1 = int.Parse(Console.ReadLine());
var y1 = int.Parse(Console.ReadLine());
var x2 = int.Parse(Console.ReadLine());
var y2 = int.Parse(Console.ReadLine());
var x3 = int.Parse(Console.ReadLine());
var y3 = int.Parse(Console.ReadLine());
var a = Math.Abs(x3 - x2);
var ha = Math.Abs(y3 - y1);
var area = (a * ha) / 2.0;
Console.WriteLine(area);
}
}
}
| 23.8 | 51 | 0.494118 | [
"MIT"
] | pirocorp/Programming-Basics | ProgrammingBasicsExamPreparation/TriangleArea/TriangleArea.cs | 597 | C# |
namespace TeamCityManager.Entities.BuildSteps
{
using System.Collections.Generic;
public class NUnitBuildStep : IBuildStep
{
public List<string> AssembliesToTest { get; set; }
public string DotNetVersion { get; set; }
public string Platform { get; set; }
public string Type
{
get
{
return "NUnit";
}
}
public string Version { get; set; }
public Dictionary<string, string> Properties
{
get
{
var properties = new Dictionary<string, string>();
properties.Add("nunit_enabled", "checked");
properties.Add("nunit_environment", DotNetVersion);
properties.Add("nunit_include", string.Join(",", AssembliesToTest));
properties.Add("nunit_platform", Platform);
properties.Add("nunit_version", string.Format("NUnit-{0}", Version));
return properties;
}
}
}
} | 26.974359 | 85 | 0.537072 | [
"MIT"
] | tombuildsstuff/teamcitymanager | TeamCityManager/Entities/BuildSteps/NUnitBuildStep.cs | 1,054 | 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.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyTitleAttribute("EasyManager.Domain.Core")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 37.380952 | 80 | 0.598726 | [
"Apache-2.0"
] | fahelmoreira/EasyManagerERP | src/EasyManager.Domain.Core/obj/Debug/netcoreapp2.1/EasyManager.Domain.Core.AssemblyInfo.cs | 785 | C# |
using System.Collections.ObjectModel;
namespace Khernet.UI.IoC
{
public interface IChatList
{
/// <summary>
/// Adds a chat list for given token.
/// </summary>
/// <param name="token">The token of user.</param>
/// <param name="chatList">The chat list.</param>
void AddChatList(UserItemViewModel user);
/// <summary>
/// Gets a chat list for given <see cref="UserItemViewModel"/>.
/// </summary>
/// <param name="token">The token of user.</param>
/// <returns>An object <see cref="ObservableCollection<ChatMessageItemViewModel>"/> containing chat list.</returns>
/*ObservableCollection<ChatMessageItemViewModel>*/
ObservableCollection<ChatMessageItemViewModel> GetChat(UserItemViewModel user);
/// <summary>
/// Gets a chat list for given token.
/// </summary>
/// <param name="token">The token of user.</param>
/// <returns>An object <see cref="ObservableCollection{ChatMessageItemViewModel}"/> containing chat list.</returns>
ObservableCollection<ChatMessageItemViewModel> GetChat(string token);
/// <summary>
/// Gets user context of chat cache.
/// </summary>
/// <param name="user">The model of user.</param>
/// <returns>The context of user.</returns>
UserChatContext GetUserContext(UserItemViewModel user);
/// <summary>
/// Clears the chat cache.
/// </summary>
void Clear();
}
}
| 36.642857 | 123 | 0.609487 | [
"MIT"
] | lemalcs/Khernet | Khernet.UI/Khernet.UI.Presentation/IoC/IChatList.cs | 1,541 | C# |
using System;
using Legacy.Game.HUD;
using UnityEngine;
namespace Legacy.Game.MMGUI
{
public abstract class BaseDragObject
{
protected UISprite m_sprite;
protected UISprite m_actionSprite;
protected UISprite m_scrollSprite;
protected UISprite m_brokenSprite;
protected UISprite m_itemBackground;
protected UILabel m_itemCounter;
protected CharacterHud m_characterHud;
public UISprite Sprite
{
get => m_sprite;
set => m_sprite = value;
}
public UISprite ActionSprite
{
get => m_actionSprite;
set => m_actionSprite = value;
}
public UISprite ScrollSprite
{
get => m_scrollSprite;
set => m_scrollSprite = value;
}
public UILabel ItemCounter
{
get => m_itemCounter;
set => m_itemCounter = value;
}
public UISprite BrokenSprite
{
get => m_brokenSprite;
set => m_brokenSprite = value;
}
public UISprite ItemBackground
{
get => m_itemBackground;
set => m_itemBackground = value;
}
public CharacterHud CharacterHud
{
get => m_characterHud;
set => m_characterHud = value;
}
public void Update()
{
if (m_sprite != null)
{
m_sprite.Update();
}
}
public virtual void SetActive(Boolean p_active)
{
NGUITools.SetActiveSelf(m_sprite.gameObject, p_active);
NGUITools.SetActiveSelf(m_actionSprite.gameObject, false);
NGUITools.SetActiveSelf(m_scrollSprite.gameObject, false);
NGUITools.SetActiveSelf(m_brokenSprite.gameObject, false);
NGUITools.SetActiveSelf(m_itemBackground.gameObject, false);
NGUITools.SetActiveSelf(m_characterHud.gameObject, false);
}
public virtual void CancelDragAction()
{
}
}
}
| 19.045455 | 63 | 0.705847 | [
"MIT"
] | Albeoris/MMXLegacy | Legacy.Game/Game/MMGUI/BaseDragObject.cs | 1,678 | C# |
using System;
using MonoGame.Extended.TextureAtlases;
namespace MonoGame.Extended.Gui.Controls
{
public class GuiButton : GuiControl
{
public GuiButton()
{
}
public GuiButton(TextureRegion2D backgroundRegion)
: base(backgroundRegion)
{
}
public event EventHandler Clicked;
public event EventHandler PressedStateChanged;
private bool _isPressed;
public bool IsPressed
{
get { return _isPressed; }
set
{
if (_isPressed != value)
{
_isPressed = value;
PressedStyle?.ApplyIf(this, _isPressed);
PressedStateChanged?.Invoke(this, EventArgs.Empty);
}
}
}
private GuiControlStyle _pressedStyle;
public GuiControlStyle PressedStyle
{
get { return _pressedStyle; }
set
{
if (_pressedStyle != value)
{
_pressedStyle = value;
PressedStyle?.ApplyIf(this, _isPressed);
}
}
}
private bool _isPointerDown;
public override void OnPointerDown(GuiPointerEventArgs args)
{
base.OnPointerDown(args);
if (IsEnabled)
{
_isPointerDown = true;
IsPressed = true;
}
}
public override void OnPointerUp(GuiPointerEventArgs args)
{
base.OnPointerUp(args);
_isPointerDown = false;
if (IsPressed)
{
IsPressed = false;
if (BoundingRectangle.Contains(args.Position) && IsEnabled)
Clicked?.Invoke(this, EventArgs.Empty);
}
}
public override void OnPointerEnter(GuiPointerEventArgs args)
{
base.OnPointerEnter(args);
if (IsEnabled && _isPointerDown)
IsPressed = true;
}
public override void OnPointerLeave(GuiPointerEventArgs args)
{
base.OnPointerLeave(args);
if (IsEnabled)
IsPressed = false;
}
}
} | 24.741935 | 75 | 0.500652 | [
"MIT"
] | stefanrbk/MonoGame.Extended | Source/MonoGame.Extended.Gui/Controls/GuiButton.cs | 2,303 | C# |
using System;
using Meadow.Foundation;
using Meadow.Foundation.Audio;
using Meadow.Foundation.Graphics;
namespace Juego.Games
{
public partial class LanderGame
{
readonly byte cellSize = 8;
DrawPixelDel DrawPixel;
public void Init(MicroGraphics gl)
{
gl.Clear();
gl.DrawText(0, 0, "Meadow Lander");
gl.DrawText(0, 16, "v0.0.1");
gl.Show();
}
public void Update(IIOConfig ioConfig)
{
var gl = ioConfig.Graphics;
Update();
gl.Clear();
DrawBackground(gl);
// DrawLives();
gl.Show();
}
void DrawBackground(MicroGraphics graphics)
{
}
void DrawLives(MicroGraphics graphics)
{
}
delegate void DrawPixelDel(int x, int y, bool colored, MicroGraphics graphics, Color color);
void DrawPixel1x(int x, int y, bool colored, MicroGraphics graphics, Color color)
{
graphics.DrawPixel(x, y, colored?color:Color.Black);
}
void DrawPixel2x(int x, int y, bool colored, MicroGraphics graphics)
{
x *= 2;
y *= 2;
graphics.DrawPixel(x, y, colored);
graphics.DrawPixel(x + 1, y, colored);
graphics.DrawPixel(x, y + 1, colored);
graphics.DrawPixel(x + 1, y + 1, colored);
}
void DrawBitmap(int x, int y, int width, int height, byte[] bitmap, MicroGraphics graphics, Color color)
{
for (var ordinate = 0; ordinate < height; ordinate++) //y
{
for (var abscissa = 0; abscissa < width; abscissa++) //x
{
var b = bitmap[(ordinate * width) + abscissa];
byte mask = 0x01;
for (var pixel = 0; pixel < 8; pixel++)
{
DrawPixel(x + (8 * abscissa) + 7 - pixel, y + ordinate, (b & mask) > 0, graphics, color);
mask <<= 1;
}
}
}
}
}
} | 26.402439 | 113 | 0.48776 | [
"Apache-2.0"
] | WildernessLabs/Juego | Source/Juego/Juego/Games/Lander/LanderGame.Renderer.cs | 2,167 | C# |
namespace LiveBot.Core.Contracts.Discord
{
public interface IDiscordRoleUpdate
{
public ulong GuildId { get; set; }
public ulong RoleId { get; set; }
public string RoleName { get; set; }
}
} | 25.222222 | 44 | 0.625551 | [
"MIT"
] | bsquidwrd/LiveBot | LiveBot.Core/Contracts/Discord/IDiscordRoleUpdate.cs | 229 | C# |
using Clocks.Clients.Core.Controls;
using Clocks.Clients.iOS.Renderers;
using CoreAnimation;
using CoreGraphics;
using System;
using System.ComponentModel;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(ExtendedEntry), typeof(ExtendedEntryRenderer))]
namespace Clocks.Clients.iOS.Renderers
{
public class ExtendedEntryRenderer : EntryRenderer
{
public ExtendedEntry ExtendedEntryElement => Element as ExtendedEntry;
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control != null)
{
Control.BorderStyle = UIKit.UITextBorderStyle.None;
}
UpdateLineColor();
UpdateCursorColor();
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals(nameof(ExtendedEntry.LineColor)))
{
UpdateLineColor();
}
else if (e.PropertyName.Equals(Entry.TextColorProperty.PropertyName))
{
UpdateCursorColor();
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
var lineLayer = GetOrAddLineLayer();
lineLayer.Frame = new CGRect(0, Frame.Size.Height - LineLayer.LineHeight, Control.Frame.Size.Width, LineLayer.LineHeight);
}
private void UpdateLineColor()
{
var lineLayer = GetOrAddLineLayer();
lineLayer.BorderColor = ExtendedEntryElement.LineColor.ToCGColor();
}
private LineLayer GetOrAddLineLayer()
{
var lineLayer = Control.Layer.Sublayers?.OfType<LineLayer>().FirstOrDefault();
if (lineLayer == null)
{
lineLayer = new LineLayer();
Control.Layer.AddSublayer(lineLayer);
Control.Layer.MasksToBounds = true;
}
return lineLayer;
}
private void UpdateCursorColor() => Control.TintColor = Element.TextColor.ToUIColor();
private class LineLayer : CALayer
{
public static nfloat LineHeight = 2f;
public LineLayer() => BorderWidth = LineHeight;
}
}
} | 29.5 | 134 | 0.594797 | [
"MIT"
] | AlexeyBuryanov/Clocks.Clients | Source/Clocks.Clients/Clocks.Clients.iOS/Renderers/ExtendedEntryRenderer.cs | 2,539 | C# |
using System.Collections.Generic;
using Microsoft.WebTools.Languages.Html.Editor.Completion.Def;
using Microsoft.VisualStudio.Utilities;
namespace UmbSense.Completion.Directives
{
[HtmlCompletionProvider(CompletionTypes.Attributes, TagName)]
[ContentType("htmlx")]
class UmbGenerateAlias : BaseCompletion
{
internal const string TagName = "umb-generate-alias";
protected override Dictionary<string, string> values => new Dictionary<string, string>()
{
{ "alias", "The model where the alias is bound." },
{ "alias-from", "The model to generate the alias from." },
{ "validation-position", "The position of the validation. Set to 'left' or 'right'." },
{ "enable-lock", "Set to true to add a lock next to the alias from where it can be unlocked and changed." }
};
}
[HtmlCompletionProvider(CompletionTypes.Values, UmbGenerateAlias.TagName, "*")]
[ContentType("htmlx")]
class UmbGenerateAliasValues : BaseValueCompletion
{
protected override Dictionary<string, List<string>> attribValues => new Dictionary<string, List<string>>()
{
{ "validation-position", new List<string> { "left", "right" } },
{ "enable-lock", new List<string> { "true", "false" } }
};
}
}
| 40.272727 | 119 | 0.650865 | [
"MIT"
] | KevinJump/UmbSense | UmbSense/Completion/Directives/UmbGenerateAlias.cs | 1,331 | C# |
#region BSD 3-Clause License
// <copyright file="IGraphWorker.cs" company="Edgerunner.org">
// Copyright 2020 Thaddeus Ryker
// </copyright>
//
// BSD 3-Clause License
//
// Copyright (c) 2020, Thaddeus Ryker
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Antlr4.Runtime.Tree;
using JetBrains.Annotations;
using Org.Edgerunner.ANTLR4.Tools.Graphing;
namespace Org.Edgerunner.ANTLR4.Tools.Testing.GrunWin.Graphing
{
/// <summary>
/// Interface representing an instance that does the work building parse tree graphs.
/// </summary>
public interface IGraphWorker
{
/// <summary>
/// Occurs when graphing is finished.
/// </summary>
event EventHandler<GraphingResult> GraphingFinished;
/// <summary>
/// Occurs when the throttling status has changed.
/// </summary>
event EventHandler ThrottleStatusChanged;
/// <summary>
/// Gets a value indicating whether the worker is currently throttling.
/// </summary>
/// <value><c>true</c> if graph throttling is currently active; otherwise, <c>false</c>.</value>
bool CurrentlyThrottling { get; }
/// <summary>
/// Gets a value indicating whether a long graphing delay is active.
/// </summary>
/// <value><c>true</c> if long graphing delay is active; otherwise, <c>false</c>.</value>
bool LongDelayActive { get; }
/// <summary>
/// Gets the current millisecond delay between graphs.
/// </summary>
/// <value>The current millisecond delay between graphs.</value>
int CurrentMillisecondDelayBetweenGraphs { get; }
/// <summary>
/// Gets a value indicating whether this instance has work.
/// </summary>
/// <value><c>true</c> if this instance has work; otherwise, <c>false</c>.</value>
bool HasWork { get; }
/// <summary>
/// Queues the specified parse tree for graphing.
/// </summary>
/// <param name="grapher">The parse tree grapher.</param>
/// <param name="tree">The parse tree.</param>
/// <param name="parserRules">The parser rules.</param>
void Graph([NotNull] IParseTreeGrapher grapher, ITree tree, IList<string> parserRules);
/// <summary>
/// Cancels all queued work.
/// </summary>
/// <returns><c>true</c> if there was existing work to cancel, <c>false</c> otherwise.</returns>
bool CancelWork();
}
} | 39.465347 | 102 | 0.688911 | [
"BSD-3-Clause"
] | wiredwiz/Grun.Net | GunWin/Graphing/IGraphWorker.cs | 3,988 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System.Windows.Controls;
namespace StateBasedNavigation.Views
{
public partial class ChatView : UserControl
{
public ChatView()
{
InitializeComponent();
}
}
}
| 44.275862 | 85 | 0.541277 | [
"MIT"
] | TataDvd/G | 2012/Tempo2012/Tempo2012.UI.WPF/Quickstarts/State-Based Navigation/State-Based Navigation/Views/ChatView.xaml.cs | 1,284 | 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Runtime.Serialization.Formatters.Binary
{
// For each object or array being read off the stream, an ObjectProgress object is created. This object
// keeps track of the progress of the parsing. When an object is being parsed, it keeps track of
// the object member being parsed. When an array is being parsed it keeps track of the position within the
// array.
internal sealed class ObjectProgress
{
// Control
internal bool _isInitial;
internal int _count; //Progress count
internal BinaryTypeEnum _expectedType = BinaryTypeEnum.ObjectUrt;
internal object? _expectedTypeInformation;
internal string? _name;
internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty;
internal InternalMemberTypeE _memberTypeEnum;
internal InternalMemberValueE _memberValueEnum;
internal Type? _dtType;
// Array Information
internal int _numItems;
internal BinaryTypeEnum _binaryTypeEnum;
internal object? _typeInformation;
// Member Information
internal int _memberLength;
internal BinaryTypeEnum[]? _binaryTypeEnumA;
internal object?[]? _typeInformationA;
internal string[]? _memberNames;
internal Type?[]? _memberTypes;
// ParseRecord
internal ParseRecord _pr = new ParseRecord();
internal ObjectProgress() { }
internal void Init()
{
_isInitial = false;
_count = 0;
_expectedType = BinaryTypeEnum.ObjectUrt;
_expectedTypeInformation = null;
_name = null;
_objectTypeEnum = InternalObjectTypeE.Empty;
_memberTypeEnum = InternalMemberTypeE.Empty;
_memberValueEnum = InternalMemberValueE.Empty;
_dtType = null;
// Array Information
_numItems = 0;
//binaryTypeEnum
_typeInformation = null;
// Member Information
_memberLength = 0;
_binaryTypeEnumA = null;
_typeInformationA = null;
_memberNames = null;
_memberTypes = null;
_pr.Init();
}
//Array item entry of nulls has a count of nulls represented by that item. The first null has been
// incremented by GetNext, the rest of the null counts are incremented here
internal void ArrayCountIncrement(int value) => _count += value;
// Specifies what is to parsed next from the wire.
internal bool GetNext(out BinaryTypeEnum outBinaryTypeEnum, out object? outTypeInformation)
{
//Initialize the out params up here.
outBinaryTypeEnum = BinaryTypeEnum.Primitive;
outTypeInformation = null;
if (_objectTypeEnum == InternalObjectTypeE.Array)
{
// Array
if (_count == _numItems)
{
return false;
}
else
{
outBinaryTypeEnum = _binaryTypeEnum;
outTypeInformation = _typeInformation;
if (_count == 0)
_isInitial = false;
_count++;
return true;
}
}
else
{
// Member
if ((_count == _memberLength) && (!_isInitial))
{
return false;
}
else
{
Debug.Assert(_binaryTypeEnumA != null && _typeInformationA != null && _memberNames != null && _memberTypes != null);
outBinaryTypeEnum = _binaryTypeEnumA[_count];
outTypeInformation = _typeInformationA[_count];
if (_count == 0)
{
_isInitial = false;
}
_name = _memberNames[_count];
_dtType = _memberTypes[_count];
_count++;
return true;
}
}
}
}
}
| 35.188976 | 136 | 0.563213 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.cs | 4,469 | C# |
namespace Merchello.Web
{
using Core.Gateways;
using Core.Models;
using Merchello.Core.Models.Interfaces;
using Merchello.Core.Strategies.Itemization;
using Merchello.Web.Models.SaleHistory;
using Models.ContentEditing;
using Models.MapperResolvers;
/// <summary>
/// Binds Merchello AutoMapper mappings during the Umbraco startup.
/// </summary>
internal static partial class AutoMapperMappings
{
/// <summary>
/// Responsible for creating the AutoMapper Mappings
/// </summary>
public static void CreateMappings()
{
// Address
AutoMapper.Mapper.CreateMap<IAddress, AddressDisplay>();
AutoMapper.Mapper.CreateMap<AddressDisplay, Address>();
// AuditLog
AutoMapper.Mapper.CreateMap<IAuditLog, AuditLogDisplay>()
.ForMember(
dest => dest.ExtendedData,
opt => opt.ResolveUsing<ExtendedDataResolver>().ConstructedBy(() => new ExtendedDataResolver()))
.ForMember(
dest => dest.RecordDate,
opt => opt.MapFrom(src => src.CreateDate))
.ForMember(
dest => dest.EntityType,
opt => opt.ResolveUsing<EntityTypeResolver>().ConstructedBy(() => new EntityTypeResolver()));
AutoMapper.Mapper.CreateMap<ICurrency, CurrencyDisplay>();
// Country and provinces
AutoMapper.Mapper.CreateMap<ICountry, CountryDisplay>();
AutoMapper.Mapper.CreateMap<IProvince, ProvinceDisplay>();
// Customer
AutoMapper.Mapper.CreateMap<ICustomer, CustomerDisplay>()
.ForMember(
dest => dest.ExtendedData,
opt => opt.ResolveUsing<ExtendedDataResolver>().ConstructedBy(() => new ExtendedDataResolver()))
.ForMember(
dest => dest.Invoices,
opt => opt.ResolveUsing<CustomerInvoicesResolver>().ConstructedBy(() => new CustomerInvoicesResolver()));
// Customer Basket
AutoMapper.Mapper.CreateMap<IItemCacheLineItem, ItemCacheLineItemDisplay>()
.ForMember(dest => dest.ExtendedData, opt => opt.ResolveUsing<ExtendedDataResolver>().ConstructedBy(() => new ExtendedDataResolver()))
.ForMember(dest => dest.LineItemTypeField, opt => opt.ResolveUsing<LineItemTypeFieldResolver>().ConstructedBy(() => new LineItemTypeFieldResolver()));
AutoMapper.Mapper.CreateMap<IItemCache, CustomerItemCacheDisplay>()
.ForMember(
dest => dest.Customer,
opt => opt.ResolveUsing<ItemCacheCustomerResolver>().ConstructedBy(() => new ItemCacheCustomerResolver()));
AutoMapper.Mapper.CreateMap<ICustomerAddress, CustomerAddressDisplay>();
// Gateway Provider
AutoMapper.Mapper.CreateMap<IGatewayProviderSettings, GatewayProviderDisplay>()
.ForMember(dest => dest.ExtendedData, opt => opt.ResolveUsing<ExtendedDataResolver>().ConstructedBy(() => new ExtendedDataResolver()))
.ForMember(dest => dest.DialogEditorView, opt => opt.ResolveUsing<GatewayProviderDialogEditorViewResolver>().ConstructedBy(() => new GatewayProviderDialogEditorViewResolver()));
AutoMapper.Mapper.CreateMap<IGatewayResource, GatewayResourceDisplay>();
// Note
AutoMapper.Mapper.CreateMap<INote, NoteDisplay>()
.ForMember(
dest => dest.EntityType,
opt => opt.ResolveUsing<NoteEntityTypeResolver>().ConstructedBy(() => new NoteEntityTypeResolver()))
.ForMember(
dest => dest.NoteTypeField,
opt => opt.ResolveUsing<NoteTypeFieldResolver>().ConstructedBy(() => new NoteTypeFieldResolver()))
.ForMember(
dest => dest.RecordDate,
opt => opt.MapFrom(src => src.CreateDate));
// Invoice
AutoMapper.Mapper.CreateMap<IInvoiceStatus, InvoiceStatusDisplay>();
AutoMapper.Mapper.CreateMap<IInvoiceLineItem, InvoiceLineItemDisplay>()
.ForMember(dest => dest.ExtendedData, opt => opt.ResolveUsing<ExtendedDataResolver>().ConstructedBy(() => new ExtendedDataResolver()))
.ForMember(dest => dest.LineItemTypeField, opt => opt.ResolveUsing<LineItemTypeFieldResolver>().ConstructedBy(() => new LineItemTypeFieldResolver()));
AutoMapper.Mapper.CreateMap<IInvoice, InvoiceDisplay>();
AutoMapper.Mapper.CreateMap<InvoiceItemItemization, InvoiceItemItemizationDisplay>();
// Order
AutoMapper.Mapper.CreateMap<IOrderStatus, OrderStatusDisplay>();
AutoMapper.Mapper.CreateMap<IOrderLineItem, OrderLineItemDisplay>()
.ForMember(dest => dest.ExtendedData, opt => opt.ResolveUsing<ExtendedDataResolver>().ConstructedBy(() => new ExtendedDataResolver()))
.ForMember(dest => dest.LineItemTypeField, opt => opt.ResolveUsing<LineItemTypeFieldResolver>().ConstructedBy(() => new LineItemTypeFieldResolver()));
AutoMapper.Mapper.CreateMap<IOrder, OrderDisplay>();
// setup the other mappings
CreateDetachedContentMappings();
CreateEntityCollectionMappings();
CreateMarketingMappings();
CreateShippingMappings();
CreateTaxationMappings();
CreatePaymentMappings();
CreateWarehouseAndProductMappings();
CreateNotificationMappings();
// ProductContentEditing.BindMappings();
}
}
} | 46.887097 | 193 | 0.621431 | [
"MIT"
] | HiteshMah-Jan/Merchello | src/Merchello.Web/AutoMapperMappings.cs | 5,816 | C# |
/*
Copyright (C) 2018-2019 de4dot@gmail.com
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.
*/
#if INSTR_INFO
using System;
using System.Collections.Generic;
using Iced.Intel;
using Xunit;
namespace Iced.UnitTests.Intel.InstructionInfoTests {
public sealed class MemorySizeExtensionsTests {
[Theory]
[InlineData((MemorySize)(-1))]
[InlineData((MemorySize)IcedConstants.NumberOfMemorySizes)]
void GetInfo_throws_if_invalid_value(MemorySize memorySize) {
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.GetInfo());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.GetSize());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.GetElementSize());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.GetElementType());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.GetElementTypeInfo());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.IsSigned());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.IsPacked());
Assert.Throws<ArgumentOutOfRangeException>(() => memorySize.GetElementCount());
memorySize.IsBroadcast();// Does not throw
}
[Theory]
[MemberData(nameof(VerifyMemorySizeProperties_Data))]
void VerifyMemorySizeProperties(MemorySize memorySize, int size, int elementSize, MemorySize elementType, int elementCount, MemorySizeFlags flags) {
var info = memorySize.GetInfo();
Assert.Equal(memorySize, info.MemorySize);
Assert.Equal(size, info.Size);
Assert.Equal(elementSize, info.ElementSize);
Assert.Equal(elementType, info.ElementType);
Assert.Equal((flags & MemorySizeFlags.Signed) != 0, info.IsSigned);
Assert.Equal((flags & MemorySizeFlags.Broadcast) != 0, info.IsBroadcast);
Assert.Equal((flags & MemorySizeFlags.Packed) != 0, info.IsPacked);
Assert.Equal(elementCount, info.ElementCount);
Assert.Equal(size, memorySize.GetSize());
Assert.Equal(elementSize, memorySize.GetElementSize());
Assert.Equal(elementType, memorySize.GetElementType());
Assert.Equal(elementType, memorySize.GetElementTypeInfo().MemorySize);
Assert.Equal((flags & MemorySizeFlags.Signed) != 0, memorySize.IsSigned());
Assert.Equal((flags & MemorySizeFlags.Packed) != 0, memorySize.IsPacked());
Assert.Equal((flags & MemorySizeFlags.Broadcast) != 0, memorySize.IsBroadcast());
Assert.Equal(elementCount, memorySize.GetElementCount());
}
public static IEnumerable<object[]> VerifyMemorySizeProperties_Data {
get {
foreach (var tc in MemorySizeInfoTestReader.GetTestCases())
yield return new object[] { tc.MemorySize, tc.Size, tc.ElementSize, tc.ElementType, tc.ElementCount, tc.Flags };
}
}
}
}
#endif
| 46.858974 | 150 | 0.769631 | [
"MIT"
] | NIKJOO/iced | src/csharp/Intel/Iced.UnitTests/Intel/InstructionInfoTests/MemorySizeExtensionsTests.cs | 3,655 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace HomePage.Web.IdentityServer.UI
{
public class ExternalProvider
{
public string DisplayName { get; set; }
public string AuthenticationScheme { get; set; }
}
} | 31.166667 | 107 | 0.708556 | [
"Apache-2.0"
] | avaxxx/homepage | src/HomePage.Web/IdentityServer/Account/ExternalProvider.cs | 376 | C# |
using System.Web.Http;
using WebActivatorEx;
using SampleWebApi;
using Swashbuckle.Application;
using SampleWebApi.Filters;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace SampleWebApi
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
// By default, the service root url is inferred from the request used to access the docs.
// However, there may be situations (e.g. proxy and load-balanced environments) where this does not
// resolve correctly. You can workaround this by providing your own code to determine the root URL.
//
//c.RootUrl(req => GetRootUrlFromAppConfig());
// If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access
// the docs is taken as the default. If your API supports multiple schemes and you want to be explicit
// about them, you can use the "Schemes" option as shown below.
//
//c.Schemes(new[] { "http", "https" });
// Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to
// hold additional metadata for an API. Version and title are required but you can also provide
// additional fields by chaining methods off SingleApiVersion.
//
c.SingleApiVersion("v1", "SampleWebApi");
// If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
// In this case, you must provide a lambda that tells Swashbuckle which actions should be
// included in the docs for a given API version. Like "SingleApiVersion", each call to "Version"
// returns an "Info" builder so you can provide additional metadata per API version.
//
//c.MultipleApiVersions(
// (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
// (vc) =>
// {
// vc.Version("v2", "Swashbuckle Dummy API V2");
// vc.Version("v1", "Swashbuckle Dummy API V1");
// });
// You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API.
// See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details.
// NOTE: These only define the schemes and need to be coupled with a corresponding "security" property
// at the document or operation level to indicate which schemes are required for an operation. To do this,
// you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties
// according to your specific authorization implementation
//
//c.BasicAuth("basic")
// .Description("Basic HTTP Authentication");
//
// NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section
//c.ApiKey("apiKey")
// .Description("API Key Authentication")
// .Name("apiKey")
// .In("header");
//
//c.OAuth2("oauth2")
// .Description("OAuth2 Implicit Grant")
// .Flow("implicit")
// .AuthorizationUrl("http://petstore.swagger.wordnik.com/api/oauth/dialog")
// //.TokenUrl("https://tempuri.org/token")
// .Scopes(scopes =>
// {
// scopes.Add("read", "Read access to protected resources");
// scopes.Add("write", "Write access to protected resources");
// });
c.OperationFilter(() => new AuthorizationHeaderParameterOperationFilter());
// Set this flag to omit descriptions for any actions decorated with the Obsolete attribute
//c.IgnoreObsoleteActions();
// Each operation be assigned one or more tags which are then used by consumers for various reasons.
// For example, the swagger-ui groups operations according to the first tag of each operation.
// By default, this will be controller name but you can use the "GroupActionsBy" option to
// override with any value.
//
//c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString());
// You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate
// the order in which operations are listed. For example, if the default grouping is in place
// (controller name) and you specify a descending alphabetic sort order, then actions from a
// ProductsController will be listed before those from a CustomersController. This is typically
// used to customize the order of groupings in the swagger-ui.
//
//c.OrderActionGroupsBy(new DescendingAlphabeticComparer());
// If you annotate Controllers and API Types with
// Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate
// those comments into the generated docs and UI. You can enable this by providing the path to one or
// more Xml comment files.
//
//c.IncludeXmlComments(GetXmlCommentsPath());
// Swashbuckle makes a best attempt at generating Swagger compliant JSON schemas for the various types
// exposed in your API. However, there may be occasions when more control of the output is needed.
// This is supported through the "MapType" and "SchemaFilter" options:
//
// Use the "MapType" option to override the Schema generation for a specific type.
// It should be noted that the resulting Schema will be placed "inline" for any applicable Operations.
// While Swagger 2.0 supports inline definitions for "all" Schema types, the swagger-ui tool does not.
// It expects "complex" Schemas to be defined separately and referenced. For this reason, you should only
// use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a
// complex Schema, use a Schema filter.
//
//c.MapType<ProductType>(() => new Schema { type = "integer", format = "int32" });
// If you want to post-modify "complex" Schemas once they've been generated, across the board or for a
// specific type, you can wire up one or more Schema filters.
//
//c.SchemaFilter<ApplySchemaVendorExtensions>();
// In a Swagger 2.0 document, complex types are typically declared globally and referenced by unique
// Schema Id. By default, Swashbuckle does NOT use the full type name in Schema Ids. In most cases, this
// works well because it prevents the "implementation detail" of type namespaces from leaking into your
// Swagger docs and UI. However, if you have multiple types in your API with the same class name, you'll
// need to opt out of this behavior to avoid Schema Id conflicts.
//
//c.UseFullTypeNameInSchemaIds();
// Alternatively, you can provide your own custom strategy for inferring SchemaId's for
// describing "complex" types in your API.
//
//c.SchemaId(t => t.FullName.Contains('`') ? t.FullName.Substring(0, t.FullName.IndexOf('`')) : t.FullName);
// Set this flag to omit schema property descriptions for any type properties decorated with the
// Obsolete attribute
//c.IgnoreObsoleteProperties();
// In accordance with the built in JsonSerializer, Swashbuckle will, by default, describe enums as integers.
// You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given
// enum type. Swashbuckle will honor this change out-of-the-box. However, if you use a different
// approach to serialize enums as strings, you can also force Swashbuckle to describe them as strings.
//
c.DescribeAllEnumsAsStrings();
// Similar to Schema filters, Swashbuckle also supports Operation and Document filters:
//
// Post-modify Operation descriptions once they've been generated by wiring up one or more
// Operation filters.
//
//c.OperationFilter<AddDefaultResponse>();
//
// If you've defined an OAuth2 flow as described above, you could use a custom filter
// to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required
// to execute the operation
//
//c.OperationFilter<AssignOAuth2SecurityRequirements>();
// Post-modify the entire Swagger document by wiring up one or more Document filters.
// This gives full control to modify the final SwaggerDocument. You should have a good understanding of
// the Swagger 2.0 spec. - https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
// before using this option.
//
//c.DocumentFilter<ApplyDocumentVendorExtensions>();
// In contrast to WebApi, Swagger 2.0 does not include the query string component when mapping a URL
// to an action. As a result, Swashbuckle will raise an exception if it encounters multiple actions
// with the same path (sans query string) and HTTP method. You can workaround this by providing a
// custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs
//
//c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
// Wrap the default SwaggerGenerator with additional behavior (e.g. caching) or provide an
// alternative implementation for ISwaggerProvider with the CustomProvider option.
//
//c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));
})
.EnableSwaggerUi(c =>
{
// Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets.
// The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown below.
//
//c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");
// Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui
// has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown above.
//
//c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
// The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false"
// strings as the possible choices. You can use this option to change these to something else,
// for example 0 and 1.
//
//c.BooleanValues(new[] { "0", "1" });
// By default, swagger-ui will validate specs against swagger.io's online validator and display the result
// in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the
// feature entirely.
//c.SetValidatorUrl("http://localhost/validator");
//c.DisableValidator();
// Use this option to control how the Operation listing is displayed.
// It can be set to "None" (default), "List" (shows operations for each resource),
// or "Full" (fully expanded: shows operations and their details).
//
//c.DocExpansion(DocExpansion.List);
// Specify which HTTP operations will have the 'Try it out!' option. An empty paramter list disables
// it for all operations.
//
//c.SupportedSubmitMethods("GET", "HEAD");
// Use the CustomAsset option to provide your own version of assets used in the swagger-ui.
// It's typically used to instruct Swashbuckle to return your version instead of the default
// when a request is made for "index.html". As with all custom content, the file must be included
// in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to
// the method as shown below.
//
//c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html");
// If your API has multiple versions and you've applied the MultipleApiVersions setting
// as described above, you can also enable a select box in the swagger-ui, that displays
// a discovery URL for each version. This provides a convenient way for users to browse documentation
// for different API versions.
//
//c.EnableDiscoveryUrlSelector();
// If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to
// the Swagger 2.0 specification, you can enable UI support as shown below.
//
//c.EnableOAuth2Support(
// clientId: "test-client-id",
// clientSecret: null,
// realm: "test-realm",
// appName: "Swagger UI"
// //additionalQueryStringParams: new Dictionary<string, string>() { { "foo", "bar" } }
//);
// If your API supports ApiKey, you can override the default values.
// "apiKeyIn" can either be "query" or "header"
//
//c.EnableApiKeySupport("apiKey", "header");
});
}
}
}
| 67.352 | 133 | 0.535396 | [
"MIT"
] | marcominerva/RestLibrary | Samples/SampleWebApi/App_Start/SwaggerConfig.cs | 16,838 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/msctf.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="ITfThreadMgr" /> struct.</summary>
public static unsafe partial class ITfThreadMgrTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ITfThreadMgr" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ITfThreadMgr).GUID, Is.EqualTo(IID_ITfThreadMgr));
}
/// <summary>Validates that the <see cref="ITfThreadMgr" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ITfThreadMgr>(), Is.EqualTo(sizeof(ITfThreadMgr)));
}
/// <summary>Validates that the <see cref="ITfThreadMgr" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ITfThreadMgr).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ITfThreadMgr" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ITfThreadMgr), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ITfThreadMgr), Is.EqualTo(4));
}
}
}
}
| 35.961538 | 145 | 0.625668 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/msctf/ITfThreadMgrTests.cs | 1,872 | C# |
namespace EOSNewYork.EOSCore.Serialization
{
public class PermissionName : BaseName
{
public PermissionName() { }
public PermissionName(string value)
: base(value)
{
}
}
} | 17.615385 | 43 | 0.576419 | [
"CC0-1.0"
] | HirenBodhi/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK | NextGenSoftware.OASIS.API.Providers.EOSIOOASIS/EOSNewYork.EOSCore/Serialization/PermissionName.cs | 229 | C# |
#region License
//MIT License
//Copyright(c) [2020]
//[Xylex Sirrush Rayne]
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
#endregion
using System.Runtime.Serialization;
namespace DreadBot
{
/// <summary>
/// This object represents one shipping option.
/// </summary>
[DataContract]
public class ShippingOption
{
/// <summary>
/// Shipping option identifier
/// </summary>
[DataMember(Name = "id", IsRequired = true)]
public string id { get; set; }
/// <summary>
/// Option title
/// </summary>
[DataMember(Name = "title", IsRequired = true)]
public string title { get; set; }
/// <summary>
/// List of price portions
/// </summary>
[DataMember(Name = "prices", IsRequired = true)]
public LabeledPrice[] prices { get; set; }
}
}
| 35.6 | 80 | 0.725281 | [
"MIT"
] | Deer-Spangle/DreadBot | source/Contracts/Payments/ShippingOption.cs | 1,780 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace OCTO.BLL.Models.Filters
{
public class ContactFilterModel
{
}
}
| 14.090909 | 35 | 0.729032 | [
"MIT"
] | narekye/diploma-octo | OCTO/OCTO.BLL.Models/Filters/ContactFilterModel.cs | 157 | C# |
using BlogService.Data;
using BlogService.Features.Core;
using MediatR;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Data.Entity;
using System;
namespace BlogService.Features.Authors
{
public class GetAuthorsQuery
{
public class GetAuthorsRequest : IRequest<GetAuthorsResponse> {
public Guid TenantUniqueId { get; set; }
}
public class GetAuthorsResponse
{
public ICollection<AuthorApiModel> Authors { get; set; } = new HashSet<AuthorApiModel>();
}
public class GetAuthorsHandler : IAsyncRequestHandler<GetAuthorsRequest, GetAuthorsResponse>
{
public GetAuthorsHandler(IBlogServiceContext context, ICache cache)
{
_context = context;
_cache = cache;
}
public async Task<GetAuthorsResponse> Handle(GetAuthorsRequest request)
{
var authors = await _context.Authors
.Include(x=>x.Tenant)
.Where(x =>x.Tenant.UniqueId == request.TenantUniqueId)
.ToListAsync();
return new GetAuthorsResponse()
{
Authors = authors.Select(x => AuthorApiModel.FromAuthor(x)).ToList()
};
}
private readonly IBlogServiceContext _context;
private readonly ICache _cache;
}
}
}
| 29.431373 | 101 | 0.586942 | [
"MIT"
] | QuinntyneBrown/BlogService | src/BlogService/Features/Authors/GetAuthorsQuery.cs | 1,501 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.SqlScriptPublish;
using Microsoft.Kusto.ServiceLayer.Scripting.Contracts;
using Microsoft.SqlTools.Utility;
namespace Microsoft.Kusto.ServiceLayer.Scripting
{
/// <summary>
/// Extension methods used by the scripting service.
/// </summary>
internal static class ScriptingExtensionMethods
{
/// <summary>
/// Gets the status of a scripting operation for the passed scripting event.
/// </summary>
/// <param name="e">The scripting event.</param>
/// <returns>The status.</returns>
public static string GetStatus(this ScriptEventArgs e)
{
Validate.IsNotNull("e", e);
string status = null;
if (e.Error != null)
{
status = "Error";
}
else if (e.Completed)
{
status = "Completed";
}
else
{
status = "Progress";
}
return status;
}
/// <summary>
/// Returns a list of ScriptingObject instances for the passed SqlScriptPublishModel instance.
/// </summary>
/// <param name="publishModel">The sql script publish model instance.</param>
/// <returns>The list of scripting objects.</returns>
public static List<ScriptingObject> GetDatabaseObjects(this SqlScriptPublishModel publishModel)
{
Validate.IsNotNull("publishModel", publishModel);
List<ScriptingObject> databaseObjects = new List<ScriptingObject>();
IEnumerable<DatabaseObjectType> objectTypes = publishModel.GetDatabaseObjectTypes();
Logger.Write(
TraceEventType.Verbose,
string.Format(
"Loaded SMO object type count {0}, types: {1}",
objectTypes.Count(),
string.Join(", ", objectTypes)));
foreach (DatabaseObjectType objectType in objectTypes)
{
IEnumerable<KeyValuePair<string, string>> databaseObjectsOfType = publishModel.EnumChildrenForDatabaseObjectType(objectType);
Logger.Write(
TraceEventType.Verbose,
string.Format(
"Loaded SMO urn object count {0} for type {1}, urns: {2}",
objectType,
databaseObjectsOfType.Count(),
string.Join(", ", databaseObjectsOfType.Select(p => p.Value))));
databaseObjects.AddRange(databaseObjectsOfType.Select(d => new Urn(d.Value).ToScriptingObject()));
}
return databaseObjects;
}
/// <summary>
/// Creates a SMO Urn instance based on the passed ScriptingObject instance.
/// </summary>
/// <param name="scriptingObject">The scripting object instance.</param>
/// <param name="database">The name of the database referenced by the Urn.</param>
/// <returns>The Urn instance.</returns>
public static Urn ToUrn(this ScriptingObject scriptingObject, string server, string database)
{
Validate.IsNotNull("scriptingObject", scriptingObject);
Validate.IsNotNullOrEmptyString("server", server);
Validate.IsNotNullOrWhitespaceString("scriptingObject.Name", scriptingObject.Name);
Validate.IsNotNullOrWhitespaceString("scriptingObject.Type", scriptingObject.Type);
// Leaving the server name blank will automatically match whatever the server SMO is running against.
string urn = string.Format(
"Server[@Name='{0}']/Database[@Name='{1}']/{2}[@Name='{3}' {4}]",
server.ToUpper(),
Urn.EscapeString(database),
scriptingObject.Type,
Urn.EscapeString(scriptingObject.Name),
scriptingObject.Schema != null ? string.Format("and @Schema = '{0}'", Urn.EscapeString(scriptingObject.Schema)) : string.Empty);
return new Urn(urn);
}
/// <summary>
/// Creates a ScriptingObject instance based on the passed SMO Urn instance.
/// </summary>
/// <param name="urn">The urn instance.</param>
/// <returns>The scripting object instance.</returns>
public static ScriptingObject ToScriptingObject(this Urn urn)
{
Validate.IsNotNull("urn", urn);
return new ScriptingObject
{
Type = urn.Type,
Schema = urn.GetAttribute("Schema"),
Name = urn.GetAttribute("Name"),
};
}
}
}
| 38.465649 | 144 | 0.590792 | [
"MIT"
] | ConnectionMaster/sqltoolsservice | src/Microsoft.Kusto.ServiceLayer/Scripting/ScriptingExtensionMethods.cs | 5,041 | 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.Globalization;
using System.Runtime.InteropServices;
#pragma warning disable 436 // Redefining types from Windows.Foundation
namespace Windows.UI.Xaml.Controls.Primitives
{
//
// GeneratorPosition is the managed projection of Windows.UI.Xaml.Controls.Primitives.GeneratorPosition.
// Any changes to the layout of this type must be exactly mirrored on the native WinRT side as well.
//
// Note that this type is owned by the Jupiter team. Please contact them before making any
// changes here.
//
[StructLayout(LayoutKind.Sequential)]
public struct GeneratorPosition
{
private int _index;
private int _offset;
public int Index { get { return _index; } set { _index = value; } }
public int Offset { get { return _offset; } set { _offset = value; } }
public GeneratorPosition(int index, int offset)
{
_index = index;
_offset = offset;
}
public override int GetHashCode()
{
return _index.GetHashCode() + _offset.GetHashCode();
}
public override string ToString()
{
return string.Concat("GeneratorPosition (", _index.ToString(CultureInfo.InvariantCulture), ",", _offset.ToString(CultureInfo.InvariantCulture), ")");
}
public override bool Equals(object o)
{
if (o is GeneratorPosition)
{
GeneratorPosition that = (GeneratorPosition)o;
return _index == that._index &&
_offset == that._offset;
}
return false;
}
public static bool operator ==(GeneratorPosition gp1, GeneratorPosition gp2)
{
return gp1._index == gp2._index &&
gp1._offset == gp2._offset;
}
public static bool operator !=(GeneratorPosition gp1, GeneratorPosition gp2)
{
return !(gp1 == gp2);
}
}
}
#pragma warning restore 436
| 30.04 | 161 | 0.614292 | [
"MIT"
] | 2E0PGS/corefx | src/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Controls/Primitives/GeneratorPosition.cs | 2,253 | C# |
using System;
using System.Collections;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Asn1
{
public class Asn1EncodableVector
: IEnumerable
{
private IList v = Platform.CreateArrayList();
public static Asn1EncodableVector FromEnumerable(
IEnumerable e)
{
Asn1EncodableVector v = new Asn1EncodableVector();
foreach (Asn1Encodable obj in e)
{
v.Add(obj);
}
return v;
}
// public Asn1EncodableVector()
// {
// }
public Asn1EncodableVector(
params Asn1Encodable[] v)
{
Add(v);
}
// public void Add(
// Asn1Encodable obj)
// {
// v.Add(obj);
// }
public void Add(
params Asn1Encodable[] objs)
{
foreach (Asn1Encodable obj in objs)
{
v.Add(obj);
}
}
public void AddOptional(
params Asn1Encodable[] objs)
{
if (objs != null)
{
foreach (Asn1Encodable obj in objs)
{
if (obj != null)
{
v.Add(obj);
}
}
}
}
public Asn1Encodable this[
int index]
{
get { return (Asn1Encodable) v[index]; }
}
[Obsolete("Use 'object[index]' syntax instead")]
public Asn1Encodable Get(
int index)
{
return this[index];
}
[Obsolete("Use 'Count' property instead")]
public int Size
{
get { return v.Count; }
}
public int Count
{
get { return v.Count; }
}
public IEnumerator GetEnumerator()
{
return v.GetEnumerator();
}
}
}
| 15.382979 | 53 | 0.59751 | [
"Apache-2.0"
] | Arthurvdmerwe/-ISO-TC-68-SC-2-ISO20038 | Crypto/src/asn1/Asn1EncodableVector.cs | 1,446 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using data.context;
namespace data.Migrations
{
[DbContext(typeof(FSPropertyManagementIdentityContext))]
partial class FSPropertyManagementIdentityContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.13")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("data.models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<Guid>("CompanyID")
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("CompanyID");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("data.models.Company", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CompanyName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Company");
});
modelBuilder.Entity("data.models.Property", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("AddressLine1")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("AddressLine2")
.HasColumnType("nvarchar(max)");
b.Property<string>("City")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("CompanyId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Parking")
.HasColumnType("bit");
b.Property<bool>("Pets")
.HasColumnType("bit");
b.Property<string>("PostalCode")
.IsRequired()
.HasMaxLength(6)
.HasColumnType("nvarchar(6)");
b.Property<string>("PropertyDescription")
.HasColumnType("nvarchar(max)");
b.Property<string>("Province")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Smoking")
.HasColumnType("bit");
b.Property<int>("TotalUnits")
.HasColumnType("int");
b.Property<int?>("TotalVacantUnits")
.IsRequired()
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.ToTable("Property");
});
modelBuilder.Entity("data.models.PropertyType", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("PropertyType");
});
modelBuilder.Entity("data.models.Tenant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("City")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("CompanyId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Country")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("EmergencyContactEmail")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("EmergencyContactName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("EmergencyContactPhone")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("MailingAddressLine1")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("MailingAddressLine2")
.HasColumnType("nvarchar(max)");
b.Property<bool>("ParkingStall")
.HasColumnType("bit");
b.Property<string>("Phone")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PostalCode")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PreferredName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Province")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Standing")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("TenancyStartDate")
.HasColumnType("datetime2");
b.Property<Guid>("UnitId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("UnitId");
b.ToTable("Tenant");
});
modelBuilder.Entity("data.models.Unit", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<decimal>("Area")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("DepositAmount")
.HasColumnType("decimal(18,2)");
b.Property<bool>("Furnished")
.HasColumnType("bit");
b.Property<string>("Laundry")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Number")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("NumberofRooms")
.HasColumnType("int");
b.Property<Guid>("PropertyId")
.HasColumnType("uniqueidentifier");
b.Property<decimal>("RentAmount")
.HasColumnType("decimal(18,2)");
b.Property<Guid>("UnitTypeId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("PropertyId");
b.HasIndex("UnitTypeId");
b.ToTable("Unit");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("data.models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("data.models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("data.models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("data.models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("data.models.ApplicationUser", b =>
{
b.HasOne("data.models.Company", "Company")
.WithMany("ApplicationUsers")
.HasForeignKey("CompanyID")
.HasConstraintName("FK_Company_TO_ApplicationUser")
.IsRequired();
b.Navigation("Company");
});
modelBuilder.Entity("data.models.Property", b =>
{
b.HasOne("data.models.Company", null)
.WithMany("Properties")
.HasForeignKey("CompanyId");
});
modelBuilder.Entity("data.models.Tenant", b =>
{
b.HasOne("data.models.Company", null)
.WithMany("Tenants")
.HasForeignKey("CompanyId");
b.HasOne("data.models.Unit", "Unit")
.WithMany("Tenants")
.HasForeignKey("UnitId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Unit");
});
modelBuilder.Entity("data.models.Unit", b =>
{
b.HasOne("data.models.Property", "Property")
.WithMany("Units")
.HasForeignKey("PropertyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("data.models.PropertyType", "UnitType")
.WithMany("Units")
.HasForeignKey("UnitTypeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Property");
b.Navigation("UnitType");
});
modelBuilder.Entity("data.models.Company", b =>
{
b.Navigation("ApplicationUsers");
b.Navigation("Properties");
b.Navigation("Tenants");
});
modelBuilder.Entity("data.models.Property", b =>
{
b.Navigation("Units");
});
modelBuilder.Entity("data.models.PropertyType", b =>
{
b.Navigation("Units");
});
modelBuilder.Entity("data.models.Unit", b =>
{
b.Navigation("Tenants");
});
#pragma warning restore 612, 618
}
}
}
| 35.863322 | 125 | 0.435525 | [
"MIT"
] | Ctrl-Tech-Crop/property-management | src/app/data/Migrations/FSPropertyManagementIdentityContextModelSnapshot.cs | 20,731 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medical.GUI.AnomalousMvc;
using Engine.Saving;
using Medical.Controller.AnomalousMvc;
using Medical;
using Anomalous.GuiFramework;
namespace Lecture.GUI
{
class SlideTaskbarView : MyGUIView
{
public event Action<SlideTaskbarView> DisplayNameChanged;
private String displayName;
private List<Task> tasks = new List<Task>();
public SlideTaskbarView(String name, String displayName)
:base(name)
{
this.DisplayName = displayName;
this.ElementName = new BorderLayoutElementName(GUILocationNames.EditorBorderLayout, BorderLayoutLocations.Top);
}
public void addTask(Task task)
{
tasks.Add(task);
}
public IEnumerable<Task> Tasks
{
get
{
return tasks;
}
}
public String DisplayName
{
get
{
return displayName;
}
set
{
displayName = value;
if (DisplayNameChanged != null)
{
DisplayNameChanged.Invoke(this);
}
}
}
protected SlideTaskbarView(LoadInfo info)
:base(info)
{
}
}
}
| 23.333333 | 124 | 0.516327 | [
"MIT"
] | AnomalousMedical/Medical | Lecture/GUI/SlideTaskbar/SlideTaskbarView.cs | 1,472 | C# |
using AntShares.Core.Scripts;
using AntShares.Cryptography;
using AntShares.Cryptography.ECC;
using AntShares.IO;
using AntShares.Wallets;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AntShares.Core
{
/// <summary>
/// 实现区块链功能的基类
/// </summary>
public abstract class Blockchain : IDisposable
{
/// <summary>
/// 当区块被写入到硬盘后触发
/// </summary>
public static event EventHandler<Block> PersistCompleted;
/// <summary>
/// 产生每个区块的时间间隔,已秒为单位
/// </summary>
public const uint SecondsPerBlock = 15;
/// <summary>
/// 小蚁币产量递减的时间间隔,以区块数量为单位
/// </summary>
public const uint DecrementInterval = 2000000;
/// <summary>
/// 每个区块产生的小蚁币的数量
/// </summary>
public static readonly uint[] MintingAmount = { 8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
/// <summary>
/// 产生每个区块的时间间隔
/// </summary>
public static readonly TimeSpan TimePerBlock = TimeSpan.FromSeconds(SecondsPerBlock);
/// <summary>
/// 后备记账人列表
/// </summary>
public static readonly ECPoint[] StandbyMiners =
{
ECPoint.DecodePoint("0327da12b5c40200e9f65569476bbff2218da4f32548ff43b6387ec1416a231ee8".HexToBytes(), ECCurve.Secp256r1),
ECPoint.DecodePoint("026ce35b29147ad09e4afe4ec4a7319095f08198fa8babbe3c56e970b143528d22".HexToBytes(), ECCurve.Secp256r1),
ECPoint.DecodePoint("0209e7fd41dfb5c2f8dc72eb30358ac100ea8c72da18847befe06eade68cebfcb9".HexToBytes(), ECCurve.Secp256r1),
ECPoint.DecodePoint("039dafd8571a641058ccc832c5e2111ea39b09c0bde36050914384f7a48bce9bf9".HexToBytes(), ECCurve.Secp256r1),
ECPoint.DecodePoint("038dddc06ce687677a53d54f096d2591ba2302068cf123c1f2d75c2dddc5425579".HexToBytes(), ECCurve.Secp256r1),
ECPoint.DecodePoint("02d02b1873a0863cd042cc717da31cea0d7cf9db32b74d4c72c01b0011503e2e22".HexToBytes(), ECCurve.Secp256r1),
ECPoint.DecodePoint("034ff5ceeac41acf22cd5ed2da17a6df4dd8358fcb2bfb1a43208ad0feaab2746b".HexToBytes(), ECCurve.Secp256r1),
};
/// <summary>
/// 小蚁股
/// </summary>
public static readonly RegisterTransaction AntShare = new RegisterTransaction
{
AssetType = AssetType.AntShare,
#if TESTNET
Name = "[{'lang':'zh-CN','name':'小蚁股(测试)'},{'lang':'en','name':'AntShare(TestNet)'}]",
#else
Name = "[{'lang':'zh-CN','name':'小蚁股'},{'lang':'en','name':'AntShare'}]",
#endif
Amount = Fixed8.FromDecimal(100000000),
Issuer = ECPoint.DecodePoint((new[] { (byte)0x02 }).Concat(ECCurve.Secp256r1.G.EncodePoint(false).Skip(1).Sha256().Sha256()).ToArray(), ECCurve.Secp256r1),
Admin = (new[] { (byte)ScriptOp.OP_TRUE }).ToScriptHash(),
Attributes = new TransactionAttribute[0],
Inputs = new TransactionInput[0],
Outputs = new TransactionOutput[0],
Scripts = new Script[0]
};
/// <summary>
/// 小蚁币
/// </summary>
public static readonly RegisterTransaction AntCoin = new RegisterTransaction
{
AssetType = AssetType.AntCoin,
#if TESTNET
Name = "[{'lang':'zh-CN','name':'小蚁币(测试)'},{'lang':'en','name':'AntCoin(TestNet)'}]",
#else
Name = "[{'lang':'zh-CN','name':'小蚁币'},{'lang':'en','name':'AntCoin'}]",
#endif
Amount = Fixed8.FromDecimal(MintingAmount.Sum(p => p * DecrementInterval)),
Issuer = ECPoint.DecodePoint((new[] { (byte)0x02 }).Concat(ECCurve.Secp256r1.G.EncodePoint(false).Skip(1).Sha256().Sha256()).ToArray(), ECCurve.Secp256r1),
Admin = (new[] { (byte)ScriptOp.OP_FALSE }).ToScriptHash(),
Attributes = new TransactionAttribute[0],
Inputs = new TransactionInput[0],
Outputs = new TransactionOutput[0],
Scripts = new Script[0]
};
/// <summary>
/// 创世区块
/// </summary>
public static readonly Block GenesisBlock = new Block
{
PrevBlock = UInt256.Zero,
Timestamp = (new DateTime(2016, 7, 15, 15, 8, 21, DateTimeKind.Utc)).ToTimestamp(),
Height = 0,
Nonce = 2083236893, //向比特币致敬
NextMiner = GetMinerAddress(StandbyMiners),
Script = new Script
{
StackScript = new byte[0],
RedeemScript = new[] { (byte)ScriptOp.OP_TRUE }
},
Transactions = new Transaction[]
{
new MinerTransaction
{
Nonce = 2083236893,
Attributes = new TransactionAttribute[0],
Inputs = new TransactionInput[0],
Outputs = new TransactionOutput[0],
Scripts = new Script[0]
},
AntShare,
AntCoin,
new IssueTransaction
{
Nonce = 2083236893,
Attributes = new TransactionAttribute[0],
Inputs = new TransactionInput[0],
Outputs = new[]
{
new TransactionOutput
{
AssetId = AntShare.Hash,
Value = AntShare.Amount,
ScriptHash = MultiSigContract.CreateMultiSigRedeemScript(StandbyMiners.Length / 2 + 1, StandbyMiners).ToScriptHash()
}
},
Scripts = new[]
{
new Script
{
StackScript = new byte[0],
RedeemScript = new[] { (byte)ScriptOp.OP_TRUE }
}
}
}
}
};
/// <summary>
/// 区块链所提供的功能
/// </summary>
public abstract BlockchainAbility Ability { get; }
/// <summary>
/// 当前最新区块散列值
/// </summary>
public abstract UInt256 CurrentBlockHash { get; }
/// <summary>
/// 当前最新区块头的散列值
/// </summary>
public virtual UInt256 CurrentHeaderHash => CurrentBlockHash;
/// <summary>
/// 默认的区块链实例
/// </summary>
public static Blockchain Default { get; private set; } = null;
/// <summary>
/// 区块头高度
/// </summary>
public virtual uint HeaderHeight => Height;
/// <summary>
/// 区块高度
/// </summary>
public abstract uint Height { get; }
/// <summary>
/// 表示当前的区块链实现是否为只读的
/// </summary>
public abstract bool IsReadOnly { get; }
static Blockchain()
{
GenesisBlock.RebuildMerkleRoot();
}
/// <summary>
/// 将指定的区块添加到区块链中
/// </summary>
/// <param name="block">要添加的区块</param>
/// <returns>返回是否添加成功</returns>
protected internal abstract bool AddBlock(Block block);
/// <summary>
/// 将指定的区块头添加到区块头链中
/// </summary>
/// <param name="headers">要添加的区块头列表</param>
protected internal abstract void AddHeaders(IEnumerable<Block> headers);
/// <summary>
/// 判断区块链中是否包含指定的资产
/// </summary>
/// <param name="hash">资产编号</param>
/// <returns>如果包含指定资产则返回true</returns>
public virtual bool ContainsAsset(UInt256 hash)
{
return hash == AntShare.Hash || hash == AntCoin.Hash;
}
/// <summary>
/// 判断区块链中是否包含指定的区块
/// </summary>
/// <param name="hash">区块编号</param>
/// <returns>如果包含指定区块则返回true</returns>
public virtual bool ContainsBlock(UInt256 hash)
{
return hash == GenesisBlock.Hash;
}
/// <summary>
/// 判断区块链中是否包含指定的交易
/// </summary>
/// <param name="hash">交易编号</param>
/// <returns>如果包含指定交易则返回true</returns>
public virtual bool ContainsTransaction(UInt256 hash)
{
return GenesisBlock.Transactions.Any(p => p.Hash == hash);
}
public bool ContainsUnspent(TransactionInput input)
{
return ContainsUnspent(input.PrevHash, input.PrevIndex);
}
public abstract bool ContainsUnspent(UInt256 hash, ushort index);
public abstract void Dispose();
public abstract IEnumerable<RegisterTransaction> GetAssets();
/// <summary>
/// 根据指定的高度,返回对应的区块信息
/// </summary>
/// <param name="height">区块高度</param>
/// <returns>返回对应的区块信息</returns>
public Block GetBlock(uint height)
{
return GetBlock(GetBlockHash(height));
}
/// <summary>
/// 根据指定的散列值,返回对应的区块信息
/// </summary>
/// <param name="hash">散列值</param>
/// <returns>返回对应的区块信息</returns>
public virtual Block GetBlock(UInt256 hash)
{
if (hash == GenesisBlock.Hash)
return GenesisBlock;
return null;
}
/// <summary>
/// 根据指定的高度,返回对应区块的散列值
/// </summary>
/// <param name="height">区块高度</param>
/// <returns>返回对应区块的散列值</returns>
public virtual UInt256 GetBlockHash(uint height)
{
if (height == 0) return GenesisBlock.Hash;
return null;
}
public IEnumerable<EnrollmentTransaction> GetEnrollments()
{
return GetEnrollments(Enumerable.Empty<Transaction>());
}
public abstract IEnumerable<EnrollmentTransaction> GetEnrollments(IEnumerable<Transaction> others);
/// <summary>
/// 根据指定的高度,返回对应的区块头信息
/// </summary>
/// <param name="height">区块高度</param>
/// <returns>返回对应的区块头信息</returns>
public virtual Block GetHeader(uint height)
{
return GetHeader(GetBlockHash(height));
}
/// <summary>
/// 根据指定的散列值,返回对应的区块头信息
/// </summary>
/// <param name="hash">散列值</param>
/// <returns>返回对应的区块头信息</returns>
public virtual Block GetHeader(UInt256 hash)
{
return GetBlock(hash)?.Header;
}
public abstract UInt256[] GetLeafHeaderHashes();
/// <summary>
/// 获取记账人的合约地址
/// </summary>
/// <param name="miners">记账人的公钥列表</param>
/// <returns>返回记账人的合约地址</returns>
public static UInt160 GetMinerAddress(ECPoint[] miners)
{
return MultiSigContract.CreateMultiSigRedeemScript(miners.Length - (miners.Length - 1) / 3, miners).ToScriptHash();
}
private List<ECPoint> _miners = new List<ECPoint>();
/// <summary>
/// 获取下一个区块的记账人列表
/// </summary>
/// <returns>返回一组公钥,表示下一个区块的记账人列表</returns>
public ECPoint[] GetMiners()
{
lock (_miners)
{
if (_miners.Count == 0)
{
_miners.AddRange(GetMiners(Enumerable.Empty<Transaction>()));
}
return _miners.ToArray();
}
}
public virtual IEnumerable<ECPoint> GetMiners(IEnumerable<Transaction> others)
{
if (!Ability.HasFlag(BlockchainAbility.TransactionIndexes) || !Ability.HasFlag(BlockchainAbility.UnspentIndexes))
throw new NotSupportedException();
//TODO: 此处排序可能将耗费大量内存,考虑是否采用其它机制
Vote[] votes = GetVotes(others).OrderBy(p => p.Enrollments.Length).ToArray();
int miner_count = (int)votes.WeightedFilter(0.25, 0.75, p => p.Count.GetData(), (p, w) => new
{
MinerCount = p.Enrollments.Length,
Weight = w
}).WeightedAverage(p => p.MinerCount, p => p.Weight);
miner_count = Math.Max(miner_count, StandbyMiners.Length);
Dictionary<ECPoint, Fixed8> miners = new Dictionary<ECPoint, Fixed8>();
Dictionary<UInt256, ECPoint> enrollments = GetEnrollments(others).ToDictionary(p => p.Hash, p => p.PublicKey);
foreach (var vote in votes)
{
foreach (UInt256 hash in vote.Enrollments)
{
if (!enrollments.ContainsKey(hash)) continue;
ECPoint pubkey = enrollments[hash];
if (!miners.ContainsKey(pubkey))
{
miners.Add(pubkey, Fixed8.Zero);
}
miners[pubkey] += vote.Count;
}
}
return miners.OrderByDescending(p => p.Value).ThenBy(p => p.Key).Select(p => p.Key).Concat(StandbyMiners).Take(miner_count);
}
/// <summary>
/// 根据指定的散列值,返回下一个区块的信息
/// </summary>
/// <param name="hash">散列值</param>
/// <returns>返回下一个区块的信息>
public abstract Block GetNextBlock(UInt256 hash);
/// <summary>
/// 根据指定的散列值,返回下一个区块的散列值
/// </summary>
/// <param name="hash">散列值</param>
/// <returns>返回下一个区块的散列值</returns>
public abstract UInt256 GetNextBlockHash(UInt256 hash);
/// <summary>
/// 根据指定的资产编号,返回对应资产的发行量
/// </summary>
/// <param name="asset_id">资产编号</param>
/// <returns>返回对应资产的当前已经发行的数量</returns>
public abstract Fixed8 GetQuantityIssued(UInt256 asset_id);
/// <summary>
/// 根据指定的区块高度,返回对应区块及之前所有区块中包含的系统费用的总量
/// </summary>
/// <param name="height">区块高度</param>
/// <returns>返回对应的系统费用的总量</returns>
public virtual long GetSysFeeAmount(uint height)
{
return GetSysFeeAmount(GetBlockHash(height));
}
/// <summary>
/// 根据指定的区块散列值,返回对应区块及之前所有区块中包含的系统费用的总量
/// </summary>
/// <param name="hash">散列值</param>
/// <returns>返回系统费用的总量</returns>
public abstract long GetSysFeeAmount(UInt256 hash);
/// <summary>
/// 根据指定的散列值,返回对应的交易信息
/// </summary>
/// <param name="hash">散列值</param>
/// <returns>返回对应的交易信息</returns>
public Transaction GetTransaction(UInt256 hash)
{
int height;
return GetTransaction(hash, out height);
}
/// <summary>
/// 根据指定的散列值,返回对应的交易信息与该交易所在区块的高度
/// </summary>
/// <param name="hash">交易散列值</param>
/// <param name="height">返回该交易所在区块的高度</param>
/// <returns>返回对应的交易信息</returns>
public virtual Transaction GetTransaction(UInt256 hash, out int height)
{
Transaction tx = GenesisBlock.Transactions.FirstOrDefault(p => p.Hash == hash);
if (tx != null)
{
height = 0;
return tx;
}
height = -1;
return null;
}
public abstract Dictionary<ushort, Claimable> GetUnclaimed(UInt256 hash);
/// <summary>
/// 根据指定的散列值和索引,获取对应的未花费的资产
/// </summary>
/// <param name="hash">交易散列值</param>
/// <param name="index">输出的索引</param>
/// <returns>返回一个交易输出,表示一个未花费的资产</returns>
public abstract TransactionOutput GetUnspent(UInt256 hash, ushort index);
/// <summary>
/// 获取选票信息
/// </summary>
/// <returns>返回一个选票列表,包含当前区块链中所有有效的选票</returns>
public IEnumerable<Vote> GetVotes()
{
return GetVotes(Enumerable.Empty<Transaction>());
}
public abstract IEnumerable<Vote> GetVotes(IEnumerable<Transaction> others);
/// <summary>
/// 判断交易是否双花
/// </summary>
/// <param name="tx">交易</param>
/// <returns>返回交易是否双花</returns>
public abstract bool IsDoubleSpend(Transaction tx);
/// <summary>
/// 当区块被写入到硬盘后调用
/// </summary>
/// <param name="block">区块</param>
protected void OnPersistCompleted(Block block)
{
lock (_miners)
{
_miners.Clear();
}
if (PersistCompleted != null) PersistCompleted(this, block);
}
/// <summary>
/// 注册默认的区块链实例
/// </summary>
/// <param name="blockchain">区块链实例</param>
/// <returns>返回注册后的区块链实例</returns>
public static Blockchain RegisterBlockchain(Blockchain blockchain)
{
if (blockchain == null) throw new ArgumentNullException();
if (Default != null) Default.Dispose();
Default = blockchain;
return blockchain;
}
}
}
| 36.436709 | 168 | 0.525737 | [
"MIT"
] | DavidthePangwaer/AntShares | AntSharesCore/Core/Blockchain.cs | 19,263 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LevelThree3
{
public partial class levelThree : Form
{
static int playPause;
List<Timer> timerlist = new List<Timer>();
// Timer initialize in arraylist
private void timerInitialize()
{
timerlist.Add(firstGhostTimer);
for (int i = 0; i < 3; i++)
{
timerlist.Add(secondGhostTimers[i]);
timerlist.Add(thirdGhostTimers[i]);
}
timerlist.Add(forthGhostTimer);
timerlist.Add(fifthGhostTimer);
timerlist.Add(sixthGhostTimer);
timerlist.Add(seventhGhostTimer);
timerlist.Add(bossGhostTimer);
}
// timer check for ghosts dispose
private void checkTimer()
{
timerInitialize();
if (ghost1.IsDisposed)
{
timerlist.Remove(firstGhostTimer);
}
if (Secondghostpics[0].IsDisposed)
{
timerlist.Remove(secondGhostTimers[0]);
}
if (Secondghostpics[1].IsDisposed)
{
timerlist.Remove(secondGhostTimers[1]);
}
if (Secondghostpics[2].IsDisposed)
{
timerlist.Remove(secondGhostTimers[2]);
}
if (Thirdghostpics[0].IsDisposed)
{
timerlist.Remove(thirdGhostTimers[0]);
}
if (Thirdghostpics[1].IsDisposed)
{
timerlist.Remove(thirdGhostTimers[1]);
}
if (Thirdghostpics[2].IsDisposed)
{
timerlist.Remove(thirdGhostTimers[2]);
}
if (ghost4.IsDisposed)
{
timerlist.Remove(forthGhostTimer);
}
if (ghost5.IsDisposed)
{
timerlist.Remove(fifthGhostTimer);
}
if (ghost6.IsDisposed)
{
timerlist.Remove(sixthGhostTimer);
}
if (ghost7.IsDisposed)
{
timerlist.Remove(seventhGhostTimer);
}
if (bossPicture.IsDisposed)
{
timerlist.Remove(bossGhostTimer);
}
}
// play pause button
private void playpause_Click(object sender, EventArgs e)
{
checkTimer();
if (playPause == 0)
{
playpause.Image = LevelThree3.Properties.Resources.play;
foreach (var timer in timerlist)
{
timer.Stop();
}
spellText.Enabled = false;
playPause = 1;
}
else if (playPause == 1)
{
playpause.Image = LevelThree3.Properties.Resources.Pause;
foreach (var timer in timerlist)
{
timer.Start();
}
firstGhostTimer.Start();
spellText.Enabled = true;
playPause = 0;
}
}
}
}
| 24.816176 | 73 | 0.482074 | [
"MIT"
] | AsifNoman/SpellAndSave | LevelThree3/PlayPause3.cs | 3,377 | C# |
using System;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
namespace HttpMultipartFormDataFactory.Tests;
internal static class TestValues
{
public static IFormFile File { get; } =
new FormFile(new MemoryStream(Encoding.Default.GetBytes("test")), 0, 4, "file", "file.txt")
{
Headers = new HeaderDictionary(),
ContentType = "text/plain",
ContentDisposition = "form-data; name=\"File\"; filename=\"file.txt\"",
};
public const object? Null = null!;
public static string String { get; } = Guid.NewGuid().ToString();
public static string EmptyString => string.Empty;
public const long Long = long.MaxValue;
public const int Int = int.MaxValue;
public const char Char = char.MaxValue;
public const bool Bool = true;
public const float Float = float.MaxValue;
public const double Double = double.MaxValue;
public const byte Byte = byte.MaxValue;
public const decimal Decimal = decimal.MaxValue;
public static Guid Guid { get; } = Guid.NewGuid();
public static DateTimeOffset DateTimeOffset { get; } = DateTimeOffset.UtcNow;
public static object?[] Nulls { get; } = { Null, Null, Null };
public static IFormFile[] Files { get; } = { File, File, File, };
public static string[] Strings { get; } = { String, String, String, };
public static string[] EmptyStrings { get; } = { EmptyString, EmptyString, EmptyString, };
public static long[] Longs { get; } = { Long, Long, Long, };
public static int[] Ints { get; } = { Int, Int, Int, };
public static char[] Chars { get; } = { Char, Char, Char, };
public static bool[] Bools { get; } = { Bool, Bool, Bool, };
public static float[] Floats { get; } = { Float, Float, Float, };
public static double[] Doubles { get; } = { Double, Double, Double, };
public static byte[] Bytes { get; } = { Byte, Byte, Byte, };
public static decimal[] Decimals { get; } = { Decimal, Decimal, Decimal, };
public static Guid[] Guids { get; } = { Guid, Guid, Guid, };
public static DateTimeOffset[] DateTimeOffsets { get; } = { DateTimeOffset, DateTimeOffset, DateTimeOffset, };
}
| 46.604167 | 114 | 0.649084 | [
"MIT"
] | hell03end/HttpMultipartFormDataFactory | HttpMultipartFormDataFactory.Tests/TestValues.cs | 2,237 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/resourcemanager/v3/folders.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.ResourceManager.V3 {
/// <summary>Holder for reflection information generated from google/cloud/resourcemanager/v3/folders.proto</summary>
public static partial class FoldersReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/resourcemanager/v3/folders.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FoldersReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci1nb29nbGUvY2xvdWQvcmVzb3VyY2VtYW5hZ2VyL3YzL2ZvbGRlcnMucHJv",
"dG8SH2dvb2dsZS5jbG91ZC5yZXNvdXJjZW1hbmFnZXIudjMaHGdvb2dsZS9h",
"cGkvYW5ub3RhdGlvbnMucHJvdG8aF2dvb2dsZS9hcGkvY2xpZW50LnByb3Rv",
"Gh9nb29nbGUvYXBpL2ZpZWxkX2JlaGF2aW9yLnByb3RvGhlnb29nbGUvYXBp",
"L3Jlc291cmNlLnByb3RvGh5nb29nbGUvaWFtL3YxL2lhbV9wb2xpY3kucHJv",
"dG8aGmdvb2dsZS9pYW0vdjEvcG9saWN5LnByb3RvGiNnb29nbGUvbG9uZ3J1",
"bm5pbmcvb3BlcmF0aW9ucy5wcm90bxogZ29vZ2xlL3Byb3RvYnVmL2ZpZWxk",
"X21hc2sucHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90aW1lc3RhbXAucHJvdG8i",
"xgMKBkZvbGRlchIRCgRuYW1lGAEgASgJQgPgQQMSEwoGcGFyZW50GAIgASgJ",
"QgPgQQISFAoMZGlzcGxheV9uYW1lGAMgASgJEkEKBXN0YXRlGAQgASgOMi0u",
"Z29vZ2xlLmNsb3VkLnJlc291cmNlbWFuYWdlci52My5Gb2xkZXIuU3RhdGVC",
"A+BBAxI0CgtjcmVhdGVfdGltZRgFIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5U",
"aW1lc3RhbXBCA+BBAxI0Cgt1cGRhdGVfdGltZRgGIAEoCzIaLmdvb2dsZS5w",
"cm90b2J1Zi5UaW1lc3RhbXBCA+BBAxI0CgtkZWxldGVfdGltZRgHIAEoCzIa",
"Lmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIRCgRldGFnGAggASgJ",
"QgPgQQMiQAoFU3RhdGUSFQoRU1RBVEVfVU5TUEVDSUZJRUQQABIKCgZBQ1RJ",
"VkUQARIUChBERUxFVEVfUkVRVUVTVEVEEAI6ROpBQQoqY2xvdWRyZXNvdXJj",
"ZW1hbmFnZXIuZ29vZ2xlYXBpcy5jb20vRm9sZGVyEhBmb2xkZXJzL3tmb2xk",
"ZXJ9UgEBIlQKEEdldEZvbGRlclJlcXVlc3QSQAoEbmFtZRgBIAEoCUIy4EEC",
"+kEsCipjbG91ZHJlc291cmNlbWFuYWdlci5nb29nbGVhcGlzLmNvbS9Gb2xk",
"ZXIiewoSTGlzdEZvbGRlcnNSZXF1ZXN0EhkKBnBhcmVudBgBIAEoCUIJ4EEC",
"+kEDEgEqEhYKCXBhZ2Vfc2l6ZRgCIAEoBUID4EEBEhcKCnBhZ2VfdG9rZW4Y",
"AyABKAlCA+BBARIZCgxzaG93X2RlbGV0ZWQYBCABKAhCA+BBASJoChNMaXN0",
"Rm9sZGVyc1Jlc3BvbnNlEjgKB2ZvbGRlcnMYASADKAsyJy5nb29nbGUuY2xv",
"dWQucmVzb3VyY2VtYW5hZ2VyLnYzLkZvbGRlchIXCg9uZXh0X3BhZ2VfdG9r",
"ZW4YAiABKAkiWwoUU2VhcmNoRm9sZGVyc1JlcXVlc3QSFgoJcGFnZV9zaXpl",
"GAEgASgFQgPgQQESFwoKcGFnZV90b2tlbhgCIAEoCUID4EEBEhIKBXF1ZXJ5",
"GAMgASgJQgPgQQEiagoVU2VhcmNoRm9sZGVyc1Jlc3BvbnNlEjgKB2ZvbGRl",
"cnMYASADKAsyJy5nb29nbGUuY2xvdWQucmVzb3VyY2VtYW5hZ2VyLnYzLkZv",
"bGRlchIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkiUwoTQ3JlYXRlRm9sZGVy",
"UmVxdWVzdBI8CgZmb2xkZXIYAiABKAsyJy5nb29nbGUuY2xvdWQucmVzb3Vy",
"Y2VtYW5hZ2VyLnYzLkZvbGRlckID4EECIjwKFENyZWF0ZUZvbGRlck1ldGFk",
"YXRhEhQKDGRpc3BsYXlfbmFtZRgBIAEoCRIOCgZwYXJlbnQYAiABKAkiiQEK",
"E1VwZGF0ZUZvbGRlclJlcXVlc3QSPAoGZm9sZGVyGAEgASgLMicuZ29vZ2xl",
"LmNsb3VkLnJlc291cmNlbWFuYWdlci52My5Gb2xkZXJCA+BBAhI0Cgt1cGRh",
"dGVfbWFzaxgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE1hc2tCA+BB",
"AiIWChRVcGRhdGVGb2xkZXJNZXRhZGF0YSJ8ChFNb3ZlRm9sZGVyUmVxdWVz",
"dBJACgRuYW1lGAEgASgJQjLgQQL6QSwKKmNsb3VkcmVzb3VyY2VtYW5hZ2Vy",
"Lmdvb2dsZWFwaXMuY29tL0ZvbGRlchIlChJkZXN0aW5hdGlvbl9wYXJlbnQY",
"AiABKAlCCeBBAvpBAxIBKiJdChJNb3ZlRm9sZGVyTWV0YWRhdGESFAoMZGlz",
"cGxheV9uYW1lGAEgASgJEhUKDXNvdXJjZV9wYXJlbnQYAiABKAkSGgoSZGVz",
"dGluYXRpb25fcGFyZW50GAMgASgJIlcKE0RlbGV0ZUZvbGRlclJlcXVlc3QS",
"QAoEbmFtZRgBIAEoCUIy4EEC+kEsCipjbG91ZHJlc291cmNlbWFuYWdlci5n",
"b29nbGVhcGlzLmNvbS9Gb2xkZXIiFgoURGVsZXRlRm9sZGVyTWV0YWRhdGEi",
"WQoVVW5kZWxldGVGb2xkZXJSZXF1ZXN0EkAKBG5hbWUYASABKAlCMuBBAvpB",
"LAoqY2xvdWRyZXNvdXJjZW1hbmFnZXIuZ29vZ2xlYXBpcy5jb20vRm9sZGVy",
"IhgKFlVuZGVsZXRlRm9sZGVyTWV0YWRhdGEy3g8KB0ZvbGRlcnMSjAEKCUdl",
"dEZvbGRlchIxLmdvb2dsZS5jbG91ZC5yZXNvdXJjZW1hbmFnZXIudjMuR2V0",
"Rm9sZGVyUmVxdWVzdBonLmdvb2dsZS5jbG91ZC5yZXNvdXJjZW1hbmFnZXIu",
"djMuRm9sZGVyIiOC0+STAhYSFC92My97bmFtZT1mb2xkZXJzLyp92kEEbmFt",
"ZRKWAQoLTGlzdEZvbGRlcnMSMy5nb29nbGUuY2xvdWQucmVzb3VyY2VtYW5h",
"Z2VyLnYzLkxpc3RGb2xkZXJzUmVxdWVzdBo0Lmdvb2dsZS5jbG91ZC5yZXNv",
"dXJjZW1hbmFnZXIudjMuTGlzdEZvbGRlcnNSZXNwb25zZSIcgtPkkwINEgsv",
"djMvZm9sZGVyc9pBBnBhcmVudBKiAQoNU2VhcmNoRm9sZGVycxI1Lmdvb2ds",
"ZS5jbG91ZC5yZXNvdXJjZW1hbmFnZXIudjMuU2VhcmNoRm9sZGVyc1JlcXVl",
"c3QaNi5nb29nbGUuY2xvdWQucmVzb3VyY2VtYW5hZ2VyLnYzLlNlYXJjaEZv",
"bGRlcnNSZXNwb25zZSIigtPkkwIUEhIvdjMvZm9sZGVyczpzZWFyY2jaQQVx",
"dWVyeRKqAQoMQ3JlYXRlRm9sZGVyEjQuZ29vZ2xlLmNsb3VkLnJlc291cmNl",
"bWFuYWdlci52My5DcmVhdGVGb2xkZXJSZXF1ZXN0Gh0uZ29vZ2xlLmxvbmdy",
"dW5uaW5nLk9wZXJhdGlvbiJFgtPkkwIVIgsvdjMvZm9sZGVyczoGZm9sZGVy",
"2kEGZm9sZGVyykEeCgZGb2xkZXISFENyZWF0ZUZvbGRlck1ldGFkYXRhEsYB",
"CgxVcGRhdGVGb2xkZXISNC5nb29nbGUuY2xvdWQucmVzb3VyY2VtYW5hZ2Vy",
"LnYzLlVwZGF0ZUZvbGRlclJlcXVlc3QaHS5nb29nbGUubG9uZ3J1bm5pbmcu",
"T3BlcmF0aW9uImGC0+STAiUyGy92My97Zm9sZGVyLm5hbWU9Zm9sZGVycy8q",
"fToGZm9sZGVy2kESZm9sZGVyLHVwZGF0ZV9tYXNrykEeCgZGb2xkZXISFFVw",
"ZGF0ZUZvbGRlck1ldGFkYXRhEr4BCgpNb3ZlRm9sZGVyEjIuZ29vZ2xlLmNs",
"b3VkLnJlc291cmNlbWFuYWdlci52My5Nb3ZlRm9sZGVyUmVxdWVzdBodLmdv",
"b2dsZS5sb25ncnVubmluZy5PcGVyYXRpb24iXYLT5JMCHiIZL3YzL3tuYW1l",
"PWZvbGRlcnMvKn06bW92ZToBKtpBF25hbWUsZGVzdGluYXRpb25fcGFyZW50",
"ykEcCgZGb2xkZXISEk1vdmVGb2xkZXJNZXRhZGF0YRKpAQoMRGVsZXRlRm9s",
"ZGVyEjQuZ29vZ2xlLmNsb3VkLnJlc291cmNlbWFuYWdlci52My5EZWxldGVG",
"b2xkZXJSZXF1ZXN0Gh0uZ29vZ2xlLmxvbmdydW5uaW5nLk9wZXJhdGlvbiJE",
"gtPkkwIWKhQvdjMve25hbWU9Zm9sZGVycy8qfdpBBG5hbWXKQR4KBkZvbGRl",
"chIURGVsZXRlRm9sZGVyTWV0YWRhdGESuwEKDlVuZGVsZXRlRm9sZGVyEjYu",
"Z29vZ2xlLmNsb3VkLnJlc291cmNlbWFuYWdlci52My5VbmRlbGV0ZUZvbGRl",
"clJlcXVlc3QaHS5nb29nbGUubG9uZ3J1bm5pbmcuT3BlcmF0aW9uIlKC0+ST",
"AiIiHS92My97bmFtZT1mb2xkZXJzLyp9OnVuZGVsZXRlOgEq2kEEbmFtZcpB",
"IAoGRm9sZGVyEhZVbmRlbGV0ZUZvbGRlck1ldGFkYXRhEoYBCgxHZXRJYW1Q",
"b2xpY3kSIi5nb29nbGUuaWFtLnYxLkdldElhbVBvbGljeVJlcXVlc3QaFS5n",
"b29nbGUuaWFtLnYxLlBvbGljeSI7gtPkkwIqIiUvdjMve3Jlc291cmNlPWZv",
"bGRlcnMvKn06Z2V0SWFtUG9saWN5OgEq2kEIcmVzb3VyY2USjQEKDFNldElh",
"bVBvbGljeRIiLmdvb2dsZS5pYW0udjEuU2V0SWFtUG9saWN5UmVxdWVzdBoV",
"Lmdvb2dsZS5pYW0udjEuUG9saWN5IkKC0+STAioiJS92My97cmVzb3VyY2U9",
"Zm9sZGVycy8qfTpzZXRJYW1Qb2xpY3k6ASraQQ9yZXNvdXJjZSxwb2xpY3kS",
"uAEKElRlc3RJYW1QZXJtaXNzaW9ucxIoLmdvb2dsZS5pYW0udjEuVGVzdElh",
"bVBlcm1pc3Npb25zUmVxdWVzdBopLmdvb2dsZS5pYW0udjEuVGVzdElhbVBl",
"cm1pc3Npb25zUmVzcG9uc2UiTYLT5JMCMCIrL3YzL3tyZXNvdXJjZT1mb2xk",
"ZXJzLyp9OnRlc3RJYW1QZXJtaXNzaW9uczoBKtpBFHJlc291cmNlLHBlcm1p",
"c3Npb25zGpABykEjY2xvdWRyZXNvdXJjZW1hbmFnZXIuZ29vZ2xlYXBpcy5j",
"b23SQWdodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9hdXRoL2Nsb3VkLXBs",
"YXRmb3JtLGh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvY2xvdWQt",
"cGxhdGZvcm0ucmVhZC1vbmx5Qu4BCiNjb20uZ29vZ2xlLmNsb3VkLnJlc291",
"cmNlbWFuYWdlci52M0IMRm9sZGVyc1Byb3RvUAFaTmdvb2dsZS5nb2xhbmcu",
"b3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xvdWQvcmVzb3VyY2VtYW5hZ2Vy",
"L3YzO3Jlc291cmNlbWFuYWdlcqoCH0dvb2dsZS5DbG91ZC5SZXNvdXJjZU1h",
"bmFnZXIuVjPKAh9Hb29nbGVcQ2xvdWRcUmVzb3VyY2VNYW5hZ2VyXFYz6gIi",
"R29vZ2xlOjpDbG91ZDo6UmVzb3VyY2VNYW5hZ2VyOjpWM2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.ClientReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, global::Google.Cloud.Iam.V1.IamPolicyReflection.Descriptor, global::Google.Cloud.Iam.V1.PolicyReflection.Descriptor, global::Google.LongRunning.OperationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.Folder), global::Google.Cloud.ResourceManager.V3.Folder.Parser, new[]{ "Name", "Parent", "DisplayName", "State", "CreateTime", "UpdateTime", "DeleteTime", "Etag" }, null, new[]{ typeof(global::Google.Cloud.ResourceManager.V3.Folder.Types.State) }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.GetFolderRequest), global::Google.Cloud.ResourceManager.V3.GetFolderRequest.Parser, new[]{ "Name" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.ListFoldersRequest), global::Google.Cloud.ResourceManager.V3.ListFoldersRequest.Parser, new[]{ "Parent", "PageSize", "PageToken", "ShowDeleted" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.ListFoldersResponse), global::Google.Cloud.ResourceManager.V3.ListFoldersResponse.Parser, new[]{ "Folders", "NextPageToken" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.SearchFoldersRequest), global::Google.Cloud.ResourceManager.V3.SearchFoldersRequest.Parser, new[]{ "PageSize", "PageToken", "Query" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.SearchFoldersResponse), global::Google.Cloud.ResourceManager.V3.SearchFoldersResponse.Parser, new[]{ "Folders", "NextPageToken" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.CreateFolderRequest), global::Google.Cloud.ResourceManager.V3.CreateFolderRequest.Parser, new[]{ "Folder" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.CreateFolderMetadata), global::Google.Cloud.ResourceManager.V3.CreateFolderMetadata.Parser, new[]{ "DisplayName", "Parent" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.UpdateFolderRequest), global::Google.Cloud.ResourceManager.V3.UpdateFolderRequest.Parser, new[]{ "Folder", "UpdateMask" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.UpdateFolderMetadata), global::Google.Cloud.ResourceManager.V3.UpdateFolderMetadata.Parser, null, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.MoveFolderRequest), global::Google.Cloud.ResourceManager.V3.MoveFolderRequest.Parser, new[]{ "Name", "DestinationParent" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.MoveFolderMetadata), global::Google.Cloud.ResourceManager.V3.MoveFolderMetadata.Parser, new[]{ "DisplayName", "SourceParent", "DestinationParent" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.DeleteFolderRequest), global::Google.Cloud.ResourceManager.V3.DeleteFolderRequest.Parser, new[]{ "Name" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.DeleteFolderMetadata), global::Google.Cloud.ResourceManager.V3.DeleteFolderMetadata.Parser, null, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.UndeleteFolderRequest), global::Google.Cloud.ResourceManager.V3.UndeleteFolderRequest.Parser, new[]{ "Name" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ResourceManager.V3.UndeleteFolderMetadata), global::Google.Cloud.ResourceManager.V3.UndeleteFolderMetadata.Parser, null, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A folder in an organization's resource hierarchy, used to
/// organize that organization's resources.
/// </summary>
public sealed partial class Folder : pb::IMessage<Folder>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Folder> _parser = new pb::MessageParser<Folder>(() => new Folder());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Folder> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Folder() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Folder(Folder other) : this() {
name_ = other.name_;
parent_ = other.parent_;
displayName_ = other.displayName_;
state_ = other.state_;
createTime_ = other.createTime_ != null ? other.createTime_.Clone() : null;
updateTime_ = other.updateTime_ != null ? other.updateTime_.Clone() : null;
deleteTime_ = other.deleteTime_ != null ? other.deleteTime_.Clone() : null;
etag_ = other.etag_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Folder Clone() {
return new Folder(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Output only. The resource name of the folder.
/// Its format is `folders/{folder_id}`, for example: "folders/1234".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 2;
private string parent_ = "";
/// <summary>
/// Required. The folder's parent's resource name.
/// Updates to the folder's parent must be performed using
/// [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 3;
private string displayName_ = "";
/// <summary>
/// The folder's display name.
/// A folder's display name must be unique amongst its siblings. For example,
/// no two folders with the same parent can share the same display name.
/// The display name must start and end with a letter or digit, may contain
/// letters, digits, spaces, hyphens and underscores and can be no longer
/// than 30 characters. This is captured by the regular expression:
/// `[\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "state" field.</summary>
public const int StateFieldNumber = 4;
private global::Google.Cloud.ResourceManager.V3.Folder.Types.State state_ = global::Google.Cloud.ResourceManager.V3.Folder.Types.State.Unspecified;
/// <summary>
/// Output only. The lifecycle state of the folder.
/// Updates to the state must be performed using
/// [DeleteFolder][google.cloud.resourcemanager.v3.Folders.DeleteFolder] and
/// [UndeleteFolder][google.cloud.resourcemanager.v3.Folders.UndeleteFolder].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.ResourceManager.V3.Folder.Types.State State {
get { return state_; }
set {
state_ = value;
}
}
/// <summary>Field number for the "create_time" field.</summary>
public const int CreateTimeFieldNumber = 5;
private global::Google.Protobuf.WellKnownTypes.Timestamp createTime_;
/// <summary>
/// Output only. Timestamp when the folder was created.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp CreateTime {
get { return createTime_; }
set {
createTime_ = value;
}
}
/// <summary>Field number for the "update_time" field.</summary>
public const int UpdateTimeFieldNumber = 6;
private global::Google.Protobuf.WellKnownTypes.Timestamp updateTime_;
/// <summary>
/// Output only. Timestamp when the folder was last modified.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp UpdateTime {
get { return updateTime_; }
set {
updateTime_ = value;
}
}
/// <summary>Field number for the "delete_time" field.</summary>
public const int DeleteTimeFieldNumber = 7;
private global::Google.Protobuf.WellKnownTypes.Timestamp deleteTime_;
/// <summary>
/// Output only. Timestamp when the folder was requested to be deleted.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Timestamp DeleteTime {
get { return deleteTime_; }
set {
deleteTime_ = value;
}
}
/// <summary>Field number for the "etag" field.</summary>
public const int EtagFieldNumber = 8;
private string etag_ = "";
/// <summary>
/// Output only. A checksum computed by the server based on the current value of the folder
/// resource. This may be sent on update and delete requests to ensure the
/// client has an up-to-date value before proceeding.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Etag {
get { return etag_; }
set {
etag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Folder);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Folder other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Parent != other.Parent) return false;
if (DisplayName != other.DisplayName) return false;
if (State != other.State) return false;
if (!object.Equals(CreateTime, other.CreateTime)) return false;
if (!object.Equals(UpdateTime, other.UpdateTime)) return false;
if (!object.Equals(DeleteTime, other.DeleteTime)) return false;
if (Etag != other.Etag) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (State != global::Google.Cloud.ResourceManager.V3.Folder.Types.State.Unspecified) hash ^= State.GetHashCode();
if (createTime_ != null) hash ^= CreateTime.GetHashCode();
if (updateTime_ != null) hash ^= UpdateTime.GetHashCode();
if (deleteTime_ != null) hash ^= DeleteTime.GetHashCode();
if (Etag.Length != 0) hash ^= Etag.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Parent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Parent);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DisplayName);
}
if (State != global::Google.Cloud.ResourceManager.V3.Folder.Types.State.Unspecified) {
output.WriteRawTag(32);
output.WriteEnum((int) State);
}
if (createTime_ != null) {
output.WriteRawTag(42);
output.WriteMessage(CreateTime);
}
if (updateTime_ != null) {
output.WriteRawTag(50);
output.WriteMessage(UpdateTime);
}
if (deleteTime_ != null) {
output.WriteRawTag(58);
output.WriteMessage(DeleteTime);
}
if (Etag.Length != 0) {
output.WriteRawTag(66);
output.WriteString(Etag);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Parent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Parent);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DisplayName);
}
if (State != global::Google.Cloud.ResourceManager.V3.Folder.Types.State.Unspecified) {
output.WriteRawTag(32);
output.WriteEnum((int) State);
}
if (createTime_ != null) {
output.WriteRawTag(42);
output.WriteMessage(CreateTime);
}
if (updateTime_ != null) {
output.WriteRawTag(50);
output.WriteMessage(UpdateTime);
}
if (deleteTime_ != null) {
output.WriteRawTag(58);
output.WriteMessage(DeleteTime);
}
if (Etag.Length != 0) {
output.WriteRawTag(66);
output.WriteString(Etag);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (State != global::Google.Cloud.ResourceManager.V3.Folder.Types.State.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) State);
}
if (createTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreateTime);
}
if (updateTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTime);
}
if (deleteTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DeleteTime);
}
if (Etag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Etag);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Folder other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
if (other.State != global::Google.Cloud.ResourceManager.V3.Folder.Types.State.Unspecified) {
State = other.State;
}
if (other.createTime_ != null) {
if (createTime_ == null) {
CreateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
CreateTime.MergeFrom(other.CreateTime);
}
if (other.updateTime_ != null) {
if (updateTime_ == null) {
UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
UpdateTime.MergeFrom(other.UpdateTime);
}
if (other.deleteTime_ != null) {
if (deleteTime_ == null) {
DeleteTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
DeleteTime.MergeFrom(other.DeleteTime);
}
if (other.Etag.Length != 0) {
Etag = other.Etag;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Parent = input.ReadString();
break;
}
case 26: {
DisplayName = input.ReadString();
break;
}
case 32: {
State = (global::Google.Cloud.ResourceManager.V3.Folder.Types.State) input.ReadEnum();
break;
}
case 42: {
if (createTime_ == null) {
CreateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(CreateTime);
break;
}
case 50: {
if (updateTime_ == null) {
UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(UpdateTime);
break;
}
case 58: {
if (deleteTime_ == null) {
DeleteTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(DeleteTime);
break;
}
case 66: {
Etag = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Parent = input.ReadString();
break;
}
case 26: {
DisplayName = input.ReadString();
break;
}
case 32: {
State = (global::Google.Cloud.ResourceManager.V3.Folder.Types.State) input.ReadEnum();
break;
}
case 42: {
if (createTime_ == null) {
CreateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(CreateTime);
break;
}
case 50: {
if (updateTime_ == null) {
UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(UpdateTime);
break;
}
case 58: {
if (deleteTime_ == null) {
DeleteTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(DeleteTime);
break;
}
case 66: {
Etag = input.ReadString();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the Folder message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// Folder lifecycle states.
/// </summary>
public enum State {
/// <summary>
/// Unspecified state.
/// </summary>
[pbr::OriginalName("STATE_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The normal and active state.
/// </summary>
[pbr::OriginalName("ACTIVE")] Active = 1,
/// <summary>
/// The folder has been marked for deletion by the user.
/// </summary>
[pbr::OriginalName("DELETE_REQUESTED")] DeleteRequested = 2,
}
}
#endregion
}
/// <summary>
/// The GetFolder request message.
/// </summary>
public sealed partial class GetFolderRequest : pb::IMessage<GetFolderRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<GetFolderRequest> _parser = new pb::MessageParser<GetFolderRequest>(() => new GetFolderRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<GetFolderRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public GetFolderRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public GetFolderRequest(GetFolderRequest other) : this() {
name_ = other.name_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public GetFolderRequest Clone() {
return new GetFolderRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Required. The resource name of the folder to retrieve.
/// Must be of the form `folders/{folder_id}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as GetFolderRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(GetFolderRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(GetFolderRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// The ListFolders request message.
/// </summary>
public sealed partial class ListFoldersRequest : pb::IMessage<ListFoldersRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ListFoldersRequest> _parser = new pb::MessageParser<ListFoldersRequest>(() => new ListFoldersRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<ListFoldersRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ListFoldersRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ListFoldersRequest(ListFoldersRequest other) : this() {
parent_ = other.parent_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
showDeleted_ = other.showDeleted_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ListFoldersRequest Clone() {
return new ListFoldersRequest(this);
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 1;
private string parent_ = "";
/// <summary>
/// Required. The resource name of the organization or folder whose folders are
/// being listed.
/// Must be of the form `folders/{folder_id}` or `organizations/{org_id}`.
/// Access to this method is controlled by checking the
/// `resourcemanager.folders.list` permission on the `parent`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 2;
private int pageSize_;
/// <summary>
/// Optional. The maximum number of folders to return in the response.
/// If unspecified, server picks an appropriate default.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 3;
private string pageToken_ = "";
/// <summary>
/// Optional. A pagination token returned from a previous call to `ListFolders`
/// that indicates where this listing should continue from.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "show_deleted" field.</summary>
public const int ShowDeletedFieldNumber = 4;
private bool showDeleted_;
/// <summary>
/// Optional. Controls whether folders in the
/// [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED]
/// state should be returned. Defaults to false.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool ShowDeleted {
get { return showDeleted_; }
set {
showDeleted_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as ListFoldersRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(ListFoldersRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Parent != other.Parent) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
if (ShowDeleted != other.ShowDeleted) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (ShowDeleted != false) hash ^= ShowDeleted.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (PageSize != 0) {
output.WriteRawTag(16);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(26);
output.WriteString(PageToken);
}
if (ShowDeleted != false) {
output.WriteRawTag(32);
output.WriteBool(ShowDeleted);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (PageSize != 0) {
output.WriteRawTag(16);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(26);
output.WriteString(PageToken);
}
if (ShowDeleted != false) {
output.WriteRawTag(32);
output.WriteBool(ShowDeleted);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (ShowDeleted != false) {
size += 1 + 1;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(ListFoldersRequest other) {
if (other == null) {
return;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
if (other.ShowDeleted != false) {
ShowDeleted = other.ShowDeleted;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Parent = input.ReadString();
break;
}
case 16: {
PageSize = input.ReadInt32();
break;
}
case 26: {
PageToken = input.ReadString();
break;
}
case 32: {
ShowDeleted = input.ReadBool();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Parent = input.ReadString();
break;
}
case 16: {
PageSize = input.ReadInt32();
break;
}
case 26: {
PageToken = input.ReadString();
break;
}
case 32: {
ShowDeleted = input.ReadBool();
break;
}
}
}
}
#endif
}
/// <summary>
/// The ListFolders response message.
/// </summary>
public sealed partial class ListFoldersResponse : pb::IMessage<ListFoldersResponse>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ListFoldersResponse> _parser = new pb::MessageParser<ListFoldersResponse>(() => new ListFoldersResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<ListFoldersResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ListFoldersResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ListFoldersResponse(ListFoldersResponse other) : this() {
folders_ = other.folders_.Clone();
nextPageToken_ = other.nextPageToken_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ListFoldersResponse Clone() {
return new ListFoldersResponse(this);
}
/// <summary>Field number for the "folders" field.</summary>
public const int FoldersFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.ResourceManager.V3.Folder> _repeated_folders_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.ResourceManager.V3.Folder.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.ResourceManager.V3.Folder> folders_ = new pbc::RepeatedField<global::Google.Cloud.ResourceManager.V3.Folder>();
/// <summary>
/// A possibly paginated list of folders that are direct descendants of
/// the specified parent resource.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.ResourceManager.V3.Folder> Folders {
get { return folders_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// A pagination token returned from a previous call to `ListFolders`
/// that indicates from where listing should continue.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as ListFoldersResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(ListFoldersResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!folders_.Equals(other.folders_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
hash ^= folders_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
folders_.WriteTo(output, _repeated_folders_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
folders_.WriteTo(ref output, _repeated_folders_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
size += folders_.CalculateSize(_repeated_folders_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(ListFoldersResponse other) {
if (other == null) {
return;
}
folders_.Add(other.folders_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
folders_.AddEntriesFrom(input, _repeated_folders_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
folders_.AddEntriesFrom(ref input, _repeated_folders_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// The request message for searching folders.
/// </summary>
public sealed partial class SearchFoldersRequest : pb::IMessage<SearchFoldersRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<SearchFoldersRequest> _parser = new pb::MessageParser<SearchFoldersRequest>(() => new SearchFoldersRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<SearchFoldersRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SearchFoldersRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SearchFoldersRequest(SearchFoldersRequest other) : this() {
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
query_ = other.query_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SearchFoldersRequest Clone() {
return new SearchFoldersRequest(this);
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 1;
private int pageSize_;
/// <summary>
/// Optional. The maximum number of folders to return in the response.
/// If unspecified, server picks an appropriate default.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 2;
private string pageToken_ = "";
/// <summary>
/// Optional. A pagination token returned from a previous call to `SearchFolders`
/// that indicates from where search should continue.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "query" field.</summary>
public const int QueryFieldNumber = 3;
private string query_ = "";
/// <summary>
/// Optional. Search criteria used to select the folders to return.
/// If no search criteria is specified then all accessible folders will be
/// returned.
///
/// Query expressions can be used to restrict results based upon displayName,
/// state and parent, where the operators `=` (`:`) `NOT`, `AND` and `OR`
/// can be used along with the suffix wildcard symbol `*`.
///
/// The `displayName` field in a query expression should use escaped quotes
/// for values that include whitespace to prevent unexpected behavior.
///
/// | Field | Description |
/// |-------------------------|----------------------------------------|
/// | displayName | Filters by displayName. |
/// | parent | Filters by parent (for example: folders/123). |
/// | state, lifecycleState | Filters by state. |
///
/// Some example queries are:
///
/// * Query `displayName=Test*` returns Folder resources whose display name
/// starts with "Test".
/// * Query `state=ACTIVE` returns Folder resources with
/// `state` set to `ACTIVE`.
/// * Query `parent=folders/123` returns Folder resources that have
/// `folders/123` as a parent resource.
/// * Query `parent=folders/123 AND state=ACTIVE` returns active
/// Folder resources that have `folders/123` as a parent resource.
/// * Query `displayName=\\"Test String\\"` returns Folder resources with
/// display names that include both "Test" and "String".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Query {
get { return query_; }
set {
query_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as SearchFoldersRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(SearchFoldersRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
if (Query != other.Query) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (PageSize != 0) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (Query.Length != 0) hash ^= Query.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (PageSize != 0) {
output.WriteRawTag(8);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(PageToken);
}
if (Query.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Query);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (PageSize != 0) {
output.WriteRawTag(8);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(PageToken);
}
if (Query.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Query);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (Query.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Query);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(SearchFoldersRequest other) {
if (other == null) {
return;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
if (other.Query.Length != 0) {
Query = other.Query;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
PageSize = input.ReadInt32();
break;
}
case 18: {
PageToken = input.ReadString();
break;
}
case 26: {
Query = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
PageSize = input.ReadInt32();
break;
}
case 18: {
PageToken = input.ReadString();
break;
}
case 26: {
Query = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// The response message for searching folders.
/// </summary>
public sealed partial class SearchFoldersResponse : pb::IMessage<SearchFoldersResponse>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<SearchFoldersResponse> _parser = new pb::MessageParser<SearchFoldersResponse>(() => new SearchFoldersResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<SearchFoldersResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SearchFoldersResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SearchFoldersResponse(SearchFoldersResponse other) : this() {
folders_ = other.folders_.Clone();
nextPageToken_ = other.nextPageToken_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SearchFoldersResponse Clone() {
return new SearchFoldersResponse(this);
}
/// <summary>Field number for the "folders" field.</summary>
public const int FoldersFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.ResourceManager.V3.Folder> _repeated_folders_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.ResourceManager.V3.Folder.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.ResourceManager.V3.Folder> folders_ = new pbc::RepeatedField<global::Google.Cloud.ResourceManager.V3.Folder>();
/// <summary>
/// A possibly paginated folder search results.
/// the specified parent resource.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.ResourceManager.V3.Folder> Folders {
get { return folders_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// A pagination token returned from a previous call to `SearchFolders`
/// that indicates from where searching should continue.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as SearchFoldersResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(SearchFoldersResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!folders_.Equals(other.folders_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
hash ^= folders_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
folders_.WriteTo(output, _repeated_folders_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
folders_.WriteTo(ref output, _repeated_folders_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
size += folders_.CalculateSize(_repeated_folders_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(SearchFoldersResponse other) {
if (other == null) {
return;
}
folders_.Add(other.folders_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
folders_.AddEntriesFrom(input, _repeated_folders_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
folders_.AddEntriesFrom(ref input, _repeated_folders_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// The CreateFolder request message.
/// </summary>
public sealed partial class CreateFolderRequest : pb::IMessage<CreateFolderRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<CreateFolderRequest> _parser = new pb::MessageParser<CreateFolderRequest>(() => new CreateFolderRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<CreateFolderRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CreateFolderRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CreateFolderRequest(CreateFolderRequest other) : this() {
folder_ = other.folder_ != null ? other.folder_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CreateFolderRequest Clone() {
return new CreateFolderRequest(this);
}
/// <summary>Field number for the "folder" field.</summary>
public const int FolderFieldNumber = 2;
private global::Google.Cloud.ResourceManager.V3.Folder folder_;
/// <summary>
/// Required. The folder being created, only the display name and parent will be
/// consulted. All other fields will be ignored.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.ResourceManager.V3.Folder Folder {
get { return folder_; }
set {
folder_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as CreateFolderRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(CreateFolderRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Folder, other.Folder)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (folder_ != null) hash ^= Folder.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (folder_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Folder);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (folder_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Folder);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (folder_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Folder);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(CreateFolderRequest other) {
if (other == null) {
return;
}
if (other.folder_ != null) {
if (folder_ == null) {
Folder = new global::Google.Cloud.ResourceManager.V3.Folder();
}
Folder.MergeFrom(other.Folder);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 18: {
if (folder_ == null) {
Folder = new global::Google.Cloud.ResourceManager.V3.Folder();
}
input.ReadMessage(Folder);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 18: {
if (folder_ == null) {
Folder = new global::Google.Cloud.ResourceManager.V3.Folder();
}
input.ReadMessage(Folder);
break;
}
}
}
}
#endif
}
/// <summary>
/// Metadata pertaining to the Folder creation process.
/// </summary>
public sealed partial class CreateFolderMetadata : pb::IMessage<CreateFolderMetadata>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<CreateFolderMetadata> _parser = new pb::MessageParser<CreateFolderMetadata>(() => new CreateFolderMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<CreateFolderMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CreateFolderMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CreateFolderMetadata(CreateFolderMetadata other) : this() {
displayName_ = other.displayName_;
parent_ = other.parent_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public CreateFolderMetadata Clone() {
return new CreateFolderMetadata(this);
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 1;
private string displayName_ = "";
/// <summary>
/// The display name of the folder.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 2;
private string parent_ = "";
/// <summary>
/// The resource name of the folder or organization we are creating the folder
/// under.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as CreateFolderMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(CreateFolderMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (DisplayName != other.DisplayName) return false;
if (Parent != other.Parent) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (DisplayName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(DisplayName);
}
if (Parent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Parent);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (DisplayName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(DisplayName);
}
if (Parent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Parent);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(CreateFolderMetadata other) {
if (other == null) {
return;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
DisplayName = input.ReadString();
break;
}
case 18: {
Parent = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
DisplayName = input.ReadString();
break;
}
case 18: {
Parent = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// The request sent to the
/// [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder]
/// method.
///
/// Only the `display_name` field can be changed. All other fields will be
/// ignored. Use the
/// [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to
/// change the `parent` field.
/// </summary>
public sealed partial class UpdateFolderRequest : pb::IMessage<UpdateFolderRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<UpdateFolderRequest> _parser = new pb::MessageParser<UpdateFolderRequest>(() => new UpdateFolderRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<UpdateFolderRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UpdateFolderRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UpdateFolderRequest(UpdateFolderRequest other) : this() {
folder_ = other.folder_ != null ? other.folder_.Clone() : null;
updateMask_ = other.updateMask_ != null ? other.updateMask_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UpdateFolderRequest Clone() {
return new UpdateFolderRequest(this);
}
/// <summary>Field number for the "folder" field.</summary>
public const int FolderFieldNumber = 1;
private global::Google.Cloud.ResourceManager.V3.Folder folder_;
/// <summary>
/// Required. The new definition of the Folder. It must include the `name` field, which
/// cannot be changed.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.ResourceManager.V3.Folder Folder {
get { return folder_; }
set {
folder_ = value;
}
}
/// <summary>Field number for the "update_mask" field.</summary>
public const int UpdateMaskFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.FieldMask updateMask_;
/// <summary>
/// Required. Fields to be updated.
/// Only the `display_name` can be updated.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.FieldMask UpdateMask {
get { return updateMask_; }
set {
updateMask_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as UpdateFolderRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(UpdateFolderRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Folder, other.Folder)) return false;
if (!object.Equals(UpdateMask, other.UpdateMask)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (folder_ != null) hash ^= Folder.GetHashCode();
if (updateMask_ != null) hash ^= UpdateMask.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (folder_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Folder);
}
if (updateMask_ != null) {
output.WriteRawTag(18);
output.WriteMessage(UpdateMask);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (folder_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Folder);
}
if (updateMask_ != null) {
output.WriteRawTag(18);
output.WriteMessage(UpdateMask);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (folder_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Folder);
}
if (updateMask_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateMask);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(UpdateFolderRequest other) {
if (other == null) {
return;
}
if (other.folder_ != null) {
if (folder_ == null) {
Folder = new global::Google.Cloud.ResourceManager.V3.Folder();
}
Folder.MergeFrom(other.Folder);
}
if (other.updateMask_ != null) {
if (updateMask_ == null) {
UpdateMask = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
UpdateMask.MergeFrom(other.UpdateMask);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (folder_ == null) {
Folder = new global::Google.Cloud.ResourceManager.V3.Folder();
}
input.ReadMessage(Folder);
break;
}
case 18: {
if (updateMask_ == null) {
UpdateMask = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
input.ReadMessage(UpdateMask);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (folder_ == null) {
Folder = new global::Google.Cloud.ResourceManager.V3.Folder();
}
input.ReadMessage(Folder);
break;
}
case 18: {
if (updateMask_ == null) {
UpdateMask = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
input.ReadMessage(UpdateMask);
break;
}
}
}
}
#endif
}
/// <summary>
/// A status object which is used as the `metadata` field for the Operation
/// returned by UpdateFolder.
/// </summary>
public sealed partial class UpdateFolderMetadata : pb::IMessage<UpdateFolderMetadata>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<UpdateFolderMetadata> _parser = new pb::MessageParser<UpdateFolderMetadata>(() => new UpdateFolderMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<UpdateFolderMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[9]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UpdateFolderMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UpdateFolderMetadata(UpdateFolderMetadata other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UpdateFolderMetadata Clone() {
return new UpdateFolderMetadata(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as UpdateFolderMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(UpdateFolderMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(UpdateFolderMetadata other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
}
/// <summary>
/// The MoveFolder request message.
/// </summary>
public sealed partial class MoveFolderRequest : pb::IMessage<MoveFolderRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<MoveFolderRequest> _parser = new pb::MessageParser<MoveFolderRequest>(() => new MoveFolderRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<MoveFolderRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[10]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public MoveFolderRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public MoveFolderRequest(MoveFolderRequest other) : this() {
name_ = other.name_;
destinationParent_ = other.destinationParent_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public MoveFolderRequest Clone() {
return new MoveFolderRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Required. The resource name of the Folder to move.
/// Must be of the form folders/{folder_id}
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "destination_parent" field.</summary>
public const int DestinationParentFieldNumber = 2;
private string destinationParent_ = "";
/// <summary>
/// Required. The resource name of the folder or organization which should be the
/// folder's new parent.
/// Must be of the form `folders/{folder_id}` or `organizations/{org_id}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DestinationParent {
get { return destinationParent_; }
set {
destinationParent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as MoveFolderRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(MoveFolderRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (DestinationParent != other.DestinationParent) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (DestinationParent.Length != 0) hash ^= DestinationParent.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (DestinationParent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(DestinationParent);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (DestinationParent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(DestinationParent);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (DestinationParent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DestinationParent);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(MoveFolderRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.DestinationParent.Length != 0) {
DestinationParent = other.DestinationParent;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
DestinationParent = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
DestinationParent = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// Metadata pertaining to the folder move process.
/// </summary>
public sealed partial class MoveFolderMetadata : pb::IMessage<MoveFolderMetadata>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<MoveFolderMetadata> _parser = new pb::MessageParser<MoveFolderMetadata>(() => new MoveFolderMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<MoveFolderMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[11]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public MoveFolderMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public MoveFolderMetadata(MoveFolderMetadata other) : this() {
displayName_ = other.displayName_;
sourceParent_ = other.sourceParent_;
destinationParent_ = other.destinationParent_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public MoveFolderMetadata Clone() {
return new MoveFolderMetadata(this);
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 1;
private string displayName_ = "";
/// <summary>
/// The display name of the folder.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "source_parent" field.</summary>
public const int SourceParentFieldNumber = 2;
private string sourceParent_ = "";
/// <summary>
/// The resource name of the folder's parent.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string SourceParent {
get { return sourceParent_; }
set {
sourceParent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "destination_parent" field.</summary>
public const int DestinationParentFieldNumber = 3;
private string destinationParent_ = "";
/// <summary>
/// The resource name of the folder or organization to move the folder to.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DestinationParent {
get { return destinationParent_; }
set {
destinationParent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as MoveFolderMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(MoveFolderMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (DisplayName != other.DisplayName) return false;
if (SourceParent != other.SourceParent) return false;
if (DestinationParent != other.DestinationParent) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (SourceParent.Length != 0) hash ^= SourceParent.GetHashCode();
if (DestinationParent.Length != 0) hash ^= DestinationParent.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (DisplayName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(DisplayName);
}
if (SourceParent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(SourceParent);
}
if (DestinationParent.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DestinationParent);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (DisplayName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(DisplayName);
}
if (SourceParent.Length != 0) {
output.WriteRawTag(18);
output.WriteString(SourceParent);
}
if (DestinationParent.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DestinationParent);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (SourceParent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceParent);
}
if (DestinationParent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DestinationParent);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(MoveFolderMetadata other) {
if (other == null) {
return;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
if (other.SourceParent.Length != 0) {
SourceParent = other.SourceParent;
}
if (other.DestinationParent.Length != 0) {
DestinationParent = other.DestinationParent;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
DisplayName = input.ReadString();
break;
}
case 18: {
SourceParent = input.ReadString();
break;
}
case 26: {
DestinationParent = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
DisplayName = input.ReadString();
break;
}
case 18: {
SourceParent = input.ReadString();
break;
}
case 26: {
DestinationParent = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// The DeleteFolder request message.
/// </summary>
public sealed partial class DeleteFolderRequest : pb::IMessage<DeleteFolderRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<DeleteFolderRequest> _parser = new pb::MessageParser<DeleteFolderRequest>(() => new DeleteFolderRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<DeleteFolderRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[12]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DeleteFolderRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DeleteFolderRequest(DeleteFolderRequest other) : this() {
name_ = other.name_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DeleteFolderRequest Clone() {
return new DeleteFolderRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Required. The resource name of the folder to be deleted.
/// Must be of the form `folders/{folder_id}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as DeleteFolderRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(DeleteFolderRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(DeleteFolderRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// A status object which is used as the `metadata` field for the `Operation`
/// returned by `DeleteFolder`.
/// </summary>
public sealed partial class DeleteFolderMetadata : pb::IMessage<DeleteFolderMetadata>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<DeleteFolderMetadata> _parser = new pb::MessageParser<DeleteFolderMetadata>(() => new DeleteFolderMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<DeleteFolderMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[13]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DeleteFolderMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DeleteFolderMetadata(DeleteFolderMetadata other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DeleteFolderMetadata Clone() {
return new DeleteFolderMetadata(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as DeleteFolderMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(DeleteFolderMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(DeleteFolderMetadata other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
}
/// <summary>
/// The UndeleteFolder request message.
/// </summary>
public sealed partial class UndeleteFolderRequest : pb::IMessage<UndeleteFolderRequest>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<UndeleteFolderRequest> _parser = new pb::MessageParser<UndeleteFolderRequest>(() => new UndeleteFolderRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<UndeleteFolderRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[14]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UndeleteFolderRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UndeleteFolderRequest(UndeleteFolderRequest other) : this() {
name_ = other.name_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UndeleteFolderRequest Clone() {
return new UndeleteFolderRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Required. The resource name of the folder to undelete.
/// Must be of the form `folders/{folder_id}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as UndeleteFolderRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(UndeleteFolderRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(UndeleteFolderRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// A status object which is used as the `metadata` field for the `Operation`
/// returned by `UndeleteFolder`.
/// </summary>
public sealed partial class UndeleteFolderMetadata : pb::IMessage<UndeleteFolderMetadata>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<UndeleteFolderMetadata> _parser = new pb::MessageParser<UndeleteFolderMetadata>(() => new UndeleteFolderMetadata());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<UndeleteFolderMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ResourceManager.V3.FoldersReflection.Descriptor.MessageTypes[15]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UndeleteFolderMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UndeleteFolderMetadata(UndeleteFolderMetadata other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public UndeleteFolderMetadata Clone() {
return new UndeleteFolderMetadata(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as UndeleteFolderMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(UndeleteFolderMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(UndeleteFolderMetadata other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| 37.567301 | 565 | 0.669463 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/resourcemanager/v3/google-cloud-resourcemanager-v3-csharp/Google.Cloud.ResourceManager.V3/Folders.g.cs | 152,110 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using HotChocolate.Types;
namespace HotChocolate.Stitching.Schemas.Contracts
{
public class LifeInsuranceContractType : ObjectType<LifeInsuranceContract>
{
protected override void Configure(
IObjectTypeDescriptor<LifeInsuranceContract> descriptor)
{
descriptor
.AsNode()
.IdField(t => t.Id)
.NodeResolver((ctx, id) =>
{
return Task.FromResult(
ctx.Service<ContractStorage>()
.Contracts
.OfType<LifeInsuranceContract>()
.FirstOrDefault(t => t.Id.Equals(id)));
});
descriptor.Interface<ContractType>();
descriptor.Field(t => t.Id).Type<NonNullType<IdType>>();
descriptor.Field(t => t.CustomerId).Type<NonNullType<IdType>>();
descriptor.Field("foo")
.Argument("bar", a => a.Type<StringType>())
.Resolver(ctx => ctx.ArgumentValue<string>("bar"));
descriptor.Field("error")
.Type<StringType>()
.Resolver(ctx => ErrorBuilder.New()
.SetMessage("Error_Message")
.SetCode("ERROR_CODE")
.SetPath(ctx.Path)
.Build());
descriptor.Field("date_field")
.Type<DateType>()
.Resolver(new DateTime(2018, 5, 17));
descriptor.Field("date_time_field")
.Type<DateTimeType>()
.Resolver(new DateTime(
2018, 5, 17, 8, 59, 0,
DateTimeKind.Utc));
descriptor.Field("string_field")
.Type<StringType>()
.Resolver("abc");
descriptor.Field("id_field")
.Type<IdType>()
.Resolver("abc_123");
descriptor.Field("byte_field")
.Type<ByteType>()
.Resolver(123);
descriptor.Field("int_field")
.Type<IntType>()
.Resolver(123);
descriptor.Field("long_field")
.Type<LongType>()
.Resolver(123);
descriptor.Field("float_field")
.Type<FloatType>()
.Argument("f", a => a.Type<FloatType>())
.Resolve(ctx => ctx.ArgumentValue<double?>("f") ?? 123.123);
descriptor.Field("decimal_field")
.Type<DecimalType>()
.Resolver(123.123);
}
}
}
| 37.647887 | 78 | 0.483726 | [
"MIT"
] | Asshiah/hotchocolate | src/HotChocolate/Stitching/test/Stitching.Tests/Schemas/Contracts/LifeInsuranceContractType.cs | 2,673 | C# |
using FGD.Bussines.Model;
using FGD.Configuration;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FGD.Data.Service
{
public class AccountSubscriptionRepository : IAccountSubscriptionRepository<AccountSubscriptionModelBussines<int>, int>
{
private FakeGoogleDriveContext _context;
public AccountSubscriptionRepository(FakeGoogleDriveContext context)
{
_context = context;
}
public async Task<AccountSubscriptionModelBussines<int>> CreateAsync(AccountSubscriptionModelBussines<int> model)
{
var res = await _context.AccountSubscriptions.AddAsync(
AutoMapperConfig.Mapper.Map<AccountSubscriptionModel<int>>(model)
);
await _context.SaveChangesAsync();
return await GetByUserIdAsync(res.Entity.AccountId);
}
[Obsolete]
public Task<bool> DeleteByIdAsync(int id)
{
throw new NotImplementedException();
}
public async Task<ICollection<AccountSubscriptionModelBussines<int>>> GetAllAsync()
{
return AutoMapperConfig.Mapper.Map<List<AccountSubscriptionModelBussines<int>>>(
await _context.AccountSubscriptions.ToListAsync()
);
}
[Obsolete]
public Task<AccountSubscriptionModelBussines<int>> GetByIdAsync(int id)
{
throw new NotImplementedException();
}
public async Task<AccountSubscriptionModelBussines<int>> GetByUserIdAsync(int id)
{
var raw = await GetRawByUserIdAsync(id);
return AutoMapperConfig.Mapper.Map<AccountSubscriptionModelBussines<int>>(raw);
}
public async Task<AccountSubscriptionModelBussines<int>> GetByUserEmailAsync(string email)
{
var user = await _context.Accounts.FirstOrDefaultAsync(a => a.Email == email);
var raw = await _context.AccountSubscriptions.FirstOrDefaultAsync(a => a.AccountId == user.Id);
return AutoMapperConfig.Mapper.Map<AccountSubscriptionModelBussines<int>>(raw);
}
public async Task<AccountSubscriptionModelBussines<int>> UpdateAsync(int id, AccountSubscriptionModelBussines<int> model)
{
var accSubb = await GetRawByUserIdAsync(model.AccountId);
accSubb.IsActive = model.IsActive;
accSubb.TakenSpace = model.TakenSpace;
_context.AccountSubscriptions.Update(accSubb);
await _context.SaveChangesAsync();
return await GetByUserIdAsync(accSubb.AccountId);
}
internal async Task<AccountSubscriptionModel<int>> GetRawByUserIdAsync(int id)
{
return await _context.AccountSubscriptions.FirstOrDefaultAsync(a => a.AccountId == id);
}
}
}
| 33.825581 | 129 | 0.669302 | [
"MIT"
] | VladyslavYakymenkoCom/Fake-Google-Drive | FGD.Data.Service/Implementation/AccountSubscriptionRepository.cs | 2,911 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461)
// Version 5.461.0.0 www.ComponentFactory.com
// *****************************************************************************
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Storage for palette ribbon group button text states.
/// </summary>
public class KryptonPaletteRibbonGroupButtonText : KryptonPaletteRibbonGroupBaseText
{
#region Identity
/// <summary>
/// Initialize a new instance of the KryptonPaletteRibbonGroupButtonText class.
/// </summary>
/// <param name="redirect">Redirector to inherit values from.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public KryptonPaletteRibbonGroupButtonText(PaletteRedirect redirect,
NeedPaintHandler needPaint)
: base(redirect, PaletteRibbonTextStyle.RibbonGroupButtonText, needPaint)
{
}
#endregion
}
}
| 48.69697 | 157 | 0.617922 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.461 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Component/KryptonPaletteRibbonGroupButtonText.cs | 1,610 | C# |
/*
Copyright 2019 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
namespace EditingSampleApp
{
public partial class EditingForm : Form
{
#region class private members
private IToolbarMenu m_toolbarMenu;
private IEngineEditSketch m_engineEditor;
#endregion
public EditingForm()
{
InitializeComponent();
}
private void EngineEditingForm_Load(object sender, EventArgs e)
{
//Set buddy controls
axTOCControl1.SetBuddyControl(axMapControl1);
axEditorToolbar.SetBuddyControl(axMapControl1);
axToolbarControl1.SetBuddyControl(axMapControl1);
//Add items to the ToolbarControl
axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapPanTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentBackCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentForwardCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
//Add items to the custom editor toolbar
axEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axEditorToolbar.AddItem("VertexCommands_CS.VertexCommandsMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconAndText);
axEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
axEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
axEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
axEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
//Create a popup menu
m_toolbarMenu = new ToolbarMenuClass();
m_toolbarMenu.AddItem("esriControls.ControlsEditingSketchContextMenu", 0, 0, false, esriCommandStyles.esriCommandStyleTextOnly);
m_engineEditor = new EngineEditorClass() as IEngineEditSketch; //this class is a singleton
//share the command pool
axToolbarControl1.CommandPool = axEditorToolbar.CommandPool;
m_toolbarMenu.CommandPool = axToolbarControl1.CommandPool;
//Create an operation stack for the undo and redo commands to use
IOperationStack operationStack = new ControlsOperationStackClass();
axEditorToolbar.OperationStack = operationStack;
//add some sample line data to the map
IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
//relative file path to the sample data from EXE location
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filePath = System.IO.Path.Combine(filePath, @"ArcGIS\data\USAMajorHighways");
IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd);
IFeatureLayer featureLayer = new FeatureLayerClass();
featureLayer.Name = "Highways";
featureLayer.Visible = true;
featureLayer.FeatureClass = workspace.OpenFeatureClass("usa_major_highways");
axMapControl1.Map.AddLayer((ILayer)featureLayer);
}
private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
if (e.button == 2)
{
m_toolbarMenu.PopupMenu(e.x, e.y, axMapControl1.hWnd);
}
}
}
} | 48.934959 | 157 | 0.712743 | [
"Apache-2.0"
] | Esri/arcobjects-sdk-community-samples | Net/Controls/EditingVertexCommands/CSharp/Application/EditingForm.cs | 6,019 | C# |
using Data;
using DesafioFULL.Domain.Interfaces.Repositorys;
using DesafioFULL.Domain.Models;
using System.Collections.Generic;
using System.Linq;
namespace DesafioFULL.Data.Repository
{
public class RepositoryParcela : RepositoryBase<Parcela>, IRepositoryParcela
{
private readonly SqlContext _context;
public RepositoryParcela(SqlContext Context)
: base(Context)
{
_context = Context;
}
public void RemoveByTitulo(int titulo)
{
try
{
IEnumerable<Parcela> parcelas = GetAll().Where(x => x.Titulo == titulo);
if (parcelas.Count() > 0)
{
foreach (Parcela parcela in parcelas)
_context.Set<Parcela>().Remove(parcela);
_context.SaveChanges();
}
}
catch
{
throw;
}
}
}
}
| 25.763158 | 88 | 0.529111 | [
"MIT"
] | t-tozatto/DesafioFULL | api/Data/Repository/RepositoryParcela.cs | 981 | C# |
using System;
namespace LibVLCSharp.Shared
{
internal class MediaEventManager : EventManager
{
readonly object _lock = new object();
#if IOS
static EventHandler<MediaMetaChangedEventArgs> _mediaMetaChanged;
static EventHandler<MediaParsedChangedEventArgs> _mediaParsedChanged;
static EventHandler<MediaSubItemAddedEventArgs> _mediaSubItemAdded;
static EventHandler<MediaDurationChangedEventArgs> _mediaDurationChanged;
static EventHandler<MediaFreedEventArgs> _mediaFreed;
static EventHandler<MediaStateChangedEventArgs> _mediaStateChanged;
static EventHandler<MediaSubItemTreeAddedEventArgs> _mediaSubItemTreeAdded;
#else
EventHandler<MediaMetaChangedEventArgs> _mediaMetaChanged;
EventHandler<MediaParsedChangedEventArgs> _mediaParsedChanged;
EventHandler<MediaSubItemAddedEventArgs> _mediaSubItemAdded;
EventHandler<MediaDurationChangedEventArgs> _mediaDurationChanged;
EventHandler<MediaFreedEventArgs> _mediaFreed;
EventHandler<MediaStateChangedEventArgs> _mediaStateChanged;
EventHandler<MediaSubItemTreeAddedEventArgs> _mediaSubItemTreeAdded;
#endif
int _mediaMetaChangedRegistrationCount;
int _mediaParsedChangedRegistrationCount;
int _mediaSubItemChangedRegistrationCount;
int _mediaDurationChangedRegistrationCount;
int _mediaFreedRegistrationCount;
int _mediaStateChangedRegistrationCount;
int _mediaSubitemTreeAddedRegistrationCount;
EventCallback _mediaMetaChangedCallback;
EventCallback _mediaParsedChangedCallback;
EventCallback _mediaSubItemChangedCallback;
EventCallback _mediaDurationChangedCallback;
EventCallback _mediaFreedCallback;
EventCallback _mediaStateChangedCallback;
EventCallback _mediaSubitemTreeAddedCallback;
public MediaEventManager(IntPtr ptr) : base(ptr)
{
}
protected internal override void AttachEvent<T>(EventType eventType, EventHandler<T> eventHandler)
{
lock(_lock)
{
switch (eventType)
{
case EventType.MediaMetaChanged:
Attach(eventType,
ref _mediaMetaChangedRegistrationCount,
() => _mediaMetaChanged += eventHandler as EventHandler<MediaMetaChangedEventArgs>,
() => _mediaMetaChangedCallback = OnMetaChanged);
break;
case EventType.MediaParsedChanged:
Attach(eventType,
ref _mediaParsedChangedRegistrationCount,
() => _mediaParsedChanged += eventHandler as EventHandler<MediaParsedChangedEventArgs>,
() => _mediaParsedChangedCallback = OnParsedChanged);
break;
case EventType.MediaSubItemAdded:
Attach(eventType,
ref _mediaSubItemChangedRegistrationCount,
() => _mediaSubItemAdded += eventHandler as EventHandler<MediaSubItemAddedEventArgs>,
() => _mediaSubItemChangedCallback = OnSubItemAdded);
break;
case EventType.MediaDurationChanged:
Attach(eventType,
ref _mediaDurationChangedRegistrationCount,
() => _mediaDurationChanged += eventHandler as EventHandler<MediaDurationChangedEventArgs>,
() => _mediaDurationChangedCallback = OnDurationChanged);
break;
case EventType.MediaFreed:
Attach(eventType,
ref _mediaFreedRegistrationCount,
() => _mediaFreed += eventHandler as EventHandler<MediaFreedEventArgs>,
() => _mediaFreedCallback = OnMediaFreed);
break;
case EventType.MediaStateChanged:
Attach(eventType,
ref _mediaStateChangedRegistrationCount,
() => _mediaStateChanged += eventHandler as EventHandler<MediaStateChangedEventArgs>,
() => _mediaStateChangedCallback = OnMediaStateChanged);
break;
case EventType.MediaSubItemTreeAdded:
Attach(eventType,
ref _mediaSubitemTreeAddedRegistrationCount,
() => _mediaSubItemTreeAdded += eventHandler as EventHandler<MediaSubItemTreeAddedEventArgs>,
() => _mediaSubitemTreeAddedCallback = OnSubItemTreeAdded);
break;
default:
OnEventUnhandled(this, eventType);
break;
}
}
}
protected internal override void DetachEvent<T>(EventType eventType, EventHandler<T> eventHandler)
{
lock (_lock)
{
switch (eventType)
{
case EventType.MediaMetaChanged:
Detach(eventType,
ref _mediaMetaChangedRegistrationCount,
() => _mediaMetaChanged -= eventHandler as EventHandler<MediaMetaChangedEventArgs>,
ref _mediaMetaChangedCallback);
break;
case EventType.MediaParsedChanged:
Detach(eventType,
ref _mediaParsedChangedRegistrationCount,
() => _mediaParsedChanged -= eventHandler as EventHandler<MediaParsedChangedEventArgs>,
ref _mediaParsedChangedCallback);
break;
case EventType.MediaSubItemAdded:
Detach(eventType,
ref _mediaSubItemChangedRegistrationCount,
() => _mediaSubItemAdded -= eventHandler as EventHandler<MediaSubItemAddedEventArgs>,
ref _mediaSubItemChangedCallback);
break;
case EventType.MediaDurationChanged:
Detach(eventType,
ref _mediaDurationChangedRegistrationCount,
() => _mediaDurationChanged -= eventHandler as EventHandler<MediaDurationChangedEventArgs>,
ref _mediaDurationChangedCallback);
break;
case EventType.MediaFreed:
Detach(eventType,
ref _mediaFreedRegistrationCount,
() => _mediaFreed -= eventHandler as EventHandler<MediaFreedEventArgs>,
ref _mediaFreedCallback);
break;
case EventType.MediaStateChanged:
Detach(eventType,
ref _mediaStateChangedRegistrationCount,
() => _mediaStateChanged -= eventHandler as EventHandler<MediaStateChangedEventArgs>,
ref _mediaStateChangedCallback);
break;
case EventType.MediaSubItemTreeAdded:
Detach(eventType,
ref _mediaSubitemTreeAddedRegistrationCount,
() => _mediaSubItemTreeAdded -= eventHandler as EventHandler<MediaSubItemTreeAddedEventArgs>,
ref _mediaSubitemTreeAddedCallback);
break;
default:
OnEventUnhandled(this, eventType);
break;
}
}
}
#if IOS
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnSubItemTreeAdded(IntPtr ptr)
{
_mediaSubItemTreeAdded?.Invoke(null,
new MediaSubItemTreeAddedEventArgs(RetrieveEvent(ptr).Union.MediaSubItemTreeAdded.MediaInstance));
}
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnMediaStateChanged(IntPtr ptr)
{
_mediaStateChanged?.Invoke(null,
new MediaStateChangedEventArgs(RetrieveEvent(ptr).Union.MediaStateChanged.NewState));
}
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnMediaFreed(IntPtr ptr)
{
_mediaFreed?.Invoke(null, new MediaFreedEventArgs(RetrieveEvent(ptr).Union.MediaFreed.MediaInstance));
}
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnDurationChanged(IntPtr ptr)
{
_mediaDurationChanged?.Invoke(null,
new MediaDurationChangedEventArgs(RetrieveEvent(ptr).Union.MediaDurationChanged.NewDuration));
}
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnSubItemAdded(IntPtr ptr)
{
_mediaSubItemAdded?.Invoke(null,
new MediaSubItemAddedEventArgs(RetrieveEvent(ptr).Union.MediaSubItemAdded.NewChild));
}
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnParsedChanged(IntPtr ptr)
{
_mediaParsedChanged?.Invoke(null,
new MediaParsedChangedEventArgs(RetrieveEvent(ptr).Union.MediaParsedChanged.NewStatus));
}
[MonoPInvokeCallback(typeof(EventCallback))]
static void OnMetaChanged(IntPtr ptr)
{
_mediaMetaChanged?.Invoke(null,
new MediaMetaChangedEventArgs(RetrieveEvent(ptr).Union.MediaMetaChanged.MetaType));
}
#else
void OnSubItemTreeAdded(IntPtr ptr)
{
_mediaSubItemTreeAdded?.Invoke(this,
new MediaSubItemTreeAddedEventArgs(RetrieveEvent(ptr).Union.MediaSubItemTreeAdded.MediaInstance));
}
void OnMediaStateChanged(IntPtr ptr)
{
_mediaStateChanged?.Invoke(this,
new MediaStateChangedEventArgs(RetrieveEvent(ptr).Union.MediaStateChanged.NewState));
}
void OnMediaFreed(IntPtr ptr)
{
_mediaFreed?.Invoke(this, new MediaFreedEventArgs(RetrieveEvent(ptr).Union.MediaFreed.MediaInstance));
}
void OnDurationChanged(IntPtr ptr)
{
_mediaDurationChanged?.Invoke(this,
new MediaDurationChangedEventArgs(RetrieveEvent(ptr).Union.MediaDurationChanged.NewDuration));
}
void OnSubItemAdded(IntPtr ptr)
{
_mediaSubItemAdded?.Invoke(this,
new MediaSubItemAddedEventArgs(RetrieveEvent(ptr).Union.MediaSubItemAdded.NewChild));
}
void OnParsedChanged(IntPtr ptr)
{
_mediaParsedChanged?.Invoke(this,
new MediaParsedChangedEventArgs(RetrieveEvent(ptr).Union.MediaParsedChanged.NewStatus));
}
void OnMetaChanged(IntPtr ptr)
{
_mediaMetaChanged?.Invoke(this,
new MediaMetaChangedEventArgs(RetrieveEvent(ptr).Union.MediaMetaChanged.MetaType));
}
#endif
}
} | 46.384615 | 121 | 0.587414 | [
"Unlicense"
] | 944095635/DMSkin-Wallpaper-Maker | Wallpaper.Maker/LibVLCSharp/Shared/Events/MediaEventManager.cs | 11,459 | C# |
using System.Threading;
using Android.AccessibilityServices;
using Android.Graphics;
using CoreAutomata;
namespace FateGrandAutomata
{
public class AccessibilityGestureService : IGestureService
{
AccessibilityService _accessibilityService;
readonly ManualResetEventSlim _gestureWaitHandle = new ManualResetEventSlim();
public AccessibilityGestureService(AccessibilityService AccessibilityService)
{
_accessibilityService = AccessibilityService;
}
public void Swipe(Location Start, Location End)
{
var swipePath = new Path();
swipePath.MoveTo(Start.X, Start.Y);
swipePath.LineTo(End.X, End.Y);
var swipeStroke = new GestureDescription.StrokeDescription(swipePath, 0, GestureTimings.SwipeDurationMs);
PerformGesture(swipeStroke);
AutomataApi.Wait(GestureTimings.SwipeWaitTimeSec);
}
public void Click(Location Location)
{
ContinueClick(Location, 1);
}
public void ContinueClick(Location Location, int Times)
{
while (Times-- > 0)
{
var swipePath = new Path();
swipePath.MoveTo(Location.X, Location.Y);
var stroke = new GestureDescription.StrokeDescription(swipePath, GestureTimings.ClickDelayMs, GestureTimings.ClickDurationMs);
PerformGesture(stroke);
}
AutomataApi.Wait(GestureTimings.ClickWaitTimeSec);
}
void PerformGesture(GestureDescription.StrokeDescription StrokeDescription)
{
_gestureWaitHandle.Reset();
var gestureBuilder = new GestureDescription.Builder();
gestureBuilder.AddStroke(StrokeDescription);
_accessibilityService.DispatchGesture(gestureBuilder.Build(), new GestureCompletedCallback(_gestureWaitHandle), null);
_gestureWaitHandle.Wait();
}
public void Dispose()
{
_accessibilityService = null;
}
}
}
| 31.727273 | 142 | 0.643266 | [
"MIT"
] | echoscrip/Fate-Grand-Automata | FateGrandAutomata/Gestures/AccessibilityGestureService.cs | 2,096 | C# |
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
using System;
using Windows.Storage;
namespace FileAccess
{
class Scenario5_CreateMultiLevelFolders
{
public static void Execute(StorageFolder device)
{
Console.WriteLine($"== Scenario5_CreateMultiLevelFolders ==");
// Create multi level folders on device
// D:\\Folder11\Folder21
// \Folder22\Folder31
// Create folder on 1st Removalable Drive (D:\)
StorageFolder Folder11 = CreateFolderHelper(device, "Folder11", CreationCollisionOption.ReplaceExisting);
// Create 1st folder within Folder11
StorageFolder Folder21 = CreateFolderHelper(Folder11, "Folder21", CreationCollisionOption.ReplaceExisting);
// Create 2nd folder within Folder11
StorageFolder Folder22 = CreateFolderHelper(Folder11, "Folder22", CreationCollisionOption.ReplaceExisting);
// Create folder within Folder22
StorageFolder Folder31 = CreateFolderHelper(Folder22, "Folder31", CreationCollisionOption.ReplaceExisting);
Console.WriteLine($"OK: Successfully created all multi level folders");
}
/// <summary>
/// Helper method to create a Folder at a specific location
/// </summary>
/// <param name="location">Location to create folder</param>
/// <param name="folderName">Folder name to create</param>
/// <returns></returns>
static StorageFolder CreateFolderHelper(StorageFolder location, String folderName, CreationCollisionOption option)
{
StorageFolder folderNew = null;
try
{
// create a folder (failing if there is already one with this name)
folderNew = location.CreateFolder(folderName, option);
Console.WriteLine($"OK: Successfully created folder: {folderNew.Path}");
}
catch (Exception )
{
Console.WriteLine($"ERROR: Can't create the folder as it already exists.");
}
return folderNew;
}
}
}
| 36.258065 | 122 | 0.627224 | [
"MIT"
] | fluent-software/Samples | samples/Storage/FileAccess/Scenario5_CreateMultiLevelFolders.cs | 2,250 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NPC.Runtime
{
public class NeoTrace /* Level *all* */
{
public static void Trace(params object[] args)
{
Neo.SmartContract.Framework.Services.Neo.Runtime.Notify(args);
}
}
}
| 20.588235 | 74 | 0.66 | [
"MIT"
] | mwherman2000/neo-npcc | neo-npcc/PartialClassTest1/NeoTrace.cs | 352 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nucleus.Gaming.Windows.Interop
{
public static class User32_WS
{
/*GWL_ID = (-12)
GWL_STYLE = (-16)
GWL_EXSTYLE = (-20)*/
public const int GWL_EXSTYLE = -20;
public const int GWLP_HINSTANCE = -6;
public const int GWLP_HWNDPARENT = -8;
public const int GWL_ID = -12;
public const int GWL_STYLE = -16;
public const int GWL_USERDATA = -21;
public const int GWL_WNDPROC = -4;
public const int DWLP_USER = 0x8;
public const int DWLP_MSGRESULT = 0x0;
public const int DWLP_DLGPROC = 0x4;
public const int WM_COMMAND = 0x111;
public const int MIN_ALL = 419;
public const int MIN_ALL_UNDO = 416;
public const UInt32 HT_CAPTION = 0x2;
//laziness, don't want to search for the ones I don't use XD
// Window Styles
public const UInt32 WS_OVERLAPPED = 0;
public const UInt32 WS_POPUP = 0x80000000;
public const UInt32 WS_CHILD = 0x40000000;
public const UInt32 WS_MINIMIZE = 0x20000000;
public const UInt32 WS_VISIBLE = 0x10000000;
public const UInt32 WS_DISABLED = 0x8000000;
public const UInt32 WS_CLIPSIBLINGS = 0x4000000;
public const UInt32 WS_CLIPCHILDREN = 0x2000000;
public const UInt32 WS_MAXIMIZE = 0x1000000;
public const UInt32 WS_CAPTION = 0xC00000; // WS_BORDER or WS_DLGFRAME
public const UInt32 WS_BORDER = 0x800000;
public const UInt32 WS_DLGFRAME = 0x400000;
public const UInt32 WS_VSCROLL = 0x200000;
public const UInt32 WS_HSCROLL = 0x100000;
public const UInt32 WS_SYSMENU = 0x80000;
public const UInt32 WS_THICKFRAME = 0x40000;
public const UInt32 WS_GROUP = 0x20000;
public const UInt32 WS_TABSTOP = 0x10000;
public const UInt32 WS_MINIMIZEBOX = 0x20000;
public const UInt32 WS_MAXIMIZEBOX = 0x10000;
public const UInt32 WS_TILED = WS_OVERLAPPED;
public const UInt32 WS_ICONIC = WS_MINIMIZE;
public const UInt32 WS_SIZEBOX = WS_THICKFRAME;
public const UInt32 WM_NCLBUTTONDOWN = 0xA1;
// Extended Window Styles
public const UInt32 WS_EX_DLGMODALFRAME = 0x0001;
public const UInt32 WS_EX_NOPARENTNOTIFY = 0x0004;
public const UInt32 WS_EX_TOPMOST = 0x0008;
public const UInt32 WS_EX_ACCEPTFILES = 0x0010;
public const UInt32 WS_EX_TRANSPARENT = 0x0020;
public const UInt32 WS_EX_MDICHILD = 0x0040;
public const UInt32 WS_EX_TOOLWINDOW = 0x0080;
public const UInt32 WS_EX_WINDOWEDGE = 0x0100;
public const UInt32 WS_EX_CLIENTEDGE = 0x0200;
public const UInt32 WS_EX_CONTEXTHELP = 0x0400;
public const UInt32 WS_EX_RIGHT = 0x1000;
public const UInt32 WS_EX_LEFT = 0x0000;
public const UInt32 WS_EX_RTLREADING = 0x2000;
public const UInt32 WS_EX_LTRREADING = 0x0000;
public const UInt32 WS_EX_LEFTSCROLLBAR = 0x4000;
public const UInt32 WS_EX_RIGHTSCROLLBAR = 0x0000;
public const UInt32 WS_EX_CONTROLPARENT = 0x10000;
public const UInt32 WS_EX_STATICEDGE = 0x20000;
public const UInt32 WS_EX_APPWINDOW = 0x40000;
public const UInt32 WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);
public const UInt32 WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST);
public const UInt32 WS_EX_LAYERED = 0x00080000;
public const UInt32 WS_EX_NOINHERITLAYOUT = 0x00100000; // Disable inheritence of mirroring by children
public const UInt32 WS_EX_LAYOUTRTL = 0x00400000; // Right to left mirroring
public const UInt32 WS_EX_COMPOSITED = 0x02000000;
public const UInt32 WS_EX_NOACTIVATE = 0x08000000;
}
}
| 44.568182 | 111 | 0.686639 | [
"MIT"
] | jackxriot/nucleuscoop | Master/Nucleus.Gaming/Platform/Windows/Interop/User32/User32_WS.cs | 3,924 | C# |
namespace Xilium.CefGlue;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Class used to implement render process callbacks. The methods of this class
/// will be called on the render process main thread (TID_RENDERER) unless
/// otherwise indicated.
/// </summary>
public abstract unsafe partial class CefRenderProcessHandler
{
private void on_web_kit_initialized(cef_render_process_handler_t* self)
{
CheckSelf(self);
OnWebKitInitialized();
}
/// <summary>
/// Called after WebKit has been initialized.
/// </summary>
protected virtual void OnWebKitInitialized()
{
}
private void on_browser_created(cef_render_process_handler_t* self, cef_browser_t* browser, cef_dictionary_value_t* extra_info)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_extraInfo = CefDictionaryValue.FromNative(extra_info);
OnBrowserCreated(m_browser, m_extraInfo);
}
/// <summary>
/// Called after a browser has been created. When browsing cross-origin a new
/// browser will be created before the old browser with the same identifier is
/// destroyed. |extra_info| is a read-only value originating from
/// CefBrowserHost::CreateBrowser(), CefBrowserHost::CreateBrowserSync(),
/// CefLifeSpanHandler::OnBeforePopup() or CefBrowserView::CreateBrowserView().
/// </summary>
protected virtual void OnBrowserCreated(CefBrowser browser, CefDictionaryValue extraInfo)
{
}
private void on_browser_destroyed(cef_render_process_handler_t* self, cef_browser_t* browser)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnBrowserDestroyed(m_browser);
}
/// <summary>
/// Called before a browser is destroyed.
/// </summary>
protected virtual void OnBrowserDestroyed(CefBrowser browser)
{
}
private cef_load_handler_t* get_load_handler(cef_render_process_handler_t* self)
{
CheckSelf(self);
var result = GetLoadHandler();
return result != null ? result.ToNative() : null;
}
/// <summary>
/// Return the handler for browser load status events.
/// </summary>
protected virtual CefLoadHandler GetLoadHandler()
{
return null;
}
private void on_context_created(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_context = CefV8Context.FromNative(context);
OnContextCreated(m_browser, m_frame, m_context);
}
/// <summary>
/// Called immediately after the V8 context for a frame has been created. To
/// retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal()
/// method. V8 handles can only be accessed from the thread on which they are
/// created. A task runner for posting tasks on the associated thread can be
/// retrieved via the CefV8Context::GetTaskRunner() method.
/// </summary>
protected virtual void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context)
{
}
private void on_context_released(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_context = CefV8Context.FromNative(context);
OnContextReleased(m_browser, m_frame, m_context);
}
/// <summary>
/// Called immediately before the V8 context for a frame is released. No
/// references to the context should be kept after this method is called.
/// </summary>
protected virtual void OnContextReleased(CefBrowser browser, CefFrame frame, CefV8Context context)
{
}
private void on_uncaught_exception(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_v8context_t* context, cef_v8exception_t* exception, cef_v8stack_trace_t* stackTrace)
{
CheckSelf(self);
var mBrowser = CefBrowser.FromNative(browser);
var mFrame = CefFrame.FromNative(frame);
var mContext = CefV8Context.FromNative(context);
var mException = CefV8Exception.FromNative(exception);
var mStackTrace = CefV8StackTrace.FromNative(stackTrace);
OnUncaughtException(mBrowser, mFrame, mContext, mException, mStackTrace);
}
/// <summary>
/// Called for global uncaught exceptions in a frame. Execution of this
/// callback is disabled by default. To enable set
/// CefSettings.uncaught_exception_stack_size > 0.
/// </summary>
protected virtual void OnUncaughtException(CefBrowser browser, CefFrame frame, CefV8Context context, CefV8Exception exception, CefV8StackTrace stackTrace)
{
}
private void on_focused_node_changed(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_domnode_t* node)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_node = CefDomNode.FromNativeOrNull(node);
OnFocusedNodeChanged(m_browser, m_frame, m_node);
if (m_node != null) m_node.Dispose();
}
/// <summary>
/// Called when a new node in the the browser gets focus. The |node| value may
/// be empty if no specific node has gained focus. The node object passed to
/// this method represents a snapshot of the DOM at the time this method is
/// executed. DOM objects are only valid for the scope of this method. Do not
/// keep references to or attempt to access any DOM objects outside the scope
/// of this method.
/// </summary>
protected virtual void OnFocusedNodeChanged(CefBrowser browser, CefFrame frame, CefDomNode node)
{
}
private int on_process_message_received(cef_render_process_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, CefProcessId source_process, cef_process_message_t* message)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_frame = CefFrame.FromNative(frame);
var m_message = CefProcessMessage.FromNative(message);
var result = OnProcessMessageReceived(m_browser, m_frame, source_process, m_message);
m_message.Dispose();
return result ? 1 : 0;
}
/// <summary>
/// Called when a new message is received from a different process. Return true
/// if the message was handled or false otherwise. Do not keep a reference to
/// or attempt to access the message outside of this callback.
/// </summary>
protected virtual bool OnProcessMessageReceived(CefBrowser browser, CefFrame frame, CefProcessId sourceProcess, CefProcessMessage message)
{
return false;
}
}
| 34.839024 | 207 | 0.703584 | [
"MIT"
] | ClrsDream/NanUI | src/NetDimension.NanUI/third_party_libraries/CefGlue-90.6.7_g19ba721_chromium_90.0.4430.212/Classes.Handlers/CefRenderProcessHandler.cs | 7,144 | C# |
//using Moralis.Platform.Objects;
//using System;
//using System.Collections.Generic;
//using System.Text;
//namespace Moralis.Platform.Services.Infrastructure
//{
// public class PointerOrLocalIdEncoder : DataEncoder
// {
// public static PointerOrLocalIdEncoder Instance { get; } = new PointerOrLocalIdEncoder { };
// protected override IDictionary<string, object> EncodeObject(MoralisObject value)
// {
// if (value.objectId is null)
// {
// // TODO (hallucinogen): handle local id. For now we throw.
// throw new InvalidOperationException("Cannot create a pointer to an object without an objectId.");
// }
// return new Dictionary<string, object>
// {
// ["__type"] = "Pointer",
// ["className"] = value.ClassName,
// ["objectId"] = value.objectId
// };
// }
// }
//}
| 31.833333 | 115 | 0.571728 | [
"MIT"
] | AllTrueVision/ethereum-unity-boilerplate | Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/Platform/Services/Infrastructure/PointerOrLocalIdEncoder.cs | 957 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Uno.Extensions;
using Uno.UI.Views.Controls;
using Windows.UI.Xaml.Data;
using Uno.UI.Converters;
using Uno.Client;
using System.Threading.Tasks;
using Uno.Diagnostics.Eventing;
using Uno.UI.Controls;
using Windows.UI.Core;
using System.Globalization;
using Uno.Disposables;
using Uno.Extensions.Specialized;
using Windows.Foundation;
using Windows.UI.Xaml.Controls.Primitives;
using Uno.UI;
using Uno.Logging;
using Uno.UI.Extensions;
using Microsoft.Extensions.Logging;
using Uno.UI.UI.Xaml.Controls.Layouter;
#if NET6_0_OR_GREATER
using ObjCRuntime;
#endif
#if XAMARIN_IOS_UNIFIED
using Foundation;
using UIKit;
using CoreGraphics;
#elif XAMARIN_IOS
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using CGRect = System.Drawing.RectangleF;
using nfloat = System.Single;
using CGPoint = System.Drawing.PointF;
using nint = System.Int32;
using CGSize = System.Drawing.SizeF;
#endif
namespace Windows.UI.Xaml.Controls
{
[Bindable]
public partial class ListViewBaseSource : UICollectionViewSource
{
/// <summary>
/// Key used to represent a null DataTemplate in _templateCache and _templateCells dictionaries (because null is a not a valid key)
/// </summary>
private readonly static DataTemplate _nullDataTemplateKey = new DataTemplate(() => null);
private readonly static IEventProvider _trace = Tracing.Get(TraceProvider.Id);
private Dictionary<ListViewBaseInternalContainer, List<Action>> _onRecycled = new Dictionary<ListViewBaseInternalContainer, List<Action>>();
/// <summary>
/// We include one extra section to ensure Header and Footer can display even when we have no sections (ie an empty grouped source).
/// </summary>
internal const int SupplementarySections = 1;
/// <summary>
/// Visual element which stops layout requests from propagating up. Used for measuring templates.
/// </summary>
private BlockLayout BlockLayout { get; } = new BlockLayout();
public static class TraceProvider
{
public readonly static Guid Id = Guid.Parse("{EE64E62E-67BD-496A-A8B1-4A142642B3A3}");
public const int ListViewBaseSource_GetCellStart = 1;
public const int ListViewBaseSource_GetCellStop = 2;
}
#region Members
private DataTemplateSelector _currentSelector;
private Dictionary<DataTemplate, CGSize> _templateCache = new Dictionary<DataTemplate, CGSize>(DataTemplate.FrameworkTemplateEqualityComparer.Default);
private Dictionary<DataTemplate, NSString> _templateCells = new Dictionary<DataTemplate, NSString>(DataTemplate.FrameworkTemplateEqualityComparer.Default);
/// <summary>
/// The furthest item in the source which has already been materialized. Items up to this point can safely be retrieved.
/// </summary>
private NSIndexPath _lastMaterializedItem = NSIndexPath.FromRowSection(0, 0);
/// <summary>
/// Is the UICollectionView currently undergoing animated scrolling, either user-initiated or programmatic.
/// </summary>
private bool _isInAnimatedScroll;
#endregion
public ListViewBaseSource()
{
}
#region Properties
private WeakReference<NativeListViewBase> _owner;
public NativeListViewBase Owner
{
get { return _owner?.GetTarget(); }
set { _owner = new WeakReference<NativeListViewBase>(value); }
}
#endregion
public ListViewBaseSource(NativeListViewBase owner)
{
Owner = owner;
}
#region Overrides
public override nint NumberOfSections(UICollectionView collectionView)
{
var itemsSections = Owner.XamlParent.IsGrouping ?
Owner.XamlParent.NumberOfDisplayGroups :
1;
return itemsSections + SupplementarySections;
}
public override nint GetItemsCount(UICollectionView collectionView, nint section)
{
int count;
if (Owner.XamlParent.IsGrouping)
{
count = GetGroupedItemsCount(section);
}
else
{
count = GetUngroupedItemsCount(section);
}
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Count requested for section {section}, returning {count}");
}
return count;
}
private int GetUngroupedItemsCount(nint section)
{
int count;
if (section == 0)
{
count = Owner.XamlParent.NumberOfItems;
}
else
{
// Extra section added to accommodate header+footer, contains no items.
count = 0;
}
return count;
}
private int GetGroupedItemsCount(nint section)
{
if ((int)section >= Owner.XamlParent.NumberOfDisplayGroups)
{
// Header+footer section which is empty
return 0;
}
return Owner.XamlParent.GetDisplayGroupCount((int)section);
}
public override void CellDisplayingEnded(UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath)
{
var key = cell as ListViewBaseInternalContainer;
if (_onRecycled.TryGetValue(key, out var actions))
{
foreach (var a in actions) { a(); }
_onRecycled.Remove(key);
}
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"CellDisplayingEnded for cell at {indexPath}");
}
}
/// <summary>
/// Queues an action to be executed when the provided viewHolder is being recycled.
/// </summary>
internal void RegisterForRecycled(ListViewBaseInternalContainer container, Action action)
{
if (!_onRecycled.TryGetValue(container, out var actions))
{
_onRecycled[container] = actions = new List<Action>();
}
actions.Add(action);
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
using (
_trace.WriteEventActivity(
TraceProvider.ListViewBaseSource_GetCellStart,
TraceProvider.ListViewBaseSource_GetCellStop
)
)
{
// Marks this item to be materialized, so its actual measured size
// is used during the calculation of the layout.
// This is required for paged lists, so that the layout calculation
// does not eagerly get all the items of the ItemsSource.
UpdateLastMaterializedItem(indexPath);
var index = Owner?.XamlParent?.GetIndexFromIndexPath(Uno.UI.IndexPath.FromNSIndexPath(indexPath)) ?? -1;
var identifier = GetReusableCellIdentifier(indexPath);
var listView = (NativeListViewBase)collectionView;
var cell = (ListViewBaseInternalContainer)collectionView.DequeueReusableCell(identifier, indexPath);
using (cell.InterceptSetNeedsLayout())
{
var selectorItem = cell.Content as SelectorItem;
if (selectorItem == null ||
// If it's not a generated container then it must be an item that returned true for IsItemItsOwnContainerOverride (eg an
// explicitly-defined ListViewItem), and shouldn't be recycled for a different item.
!selectorItem.IsGeneratedContainer)
{
cell.Owner = Owner;
selectorItem = Owner?.XamlParent?.GetContainerForIndex(index) as SelectorItem;
cell.Content = selectorItem;
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Creating new view at indexPath={indexPath}.");
}
FrameworkElement.InitializePhaseBinding(selectorItem);
// Ensure the item has a parent, since it's added to the native collection view
// which does not automatically sets the parent DependencyObject.
selectorItem.SetParentOverride(Owner?.XamlParent?.InternalItemsPanelRoot);
}
else if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Reusing view at indexPath={indexPath}, previously bound to {selectorItem.DataContext}.");
}
Owner?.XamlParent?.PrepareContainerForIndex(selectorItem, index);
// Normally this happens when the SelectorItem.Content is set, but there's an edge case where after a refresh, a
// container can be dequeued which happens to have had exactly the same DataContext as the new item.
cell.ClearMeasuredSize();
}
Owner?.XamlParent?.TryLoadMoreItems(index);
return cell;
}
}
/// <summary>
/// Update record of the furthest item materialized.
/// </summary>
/// <param name="newItem">Item currently being materialized.</param>
/// <returns>True if the value has changed and the layout would change.</returns>
internal bool UpdateLastMaterializedItem(NSIndexPath newItem)
{
if (newItem.Compare(_lastMaterializedItem) > 0)
{
_lastMaterializedItem = newItem;
return Owner.ItemTemplateSelector != null; ;
}
else
{
return false;
}
}
/// <summary>
/// Is item in the range of already-materialized items?
/// </summary>
private bool IsMaterialized(NSIndexPath itemPath) => itemPath.Compare(_lastMaterializedItem) <= 0;
// Consider group header to be materialized if first item in group is materialized
private bool IsMaterialized(int section) => section <= _lastMaterializedItem.Section;
public override void WillDisplayCell(UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath)
{
var index = Owner?.XamlParent?.GetIndexFromIndexPath(Uno.UI.IndexPath.FromNSIndexPath(indexPath)) ?? -1;
var container = cell as ListViewBaseInternalContainer;
var selectorItem = container?.Content as SelectorItem;
//Update IsSelected and multi-select state immediately before display, in case either was modified after cell was prefetched but before it became visible
if (selectorItem != null)
{
selectorItem.IsSelected = Owner?.XamlParent?.IsSelected(index) ?? false;
Owner?.XamlParent?.ApplyMultiSelectState(selectorItem);
}
FrameworkElement.RegisterPhaseBinding(container.Content, a => RegisterForRecycled(container, a));
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"WillDisplayCell for cell at {indexPath}");
}
}
public override UICollectionReusableView GetViewForSupplementaryElement(
UICollectionView collectionView,
NSString elementKind,
NSIndexPath indexPath)
{
var listView = (NativeListViewBase)collectionView;
if (elementKind == NativeListViewBase.ListViewHeaderElementKind)
{
return GetBindableSupplementaryView(
collectionView: collectionView,
elementKind: NativeListViewBase.ListViewHeaderElementKindNS,
indexPath: indexPath,
reuseIdentifier: NativeListViewBase.ListViewHeaderReuseIdentifierNS,
context: listView.Header,
template: listView.HeaderTemplate,
style: null
);
}
else if (elementKind == NativeListViewBase.ListViewFooterElementKind)
{
return GetBindableSupplementaryView(
collectionView: collectionView,
elementKind: NativeListViewBase.ListViewFooterElementKindNS,
indexPath: indexPath,
reuseIdentifier: NativeListViewBase.ListViewFooterReuseIdentifierNS,
context: listView.Footer,
template: listView.FooterTemplate,
style: null
);
}
else if (elementKind == NativeListViewBase.ListViewSectionHeaderElementKind)
{
// Ensure correct template can be retrieved
UpdateLastMaterializedItem(indexPath);
return GetBindableSupplementaryView(
collectionView: collectionView,
elementKind: NativeListViewBase.ListViewSectionHeaderElementKindNS,
indexPath: indexPath,
reuseIdentifier: NativeListViewBase.ListViewSectionHeaderReuseIdentifierNS,
//ICollectionViewGroup.Group is used as context for sectionHeader
context: listView.XamlParent.GetGroupAtDisplaySection(indexPath.Section).Group,
template: GetTemplateForGroupHeader(indexPath.Section),
style: listView.GroupStyle?.HeaderContainerStyle
);
}
else
{
throw new NotSupportedException("Unsupported element kind: {0}".InvariantCultureFormat(elementKind));
}
}
private UICollectionReusableView GetBindableSupplementaryView(
UICollectionView collectionView,
NSString elementKind,
NSIndexPath indexPath,
NSString reuseIdentifier,
object context,
DataTemplate template,
Style style)
{
var supplementaryView = (ListViewBaseInternalContainer)collectionView.DequeueReusableSupplementaryView(
elementKind,
reuseIdentifier,
indexPath);
using (supplementaryView.InterceptSetNeedsLayout())
{
if (supplementaryView.Content == null)
{
supplementaryView.Owner = Owner;
var content = CreateContainerForElementKind(elementKind);
content.HorizontalContentAlignment = HorizontalAlignment.Stretch;
content.VerticalContentAlignment = VerticalAlignment.Stretch;
supplementaryView.Content = content
.Binding("Content", "");
}
supplementaryView.Content.ContentTemplate = template;
supplementaryView.Content.DataContext = context;
if (style != null)
{
supplementaryView.Content.Style = style;
}
}
return supplementaryView;
}
internal void SetIsAnimatedScrolling() => _isInAnimatedScroll = true;
#if !MACCATALYST // Fix on .NET 6 Preview 6 https://github.com/unoplatform/uno/issues/5873
public override void Scrolled(UIScrollView scrollView)
{
InvokeOnScroll();
}
// Called when user starts dragging
public override void DraggingStarted(UIScrollView scrollView)
{
_isInAnimatedScroll = true;
}
// Called when user stops dragging (lifts finger)
public override void DraggingEnded(UIScrollView scrollView, bool willDecelerate)
{
if (!willDecelerate)
{
//No fling, send final scroll event
OnAnimatedScrollEnded();
}
}
// Called when a user-initiated fling comes to a stop
public override void DecelerationEnded(UIScrollView scrollView)
{
OnAnimatedScrollEnded();
}
// Called at the end of a programmatic animated scroll
public override void ScrollAnimationEnded(UIScrollView scrollView)
{
OnAnimatedScrollEnded();
}
public override void DidZoom(UIScrollView scrollView)
{
// Note: untested, more may be needed to support zooming. On ScrollContentPresenter we set ViewForZoomingInScrollView (not
// obvious what it would be in the case of a list).
Owner.XamlParent?.ScrollViewer?.Presenter?.OnNativeZoom((float)Owner.ZoomScale);
}
#endif
private void OnAnimatedScrollEnded()
{
_isInAnimatedScroll = false;
InvokeOnScroll();
}
private void InvokeOnScroll()
{
var shouldReportNegativeOffsets = Owner.XamlParent?.ScrollViewer?.ShouldReportNegativeOffsets ?? false;
// iOS can return, eg, negative values for offset, whereas Windows never will, even for 'elastic' scrolling
var clampedOffset = shouldReportNegativeOffsets ?
Owner.ContentOffset :
Owner.ContentOffset.Clamp(CGPoint.Empty, Owner.UpperScrollLimit);
Owner.XamlParent?.ScrollViewer?.Presenter?.OnNativeScroll(clampedOffset.X, clampedOffset.Y, isIntermediate: _isInAnimatedScroll);
}
#if !MACCATALYST // Fix on .NET 6 Preview 6 https://github.com/unoplatform/uno/issues/5873
public override void WillEndDragging(UIScrollView scrollView, CGPoint velocity, ref CGPoint targetContentOffset)
{
// If snap points are enabled, override the target offset with the calculated snap point.
var snapTo = Owner?.NativeLayout?.GetSnapTo(velocity, targetContentOffset);
if (snapTo.HasValue)
{
targetContentOffset = snapTo.Value;
}
}
#endif
#endregion
internal void ReloadData()
{
_lastMaterializedItem = NSIndexPath.FromRowSection(0, 0);
}
/// <summary>
/// Get item container corresponding to an element kind (header, footer, list item, etc)
/// </summary>
private ContentControl CreateContainerForElementKind(NSString elementKind)
{
if (elementKind == NativeListViewBase.ListViewSectionHeaderElementKindNS)
{
return Owner?.XamlParent?.GetGroupHeaderContainer(null);
}
else if (elementKind == NativeListViewBase.ListViewItemElementKindNS)
{
return Owner?.XamlParent?.GetContainerForIndex(-1) as ContentControl;
}
else
{
//Used for header and footer
return ContentControl.CreateItemContainer();
}
}
internal CGSize GetHeaderSize(Size availableSize)
{
return Owner.HeaderTemplate != null ? GetTemplateSize(Owner.HeaderTemplate, NativeListViewBase.ListViewHeaderElementKindNS, availableSize) : CGSize.Empty;
}
internal CGSize GetFooterSize(Size availableSize)
{
return Owner.FooterTemplate != null ? GetTemplateSize(Owner.FooterTemplate, NativeListViewBase.ListViewFooterElementKindNS, availableSize) : CGSize.Empty;
}
internal CGSize GetSectionHeaderSize(int section, Size availableSize)
{
var template = GetTemplateForGroupHeader(section);
return template.SelectOrDefault(ht => GetTemplateSize(ht, NativeListViewBase.ListViewSectionHeaderElementKindNS, availableSize), CGSize.Empty);
}
internal CGSize GetItemSize(UICollectionView collectionView, NSIndexPath indexPath, Size availableSize)
{
DataTemplate itemTemplate = GetTemplateForItem(indexPath);
if (_currentSelector != Owner.ItemTemplateSelector)
{
// If the templateSelector has changed, clear the cache
_currentSelector = Owner.ItemTemplateSelector;
_templateCache.Clear();
_templateCells.Clear();
}
var size = GetTemplateSize(itemTemplate, NativeListViewBase.ListViewItemElementKindNS, availableSize);
if (size == CGSize.Empty)
{
// The size of the template is usually empty for items that have not been displayed yet when using ItemTemplateSelector.
// The reason why we can't measure the template is because we do not resolve it,
// as it would require enumerating through all items of a possibly virtualized ItemsSource.
// To ensure a first display (after which they will be properly measured), we need them to have a non-empty size.
size = new CGSize(44, 44); // 44 is the default MinHeight/MinWidth of ListViewItem/GridViewItem on UWP.
}
return size;
}
private DataTemplate GetTemplateForItem(NSIndexPath indexPath)
{
if (IsMaterialized(indexPath))
{
return Owner?.XamlParent?.ResolveItemTemplate(Owner.XamlParent.GetDisplayItemFromIndexPath(indexPath.ToIndexPath()));
}
else
{
// Ignore ItemTemplateSelector since we do not know what the item is
return Owner?.XamlParent?.ItemTemplate;
}
}
private DataTemplate GetTemplateForGroupHeader(int section)
{
var groupStyle = Owner.GroupStyle;
if (IsMaterialized(section))
{
return DataTemplateHelper.ResolveTemplate(
groupStyle?.HeaderTemplate,
groupStyle?.HeaderTemplateSelector,
Owner.XamlParent.GetGroupAtDisplaySection(section).Group,
Owner);
}
else
{
return groupStyle?.HeaderTemplate;
}
}
/// <summary>
/// Gets the actual item template size, using a non-databound materialized
/// view of the template.
/// </summary>
/// <param name="dataTemplate">A data template</param>
/// <returns>The actual size of the template</returns>
private CGSize GetTemplateSize(DataTemplate dataTemplate, NSString elementKind, Size availableSize)
{
CGSize size;
// Cache the sizes to avoid creating new templates every time.
if (!_templateCache.TryGetValue(dataTemplate ?? _nullDataTemplateKey, out size))
{
var container = CreateContainerForElementKind(elementKind);
// Force a null DataContext so the parent's value does not flow
// through when temporarily adding the container to Owner.XamlParent
container.SetValue(FrameworkElement.DataContextProperty, null);
Style style = null;
if (elementKind == NativeListViewBase.ListViewItemElementKind)
{
style = Owner.ItemContainerStyle;
}
else if (elementKind == NativeListViewBase.ListViewSectionHeaderElementKind)
{
style = Owner.GroupStyle?.HeaderContainerStyle;
}
if (style != null)
{
container.Style = style;
}
if (!container.IsContainerFromTemplateRoot)
{
container.ContentTemplate = dataTemplate;
}
try
{
// Attach templated container to visual tree while measuring. This works around the bug that default Style is not
// applied until view is loaded.
Owner.XamlParent.AddSubview(BlockLayout);
BlockLayout.AddSubview(container);
// Measure with PositiveInfinity rather than MaxValue, since some views handle this better.
size = Owner.NativeLayout.Layouter.MeasureChild(container, availableSize);
if ((size.Height > nfloat.MaxValue / 2 || size.Width > nfloat.MaxValue / 2) &&
this.Log().IsEnabled(LogLevel.Warning)
)
{
this.Log().LogWarning($"Infinite item size reported, this can crash {nameof(UICollectionView)}.");
}
}
finally
{
Owner.XamlParent.RemoveChild(BlockLayout);
BlockLayout.RemoveChild(container);
// Reset the DataContext for reuse.
container.ClearValue(FrameworkElement.DataContextProperty);
}
_templateCache[dataTemplate ?? _nullDataTemplateKey] = size;
}
return size;
}
/// <summary>
/// Determine the identifier to use for the dequeuing.
/// This avoid for already materialized items with a specific template
/// to switch to a different template, and have to re-create the content
/// template.
/// </summary>
private NSString GetReusableCellIdentifier(NSIndexPath indexPath)
{
NSString identifier;
var template = GetTemplateForItem(indexPath);
if (!_templateCells.TryGetValue(template ?? _nullDataTemplateKey, out identifier))
{
identifier = new NSString(_templateCells.Count.ToString(CultureInfo.InvariantCulture));
_templateCells[template ?? _nullDataTemplateKey] = identifier;
Owner.RegisterClassForCell(typeof(ListViewBaseInternalContainer), identifier);
}
return identifier;
}
}
/// <summary>
/// A hidden root item that allows the reuse of ContentControl features.
/// </summary>
internal class ListViewBaseInternalContainer : UICollectionViewCell, ISetLayoutSlots
{
/// <summary>
/// Native constructor, do not use explicitly.
/// </summary>
/// <remarks>
/// Used by the Xamarin Runtime to materialize native
/// objects that may have been collected in the managed world.
/// </remarks>
public ListViewBaseInternalContainer(IntPtr handle) : base(handle) { }
public ListViewBaseInternalContainer()
{
}
private CGSize _lastUsedSize;
private CGSize? _measuredContentSize;
private readonly SerialDisposable _contentChangedDisposable = new SerialDisposable();
private bool _needsLayout = true;
private bool _interceptSetNeedsLayout = false;
private WeakReference<NativeListViewBase> _ownerRef;
public NativeListViewBase Owner
{
get { return _ownerRef?.GetTarget(); }
set
{
if (value != _ownerRef?.GetTarget())
{
_ownerRef = new WeakReference<NativeListViewBase>(value);
}
}
}
private Orientation ScrollOrientation => Owner.NativeLayout.ScrollOrientation;
private bool SupportsDynamicItemSizes => Owner.NativeLayout.SupportsDynamicItemSizes;
private ILayouter Layouter => Owner.NativeLayout.Layouter;
protected override void Dispose(bool disposing)
{
if (!disposing)
{
GC.ReRegisterForFinalize(this);
CoreDispatcher.Main.RunIdleAsync(_ => Dispose());
}
else
{
// We need to explicitly remove the content before being disposed
// otherwise, the children will try to reference ContentView which
// will have been disposed.
foreach (var v in ContentView.Subviews)
{
v.RemoveFromSuperview();
}
base.Dispose(disposing);
}
}
public ContentControl Content
{
get
{
return /* Cache the content ?*/ContentView?.Subviews.FirstOrDefault() as ContentControl;
}
set
{
using (InterceptSetNeedsLayout())
{
if (ContentView.Subviews.Any())
{
ContentView.Subviews[0].RemoveFromSuperview();
}
value.Frame = ContentView.Bounds;
value.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
ContentView.AddSubview(value);
ClearMeasuredSize();
_contentChangedDisposable.Disposable = value?.RegisterDisposablePropertyChangedCallback(ContentControl.ContentProperty, (_, __) => _measuredContentSize = null);
}
}
}
public override CGRect Frame
{
get => base.Frame;
set
{
base.Frame = value;
UpdateContentViewFrame();
UpdateContentLayoutSlots(value);
}
}
public override CGRect Bounds
{
get => base.Bounds;
set
{
if (_measuredContentSize.HasValue)
{
// At some points, eg during a collection change, iOS seems to apply an outdated size even after we've updated the
// LayoutAttributes. Keep the good size.
SetExtent(ref value, _measuredContentSize.Value);
}
base.Bounds = value;
UpdateContentViewFrame();
UpdateContentLayoutSlots(Frame);
}
}
/// <summary>
/// Set the ContentView's size to match the InternalContainer, this is necessary for touches to buttons inside the template to
/// propagate properly.
/// </summary>
private void UpdateContentViewFrame()
{
if (ContentView != null)
{
ContentView.Frame = Bounds;
}
}
/// <summary>
/// Fakely propagate the applied Frame of this internal container as the LayoutSlot of the publicly visible container.
/// This is required for the UIElement.TransformToVisual to work properly.
/// </summary>
private void UpdateContentLayoutSlots(Rect frame)
{
var content = Content;
if (content != null)
{
LayoutInformation.SetLayoutSlot(content, frame);
content.LayoutSlotWithMarginsAndAlignments = frame;
}
}
/// <summary>
/// Clear the cell's measured size, this allows the static template size to be updated with the correct databound size.
/// </summary>
internal void ClearMeasuredSize() => _measuredContentSize = null;
public override UICollectionViewLayoutAttributes PreferredLayoutAttributesFittingAttributes(UICollectionViewLayoutAttributes layoutAttributes)
{
if (!(((object)layoutAttributes) is UICollectionViewLayoutAttributes))
{
// This case happens for a yet unknown GC issue, where the layoutAttribute instance passed the current
// method maps to another object. The repro steps are not clear, and it may be related to ListView/GridView
// data reload.
this.Log().Error("ApplyLayoutAttributes has been called with an invalid instance. See bug #XXX for more details.");
return null;
}
if (Content == null)
{
this.Log().Error("Empty ListViewBaseInternalContainer content.");
return null;
}
try
{
var size = layoutAttributes.Frame.Size;
if (_measuredContentSize == null || size != _lastUsedSize)
{
_lastUsedSize = size;
var availableSize = AdjustAvailableSize(layoutAttributes.Frame.Size.ToFoundationSize());
if (Window != null || Owner.XamlParent.Window == null)
{
using (InterceptSetNeedsLayout())
{
_measuredContentSize = Layouter.MeasureChild(Content, availableSize);
}
}
else
{
try
{
//Attach temporarily, because some Uno control (eg ItemsControl) are only measured correctly after MovedToWindow has been called
InterceptSetNeedsLayout();
Owner.XamlParent.AddSubview(this);
_measuredContentSize = Layouter.MeasureChild(Content, availableSize);
}
finally
{
Owner.XamlParent.RemoveChild(this);
AllowSetNeedsLayout();
}
}
if (SupportsDynamicItemSizes ||
layoutAttributes.RepresentedElementKind == NativeListViewBase.ListViewSectionHeaderElementKind ||
layoutAttributes.RepresentedElementKind == NativeListViewBase.ListViewHeaderElementKind ||
layoutAttributes.RepresentedElementKind == NativeListViewBase.ListViewFooterElementKind
)
{
//Fetch layout for this item from collection view, since it may have been updated by an earlier item
var cachedAttributes = layoutAttributes.RepresentedElementKind == null ?
Owner.NativeLayout.LayoutAttributesForItem(layoutAttributes.IndexPath) :
Owner.NativeLayout.LayoutAttributesForSupplementaryView((NSString)layoutAttributes.RepresentedElementKind, layoutAttributes.IndexPath);
// cachedAttributes may be null if we have modified the collection with DeleteItems
var frame = cachedAttributes?.Frame ?? layoutAttributes.Frame;
SetExtent(ref frame, _measuredContentSize.Value);
var sizesAreDifferent = frame.Size != layoutAttributes.Frame.Size;
if (sizesAreDifferent)
{
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Adjusting layout attributes for item at {layoutAttributes.IndexPath}({layoutAttributes.RepresentedElementKind}), Content={Content?.Content}. Previous frame={layoutAttributes.Frame}, new frame={frame}.");
}
Owner.NativeLayout.HasDynamicElementSizes = true;
this.Frame = frame;
SetNeedsLayout();
//If we don't do a lightweight refresh here, in some circumstances (grouping enabled?) the UICollectionView seems
//to use stale layoutAttributes for deciding if items should be visible, leading to them popping out of view mid-viewport.
Owner?.NativeLayout?.RefreshLayout();
}
layoutAttributes.Frame = frame;
if (sizesAreDifferent)
{
Owner.NativeLayout.UpdateLayoutAttributesForElement(layoutAttributes);
}
if (layoutAttributes.RepresentedElementKind != null)
{
//The UICollectionView seems to call PreferredLayoutAttributesFittingAttributes for supplementary views last. Therefore
//we need to relayout all visible items to make sure item views are offset to account for headers and group headers.
Owner.NativeLayout.RefreshLayout();
}
}
}
}
catch (Exception e)
{
this.Log().Error($"Adjusting layout attributes for {layoutAttributes?.IndexPath?.ToString() ?? "[null]"} failed", e);
}
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Returning layout attributes for item at {layoutAttributes.IndexPath}({layoutAttributes.RepresentedElementKind}), Content={Content?.Content}, with frame {layoutAttributes.Frame}");
}
if (layoutAttributes.Frame != this.Frame)
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().Debug($"Overwriting Frame: Item={layoutAttributes.IndexPath}: layoutAttributes.Frame={layoutAttributes.Frame}, this.Frame={this.Frame}");
}
// For some reason the item's Frame can be left stuck in the wrong value in certain cases where it is changed repeatedly in
// response to sequential collection changes.
Frame = layoutAttributes.Frame;
}
return layoutAttributes;
}
public void SetSuperviewNeedsLayout()
{
if (!_needsLayout && !_interceptSetNeedsLayout)
{
_needsLayout = true;
Owner?.NativeLayout?.RefreshLayout();
ClearMeasuredSize();
SetNeedsLayout();
}
}
public override void LayoutSubviews()
{
_needsLayout = false;
var size = Bounds.Size;
if (Content != null)
{
Layouter.ArrangeChild(Content, new Rect(0, 0, (float)size.Width, (float)size.Height));
// The item has to be arranged relative to this internal container (at 0,0),
// but doing this the LayoutSlot[WithMargins] has been updated,
// so we fakely re-inject the relative position of the item in its parent.
UpdateContentLayoutSlots(Frame);
}
}
/// <summary>
/// Instruct the <see cref="ListViewBaseInternalContainer"/> not to propagate layout requests to its parent list, eg because the
/// item is in the process of being prepared by the list.
/// </summary>
internal IDisposable InterceptSetNeedsLayout()
{
_interceptSetNeedsLayout = true;
return Disposable.Create(AllowSetNeedsLayout);
}
/// <summary>
/// Tell the container to resume propagating layout requests.
/// </summary>
private void AllowSetNeedsLayout() => _interceptSetNeedsLayout = false;
/// <summary>
/// Set available size to be infinite in the scroll direction.
/// </summary>
private Size AdjustAvailableSize(Size availableSize)
{
if (ScrollOrientation == Orientation.Vertical)
{
availableSize.Height = double.PositiveInfinity;
}
else
{
availableSize.Width = double.PositiveInfinity;
}
return availableSize;
}
/// <summary>
/// Set the frame's extent in the direction of scrolling.
/// </summary>
private void SetExtent(ref CGRect frame, CGSize targetSize)
{
if (ScrollOrientation == Orientation.Vertical)
{
frame.Height = targetSize.Height;
}
else
{
frame.Width = targetSize.Width;
}
}
}
internal partial class BlockLayout : Border
{
public override void SetNeedsLayout()
{
//Block
}
public override void SetSuperviewNeedsLayout()
{
//Block
}
}
}
| 32.535183 | 230 | 0.728128 | [
"Apache-2.0"
] | ArchieCoder/uno | src/Uno.UI/UI/Xaml/Controls/ListViewBase/ListViewBaseSource.iOS.cs | 32,828 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using FluentAssertions;
using IdentityModel;
using IdentityModel.Client;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer4.IntegrationTests.Clients
{
public class ExtensionGrantClient
{
private const string TokenEndpoint = "https://server/connect/token";
private readonly HttpClient _client;
private readonly HttpMessageHandler _handler;
public ExtensionGrantClient()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_handler = server.CreateHandler();
_client = server.CreateClient();
}
[Fact]
public async Task Valid_Client()
{
var client = new TokenClient(
TokenEndpoint,
"client.custom",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "custom_credential", "custom credential"}
};
var response = await client.RequestCustomGrantAsync("custom", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
var unixNow = DateTime.UtcNow.ToEpochTime();
var exp = Int64.Parse(payload["exp"].ToString());
exp.Should().BeLessThan(unixNow + 3605);
exp.Should().BeGreaterThan(unixNow + 3595);
payload.Count().Should().Be(10);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.custom");
payload.Should().Contain("sub", "818727");
payload.Should().Contain("idp", "local");
var audiences = ((JArray)payload["aud"]).Select(x => x.ToString());
audiences.Count().Should().Be(2);
audiences.Should().Contain("https://idsvr4/resources");
audiences.Should().Contain("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("custom");
}
[Fact]
public async Task Valid_Client_No_Subject()
{
var client = new TokenClient(
TokenEndpoint,
"client.custom",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "custom_credential", "custom credential"}
};
var response = await client.RequestCustomGrantAsync("custom.nosubject", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
payload.Count().Should().Be(6);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.custom");
var audiences = ((JArray)payload["aud"]).Select(x => x.ToString());
audiences.Count().Should().Be(2);
audiences.Should().Contain("https://idsvr4/resources");
audiences.Should().Contain("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
}
[Fact]
public async Task Valid_Client_with_default_Scopes()
{
var client = new TokenClient(
TokenEndpoint,
"client.custom",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "custom_credential", "custom credential"}
};
var response = await client.RequestCustomGrantAsync("custom", extra: customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
payload.Count().Should().Be(10);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.custom");
payload.Should().Contain("sub", "818727");
payload.Should().Contain("idp", "local");
var audiences = ((JArray)payload["aud"]).Select(x => x.ToString());
audiences.Count().Should().Be(2);
audiences.Should().Contain("https://idsvr4/resources");
audiences.Should().Contain("api");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("custom");
var scopes = payload["scope"] as JArray;
scopes.Count().Should().Be(2);
scopes.First().ToString().Should().Be("api1");
scopes.Skip(1).First().ToString().Should().Be("api2");
}
[Fact]
public async Task Valid_Client_Missing_Grant_Specific_Data()
{
var client = new TokenClient(
TokenEndpoint,
"client.custom",
"secret",
innerHttpMessageHandler: _handler);
var response = await client.RequestCustomGrantAsync("custom", "api1");
response.IsError.Should().Be(true);
response.ErrorType.Should().Be(ResponseErrorType.Protocol);
response.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant);
response.ErrorDescription.Should().Be("invalid_custom_credential");
}
[Fact]
public async Task Valid_Client_Unsupported_Grant()
{
var client = new TokenClient(
TokenEndpoint,
"client.custom",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "custom_credential", "custom credential"}
};
var response = await client.RequestCustomGrantAsync("invalid", "api1", customParameters);
response.IsError.Should().Be(true);
response.ErrorType.Should().Be(ResponseErrorType.Protocol);
response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Error.Should().Be("unsupported_grant_type");
}
[Fact]
public async Task Valid_Client_Unauthorized_Grant()
{
var client = new TokenClient(
TokenEndpoint,
"client.custom",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "custom_credential", "custom credential"}
};
var response = await client.RequestCustomGrantAsync("custom2", "api1", customParameters);
response.IsError.Should().Be(true);
response.ErrorType.Should().Be(ResponseErrorType.Protocol);
response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Error.Should().Be("unsupported_grant_type");
}
[Fact]
public async Task Dynamic_Client_Lifetime()
{
var client = new TokenClient(
TokenEndpoint,
"client.dynamic",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "lifetime", "5000"},
{ "sub", "818727"}
};
var response = await client.RequestCustomGrantAsync("dynamic", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(5000);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
var unixNow = DateTime.UtcNow.ToEpochTime();
var exp = Int64.Parse(payload["exp"].ToString());
exp.Should().BeLessThan(unixNow + 5005);
exp.Should().BeGreaterThan(unixNow + 4995);
payload.Count().Should().Be(10);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.dynamic");
payload.Should().Contain("sub", "818727");
payload.Should().Contain("idp", "local");
var audiences = ((JArray)payload["aud"]).Select(x => x.ToString());
audiences.Count().Should().Be(2);
audiences.Should().Contain("https://idsvr4/resources");
audiences.Should().Contain("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("delegation");
}
[Fact]
public async Task Dynamic_Client_Jwt()
{
var client = new TokenClient(
TokenEndpoint,
"client.dynamic",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "sub", "818727"},
{ "type", "jwt" }
};
var response = await client.RequestCustomGrantAsync("dynamic", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
response.AccessToken.Should().Contain(".");
}
[Fact]
public async Task Dynamic_Client_Reference()
{
var client = new TokenClient(
TokenEndpoint,
"client.dynamic",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "sub", "818727"},
{ "type", "reference" }
};
var response = await client.RequestCustomGrantAsync("dynamic", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
response.AccessToken.Should().NotContain(".");
}
[Fact]
public async Task Dynamic_Client_Client_Claims()
{
var client = new TokenClient(
TokenEndpoint,
"client.dynamic",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "claim", "extra_claim"},
{ "sub", "818727"}
};
var response = await client.RequestCustomGrantAsync("dynamic", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
payload.Count().Should().Be(11);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.dynamic");
payload.Should().Contain("sub", "818727");
payload.Should().Contain("idp", "local");
payload.Should().Contain("client_extra", "extra_claim");
var audiences = ((JArray)payload["aud"]).Select(x => x.ToString());
audiences.Count().Should().Be(2);
audiences.Should().Contain("https://idsvr4/resources");
audiences.Should().Contain("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("delegation");
}
[Fact]
public async Task Dynamic_Client_Client_Claims_no_Sub()
{
var client = new TokenClient(
TokenEndpoint,
"client.dynamic",
"secret",
innerHttpMessageHandler: _handler);
var customParameters = new Dictionary<string, string>
{
{ "claim", "extra_claim"}
};
var response = await client.RequestCustomGrantAsync("dynamic", "api1", customParameters);
response.IsError.Should().BeFalse();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
payload.Count().Should().Be(7);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.dynamic");
payload.Should().Contain("client_extra", "extra_claim");
var audiences = ((JArray)payload["aud"]).Select(x => x.ToString());
audiences.Count().Should().Be(2);
audiences.Should().Contain("https://idsvr4/resources");
audiences.Should().Contain("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
}
private Dictionary<string, object> GetPayload(TokenResponse response)
{
var token = response.AccessToken.Split('.').Skip(1).Take(1).First();
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(
Encoding.UTF8.GetString(Base64Url.Decode(token)));
return dictionary;
}
}
} | 37.334873 | 110 | 0.556353 | [
"Apache-2.0"
] | Aratirn/IdentityServer4 | test/IdentityServer.IntegrationTests/Clients/ExtensionGrantClient.cs | 16,168 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text.Json;
using FluentAssertions;
using Microsoft.DotNet.Interactive.Jupyter.ZMQ;
using Microsoft.DotNet.Interactive.Notebook;
using Microsoft.DotNet.Interactive.Tests.Utility;
using Xunit;
namespace Microsoft.DotNet.Interactive.Jupyter.Tests
{
public class CustomMetadataParsingTests
{
[Fact]
public void Input_cell_metadata_can_be_parsed_with_all_fields()
{
var rawMetadata = new
{
dotnet_interactive = new InputCellMetadata("fsharp")
};
var rawMetadataJson = JsonSerializer.Serialize(rawMetadata);
var metadata = MetadataExtensions.DeserializeMetadataFromJsonString(rawMetadataJson);
metadata.Should()
.ContainKey("dotnet_interactive")
.WhichValue
.Should()
.BeEquivalentToRespectingRuntimeTypes(new InputCellMetadata("fsharp"));
}
[Fact]
public void Input_cell_metadata_can_be_parsed_with_no_fields()
{
var rawMetadata = new
{
dotnet_interactive = new InputCellMetadata()
};
var rawMetadataJson = JsonSerializer.Serialize(rawMetadata);
var metadata = MetadataExtensions.DeserializeMetadataFromJsonString(rawMetadataJson);
metadata.Should()
.ContainKey("dotnet_interactive")
.WhichValue
.Should()
.BeEquivalentToRespectingRuntimeTypes(new InputCellMetadata() );
}
[Fact]
public void Input_cell_metadata_is_not_parsed_when_not_present()
{
var rawMetadata = new
{
dotnet_interactive_but_not_the_right_shape = new InputCellMetadata("fsharp")
};
var rawMetadataJson = JsonSerializer.Serialize(rawMetadata);
var metadata = MetadataExtensions.DeserializeMetadataFromJsonString(rawMetadataJson);
metadata.Should()
.NotContainKey("dotnet_interactive");
}
}
}
| 37.098361 | 101 | 0.6403 | [
"MIT"
] | AngleQian/interactive | src/Microsoft.DotNet.Interactive.Jupyter.Tests/CustomMetadataParsingTests.cs | 2,265 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Dfe.Edis.SourceAdapter.Ukrlp.Infrastructure.UkrlpSoapApi.UnitTests")] | 46.666667 | 100 | 0.857143 | [
"MIT"
] | DFE-Digital/edis-source-adapter-ukrlp | src/Dfe.Edis.SourceAdapter.Ukrlp.Infrastructure.UkrlpSoapApi/Properties/AssemblyInfo.cs | 140 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Nucs.JsonSettings.Examples {
static class JsonProgram {
/// <summary>
/// The main entry point for the application.
/// </summary>
private static Settings Settings { get; } = JsonSettings.Load<Settings>("memory.jsn");
public static void Run(string[] args) {
//simple app to open a file by command and browse to a new file on demand.
while (true) {
Console.WriteLine("Commands: \nopen - open a file\nbrowse - browse to a new file\nquit - closes");
Console.Write(">");
while (Console.ReadLine().ToLowerInvariant() is string r && (r == "open" || r == "browse" || r == "quit")) {
switch (r) {
case "open":
if (string.IsNullOrEmpty(Settings.LastPath))
goto _browse;
Process.Start(Settings.LastPath);
break;
case "browse":
_browse:
var dia = new OpenFileDialog() {FileName = Settings.LastPath, Multiselect = false};
if (dia.ShowDialog() == DialogResult.OK) {
Settings.LastPath = dia.FileName;
Settings.Save();
}
break;
}
Console.Write(">");
}
}
}
}
public class Settings : JsonSettings {
public override string FileName { get; set; } = "some.default.just.in.case.jsn";
public virtual string LastPath { get; set; }
public Settings() { }
public Settings(string fileName) : base(fileName) { }
}
} | 39.56 | 124 | 0.490394 | [
"MIT"
] | BridgerPhotonics/JsonSettings | examples/JsonSettings.Examples/JsonSettings.cs | 1,980 | C# |
namespace RPGStoreSimulator
{
class Sword : BaseItem
{
public int sharpness = 0; // How much it pierces armour.
public float crit = 0.1f; // Chance of critting.
public Sword() { }
public override void Setup() // Just adding stats cuz why not.
{
string[] stats = { };
Table.Add(GetStats(), $"- Sharpness: {sharpness}", out stats); SetStats(stats);
Table.Add(GetStats(), $"- Crit: {crit * 100}%", out stats); SetStats(stats);
}
}
} | 33.875 | 92 | 0.5369 | [
"MIT"
] | JacobsReturn/RPGStoreFront | RPGStoreSimulator/Classes/Inventory/Sword.cs | 544 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "GIL_618e",
"name": [
"鸦羽的召唤",
"Glinda's Call"
],
"text": [
"获得<b>回响</b>。",
"Has <b>Echo</b>."
],
"cardClass": "WARLOCK",
"type": "ENCHANTMENT",
"cost": null,
"rarity": null,
"set": "GILNEAS",
"collectible": null,
"dbfId": 52780
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_GIL_618e : SimTemplate
{
}
} | 14.592593 | 36 | 0.538071 | [
"MIT"
] | chi-rei-den/Silverfish | cards/GILNEAS/GIL/Sim_GIL_618e.cs | 414 | C# |
// Copyright © 2017 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, 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
//
// 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.
namespace chocolatey.tests.infrastructure.app.commands
{
using System;
using System.Collections.Generic;
using System.Linq;
using chocolatey.infrastructure.app.attributes;
using chocolatey.infrastructure.app.commands;
using chocolatey.infrastructure.app.configuration;
using chocolatey.infrastructure.app.domain;
using chocolatey.infrastructure.app.services;
using chocolatey.infrastructure.commandline;
using Moq;
using Should;
public class ChocolateySourceCommandSpecs
{
public abstract class ChocolateySourceCommandSpecsBase : TinySpec
{
protected ChocolateySourceCommand command;
protected Mock<IChocolateyConfigSettingsService> configSettingsService = new Mock<IChocolateyConfigSettingsService>();
protected ChocolateyConfiguration configuration = new ChocolateyConfiguration();
public override void Context()
{
configuration.Sources = "https://localhost/somewhere/out/there";
command = new ChocolateySourceCommand(configSettingsService.Object);
}
}
public class when_implementing_command_for : ChocolateySourceCommandSpecsBase
{
private List<string> results;
public override void Because()
{
results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast<CommandForAttribute>().Select(a => a.CommandName).ToList();
}
[Fact]
public void should_implement_source()
{
results.ShouldContain("source");
}
[Fact]
public void should_implement_sources()
{
results.ShouldContain("sources");
}
}
public class when_configurating_the_argument_parser : ChocolateySourceCommandSpecsBase
{
private OptionSet optionSet;
public override void Context()
{
base.Context();
optionSet = new OptionSet();
configuration.Sources = "https://localhost/somewhere/out/there";
}
public override void Because()
{
command.configure_argument_parser(optionSet, configuration);
}
[Fact]
public void should_clear_previously_set_Source()
{
configuration.Sources.ShouldBeEmpty();
}
[Fact]
public void should_add_name_to_the_option_set()
{
optionSet.Contains("name").ShouldBeTrue();
}
[Fact]
public void should_add_short_version_of_name_to_the_option_set()
{
optionSet.Contains("n").ShouldBeTrue();
}
[Fact]
public void should_add_source_to_the_option_set()
{
optionSet.Contains("source").ShouldBeTrue();
}
[Fact]
public void should_add_short_version_of_source_to_the_option_set()
{
optionSet.Contains("s").ShouldBeTrue();
}
[Fact]
public void should_add_user_to_the_option_set()
{
optionSet.Contains("user").ShouldBeTrue();
}
[Fact]
public void should_add_short_version_of_user_to_the_option_set()
{
optionSet.Contains("u").ShouldBeTrue();
}
[Fact]
public void should_add_password_to_the_option_set()
{
optionSet.Contains("password").ShouldBeTrue();
}
[Fact]
public void should_add_short_version_of_password_to_the_option_set()
{
optionSet.Contains("p").ShouldBeTrue();
}
}
public class when_handling_additional_argument_parsing : ChocolateySourceCommandSpecsBase
{
private readonly IList<string> unparsedArgs = new List<string>();
private Action because;
public override void Because()
{
because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration);
}
public void reset()
{
unparsedArgs.Clear();
configSettingsService.ResetCalls();
}
[Fact]
public void should_use_the_first_unparsed_arg_as_the_subcommand()
{
reset();
unparsedArgs.Add("list");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list);
}
[Fact]
public void should_throw_when_more_than_one_unparsed_arg_is_passed()
{
reset();
unparsedArgs.Add("wtf");
unparsedArgs.Add("bbq");
var errorred = false;
Exception error = null;
try
{
because();
}
catch (Exception ex)
{
errorred = true;
error = ex;
}
errorred.ShouldBeTrue();
error.ShouldNotBeNull();
error.ShouldBeType<ApplicationException>();
error.Message.ShouldContain("A single sources command must be listed");
}
[Fact]
public void should_accept_add_as_the_subcommand()
{
reset();
unparsedArgs.Add("add");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.add);
}
[Fact]
public void should_accept_uppercase_add_as_the_subcommand()
{
reset();
unparsedArgs.Add("ADD");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.add);
}
[Fact]
public void should_remove_add_as_the_subcommand()
{
reset();
unparsedArgs.Add("remove");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.remove);
}
[Fact]
public void should_accept_enable_as_the_subcommand()
{
reset();
unparsedArgs.Add("enable");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.enable);
}
[Fact]
public void should_accept_disable_as_the_subcommand()
{
reset();
unparsedArgs.Add("disable");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.disable);
}
[Fact]
public void should_set_unrecognized_values_to_list_as_the_subcommand()
{
reset();
unparsedArgs.Add("wtf");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list);
}
[Fact]
public void should_default_to_list_as_the_subcommand()
{
reset();
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list);
}
[Fact]
public void should_handle_passing_in_an_empty_string()
{
reset();
unparsedArgs.Add(" ");
because();
configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list);
}
}
public class when_handling_validation : ChocolateySourceCommandSpecsBase
{
private Action because;
public override void Because()
{
because = () => command.handle_validation(configuration);
}
[Fact]
public void should_throw_when_command_is_not_list_and_name_is_not_set()
{
configuration.SourceCommand.Command = SourceCommandType.add;
configuration.SourceCommand.Name = "";
var errorred = false;
Exception error = null;
try
{
because();
}
catch (Exception ex)
{
errorred = true;
error = ex;
}
errorred.ShouldBeTrue();
error.ShouldNotBeNull();
error.ShouldBeType<ApplicationException>();
error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.SourceCommand.Command.to_string()));
}
[Fact]
public void should_continue_when_command_is_list_and_name_is_not_set()
{
configuration.SourceCommand.Command = SourceCommandType.list;
configuration.SourceCommand.Name = "";
because();
}
[Fact]
public void should_continue_when_command_is_not_list_and_name_is_set()
{
configuration.SourceCommand.Command = SourceCommandType.list;
configuration.SourceCommand.Name = "bob";
because();
}
}
public class when_noop_is_called : ChocolateySourceCommandSpecsBase
{
public override void Because()
{
command.noop(configuration);
}
[Fact]
public void should_call_service_noop()
{
configSettingsService.Verify(c => c.noop(configuration), Times.Once);
}
}
public class when_run_is_called : ChocolateySourceCommandSpecsBase
{
private Action because;
public override void Because()
{
because = () => command.run(configuration);
}
[Fact]
public void should_call_service_source_list_when_command_is_list()
{
configuration.SourceCommand.Command = SourceCommandType.list;
because();
configSettingsService.Verify(c => c.source_list(configuration), Times.Once);
}
[Fact]
public void should_call_service_source_add_when_command_is_add()
{
configuration.SourceCommand.Command = SourceCommandType.add;
because();
configSettingsService.Verify(c => c.source_add(configuration), Times.Once);
}
[Fact]
public void should_call_service_source_remove_when_command_is_remove()
{
configuration.SourceCommand.Command = SourceCommandType.remove;
because();
configSettingsService.Verify(c => c.source_remove(configuration), Times.Once);
}
[Fact]
public void should_call_service_source_disable_when_command_is_disable()
{
configuration.SourceCommand.Command = SourceCommandType.disable;
because();
configSettingsService.Verify(c => c.source_disable(configuration), Times.Once);
}
[Fact]
public void should_call_service_source_enable_when_command_is_enable()
{
configuration.SourceCommand.Command = SourceCommandType.enable;
because();
configSettingsService.Verify(c => c.source_enable(configuration), Times.Once);
}
}
public class when_list_is_called : ChocolateySourceCommandSpecsBase
{
private Action because;
public override void Because()
{
because = () => command.list(configuration);
}
[Fact]
public void should_call_service_source_list_when_command_is_list()
{
configuration.SourceCommand.Command = SourceCommandType.list;
because();
configSettingsService.Verify(c => c.source_list(configuration), Times.Once);
}
}
}
}
| 33.933002 | 175 | 0.534625 | [
"Apache-2.0"
] | Apteryx0/choco | src/chocolatey.tests/infrastructure.app/commands/ChocolateySourceCommandSpecs.cs | 13,679 | C# |
using CommunityBot.Extensions;
using CommunityBot.Features.Lists;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using static CommunityBot.Features.Lists.ListException;
namespace CommunityBot.Helpers
{
public static class ListHelper
{
public enum ListPermission
{
PRIVATE,
LIST,
READ,
PUBLIC
};
public static IReadOnlyList<String> PermissionStrings { get; } = new List<String>
{
"private",
"view only",
"read only",
"public"
};
public static IReadOnlyDictionary<string, ListPermission> ValidPermissions { get; } = new Dictionary<string, ListPermission>
{
{ "-p", ListPermission.PRIVATE },
{ "-l", ListPermission.LIST },
{ "-r", ListPermission.READ },
{ "-pu", ListPermission.PUBLIC }
};
public static IReadOnlyDictionary<string, Discord.Emoji> ControlEmojis { get; } = new Dictionary<string, Discord.Emoji>
{
{"up", new Discord.Emoji("⬆") },
{"down", new Discord.Emoji("⬇") },
{"check", new Discord.Emoji("✅") }
};
public struct UserInfo : IEquatable<object>
{
public ulong Id { get; }
public ulong[] RoleIds { get; }
public UserInfo(ulong id, ulong[] roleIds)
{
this.Id = id;
this.RoleIds = roleIds;
}
}
public enum ManagerMethodId
{
MODIFY,
GETPRIVATE,
GETPUBLIC,
CREATEPRIVATE,
CREATEPUBLIC,
ADD,
INSERT,
OUTPUTPRIVATE,
OUTPUTPUBLIC,
REMOVE,
REMOVELIST,
CLEAR
}
public static IReadOnlyList<ManagerMethod> GetValidOperations(ListManager manager)
{
var validOperations = new List<ManagerMethod>
{
new ManagerMethod("-m", ManagerMethodId.MODIFY, (userInfo, availableRoles, args) => manager.ModifyPermission(userInfo, availableRoles, args)),
new ManagerMethod("-g", ManagerMethodId.GETPRIVATE, (userInfo, availableRoles, args) => manager.GetAllPrivate(userInfo)),
new ManagerMethod("-gp", ManagerMethodId.GETPUBLIC, (userInfo, availableRoles, args) => manager.GetAllPublic(userInfo)),
new ManagerMethod("-c", ManagerMethodId.CREATEPRIVATE, (userInfo, availableRoles, args) => manager.CreateListPrivate(userInfo, args)),
new ManagerMethod("-cp", ManagerMethodId.CREATEPUBLIC, (userInfo, availableRoles, args) => manager.CreateListPublic(userInfo, args)),
new ManagerMethod("-a", ManagerMethodId.ADD, (userInfo, availableRoles, args) => manager.Add(userInfo, args)),
new ManagerMethod("-i", ManagerMethodId.INSERT, (userInfo, availableRoles, args) => manager.Insert(userInfo, args)),
new ManagerMethod("-l", ManagerMethodId.OUTPUTPRIVATE, (userInfo, availableRoles, args) => manager.OutputListPrivate(userInfo, args)),
new ManagerMethod("-lp", ManagerMethodId.OUTPUTPUBLIC, (userInfo, availableRoles, args) => manager.OutputListPublic(userInfo, args)),
new ManagerMethod("-r", ManagerMethodId.REMOVE, (userInfo, availableRoles, args) => manager.Remove(userInfo, args)),
new ManagerMethod("-rl", ManagerMethodId.REMOVELIST, (userInfo, availableRoles, args) => manager.RemoveList(userInfo, args)),
new ManagerMethod("-cl", ManagerMethodId.CLEAR, (userInfo, availableRoles, args) => manager.Clear(userInfo, args))
};
return validOperations;
}
public struct ManagerMethod : IEquatable<object>
{
public string Shortcut { get; set; }
public ManagerMethodId MethodId { get; set; }
public Func<UserInfo, Dictionary<string, ulong>, string[], ListOutput> Reference { get; set; }
public ManagerMethod(string shortcut, ManagerMethodId methodId, Func<UserInfo, Dictionary<string, ulong>, string[], ListOutput> reference)
{
Shortcut = shortcut;
MethodId = methodId;
Reference = reference;
}
}
public struct ListOutput : IEquatable<object>
{
public string outputString { get; set; }
public Discord.Embed outputEmbed { get; set; }
public bool listenForReactions { get; set; }
public ListPermission permission { get; set; }
}
public static ListOutput GetListOutput(string s)
{
return new ListOutput { outputString = s, permission = ListPermission.PUBLIC };
}
public static ListOutput GetListOutput(string s, ListPermission p)
{
return new ListOutput { outputString = s, permission = p };
}
public static ListOutput GetListOutput(Discord.Embed e)
{
return new ListOutput { outputEmbed = e, permission = ListPermission.PUBLIC };
}
public static ListOutput GetListOutput(Discord.Embed e, ListPermission p)
{
return new ListOutput { outputEmbed = e, permission = p };
}
public static string GetNounPlural(string s, int count)
{
return $"{s}{(count < 2 ? "" : "s")}";
}
public static SeperatedArray SeperateArray(string[] input)
{
return SeperateArray(input, input.Length - 1);
}
public static SeperatedArray SeperateArray(string[] input, params int[] indices)
{
var sa = new SeperatedArray();
sa.seperated = new string[indices.Length];
for (int i = 0; i < indices.Length; i++)
{
sa.seperated[i] = input[indices[i]];
}
sa.array = new string[input.Length - indices.Length];
var currentIndex = 0;
for (int i = 0; i < input.Length; i++)
{
if (!indices.Contains(i))
{
sa.array[currentIndex++] = input[i];
}
}
return sa;
}
public struct SeperatedArray : IEquatable<object>
{
public string[] seperated { get; set; }
public string[] array { get; set; }
}
}
}
| 38.872093 | 170 | 0.564313 | [
"MIT"
] | Charly6596/Community-Discord-BOT | CommunityBot/Helpers/ListHelper.cs | 6,694 | C# |
//
// EngineSettings.cs
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2006 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Net.BitTorrent.Client.Encryption;
using System.Reflection;
using System;
using System.Net;
namespace System.Net.BitTorrent.Client
{
/// <summary>
/// Represents the Settings which need to be passed to the engine
/// </summary>
[Serializable]
#if NETSTANDARD1_5
public class EngineSettings
#else
public class EngineSettings : ICloneable
#endif
{
#region Private Fields
private bool haveSupressionEnabled; // True if you want to enable have surpression
private EncryptionTypes allowedEncryption; // The minimum encryption level to use. "None" corresponds to no encryption.
private int listenPort; // The port to listen to incoming connections on
private int globalMaxConnections; // The maximum number of connections that can be opened
private int globalMaxHalfOpenConnections; // The maximum number of simultaenous 1/2 open connections
private int globalMaxDownloadSpeed; // The maximum combined download speed
private int globalMaxUploadSpeed; // The maximum combined upload speed
private int maxOpenStreams = 15; // The maximum number of simultaenous open filestreams
private int maxReadRate; // The maximum read rate from the harddisk (for all active torrentmanagers)
private int maxWriteRate; // The maximum write rate to the harddisk (for all active torrentmanagers)
private bool preferEncryption; // If encrypted and unencrypted connections are enabled, specifies if encryption should be chosen first
private IPEndPoint reportedEndpoint; // The IPEndpoint reported to the tracker
private string savePath; // The path that torrents will be downloaded to by default
#endregion Private Fields
#region Properties
public EncryptionTypes AllowedEncryption
{
get { return this.allowedEncryption; }
set { this.allowedEncryption = value; }
}
public bool HaveSupressionEnabled
{
get { return this.haveSupressionEnabled; }
set { this.haveSupressionEnabled = value; }
}
public int GlobalMaxConnections
{
get { return this.globalMaxConnections; }
set { this.globalMaxConnections = value; }
}
public int GlobalMaxHalfOpenConnections
{
get { return this.globalMaxHalfOpenConnections; }
set { this.globalMaxHalfOpenConnections = value; }
}
public int GlobalMaxDownloadSpeed
{
get { return this.globalMaxDownloadSpeed; }
set { this.globalMaxDownloadSpeed = value; }
}
public int GlobalMaxUploadSpeed
{
get { return this.globalMaxUploadSpeed; }
set { this.globalMaxUploadSpeed = value; }
}
[Obsolete("Use the constructor overload for ClientEngine which takes a port argument." +
"Alternatively just use the ChangeEndpoint method at a later stage")]
public int ListenPort
{
get { return this.listenPort; }
set { this.listenPort = value; }
}
public int MaxOpenFiles
{
get { return maxOpenStreams; }
set { maxOpenStreams = value; }
}
public int MaxReadRate
{
get { return maxReadRate; }
set { maxReadRate = value; }
}
public int MaxWriteRate
{
get { return maxWriteRate; }
set { maxWriteRate = value; }
}
public IPEndPoint ReportedAddress
{
get { return reportedEndpoint; }
set { reportedEndpoint = value; }
}
public bool PreferEncryption
{
get { return preferEncryption; }
set { preferEncryption = value; }
}
public string SavePath
{
get { return this.savePath; }
set { this.savePath = value; }
}
#endregion Properties
#region Defaults
private const bool DefaultEnableHaveSupression = false;
private const string DefaultSavePath = "";
private const int DefaultMaxConnections = 150;
private const int DefaultMaxDownloadSpeed = 0;
private const int DefaultMaxUploadSpeed = 0;
private const int DefaultMaxHalfOpenConnections = 5;
private const EncryptionTypes DefaultAllowedEncryption = EncryptionTypes.All;
private const int DefaultListenPort = 52138;
#endregion
#region Constructors
public EngineSettings()
: this(DefaultSavePath, DefaultListenPort, DefaultMaxConnections, DefaultMaxHalfOpenConnections,
DefaultMaxDownloadSpeed, DefaultMaxUploadSpeed, DefaultAllowedEncryption)
{
}
public EngineSettings(string defaultSavePath, int listenPort)
: this(defaultSavePath, listenPort, DefaultMaxConnections, DefaultMaxHalfOpenConnections, DefaultMaxDownloadSpeed, DefaultMaxUploadSpeed, DefaultAllowedEncryption)
{
}
public EngineSettings(string defaultSavePath, int listenPort, int globalMaxConnections)
: this(defaultSavePath, listenPort, globalMaxConnections, DefaultMaxHalfOpenConnections, DefaultMaxDownloadSpeed, DefaultMaxUploadSpeed, DefaultAllowedEncryption)
{
}
public EngineSettings(string defaultSavePath, int listenPort, int globalMaxConnections, int globalHalfOpenConnections)
: this(defaultSavePath, listenPort, globalMaxConnections, globalHalfOpenConnections, DefaultMaxDownloadSpeed, DefaultMaxUploadSpeed, DefaultAllowedEncryption)
{
}
public EngineSettings(string defaultSavePath, int listenPort, int globalMaxConnections, int globalHalfOpenConnections, int globalMaxDownloadSpeed, int globalMaxUploadSpeed, EncryptionTypes allowedEncryption)
{
this.globalMaxConnections = globalMaxConnections;
this.globalMaxDownloadSpeed = globalMaxDownloadSpeed;
this.globalMaxUploadSpeed = globalMaxUploadSpeed;
this.globalMaxHalfOpenConnections = globalHalfOpenConnections;
this.listenPort = listenPort;
this.allowedEncryption = allowedEncryption;
this.savePath = defaultSavePath;
}
#endregion
#region Methods
#if NETSTANDARD1_5
#else
object ICloneable.Clone()
{
return Clone();
}
#endif
public EngineSettings Clone()
{
return (EngineSettings)MemberwiseClone();
}
public override bool Equals(object obj)
{
EngineSettings settings = obj as EngineSettings;
return (settings == null) ? false : this.globalMaxConnections == settings.globalMaxConnections &&
this.globalMaxDownloadSpeed == settings.globalMaxDownloadSpeed &&
this.globalMaxHalfOpenConnections == settings.globalMaxHalfOpenConnections &&
this.globalMaxUploadSpeed == settings.globalMaxUploadSpeed &&
this.listenPort == settings.listenPort &&
this.allowedEncryption == settings.allowedEncryption &&
this.savePath == settings.savePath;
}
public override int GetHashCode()
{
return this.globalMaxConnections +
this.globalMaxDownloadSpeed +
this.globalMaxHalfOpenConnections +
this.globalMaxUploadSpeed +
this.listenPort.GetHashCode() +
this.allowedEncryption.GetHashCode() +
this.savePath.GetHashCode();
}
#endregion Methods
}
} | 38.272358 | 215 | 0.63197 | [
"MIT"
] | kanggaogang/BitTorrent | src/BitTorrent/Client/Settings/EngineSettings.cs | 9,415 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Structure.UIClass
{
internal class WindowSettings
{
internal double NormalHeight { get; set; }
internal double NormalWidth { get; set; }
internal double MaxHeight { get; set; }
internal double MaxWidth { get; set; }
}
}
| 19.142857 | 50 | 0.664179 | [
"MIT"
] | avinash1203/Structure | Structure/UIClass/WindowSettings.cs | 404 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipaySecurityRiskBackgroundQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipaySecurityRiskBackgroundQueryModel : AopObject
{
/// <summary>
/// params+用于背调查询的输入信息+用户传入
/// </summary>
[XmlElement("params")]
public string Params { get; set; }
/// <summary>
/// partner_name+唯一+作为标识调用者身份的字段+用户填入
/// </summary>
[XmlElement("partner_name")]
public string PartnerName { get; set; }
}
}
| 24.28 | 67 | 0.599671 | [
"MIT"
] | BJDIIL/DiiL | Sdk/AlipaySdk/Domain/AlipaySecurityRiskBackgroundQueryModel.cs | 673 | C# |
namespace G09projectenII.Models.ViewModels
{
public class ProfilePicViewModel
{
public int Size { get; set; }
public bool Rounded { get; set; }
public string ProfilePicPath { get; set; }
public string CssClass { get; set; }
}
}
| 24.818182 | 50 | 0.619048 | [
"MIT"
] | DanteDeRuwe/lorem-web | G09projectenII/Models/ViewModels/ProfilePicViewModel.cs | 275 | C# |
using Aveva.ApplicationFramework;
using Aveva.ApplicationFramework.Presentation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aveva.Presentation.AttributeBrowserAddin
{
class ExportModelAddin : IAddin
{
public string Description
{
get { return "Export PDMS model"; }
}
public string Name
{
get { return "ExportModel"; }
}
public void Start(ServiceManager serviceManager)
{
CommandManager commandManager = (CommandManager)serviceManager.GetService(typeof(CommandManager));
ExportModelCommand showCommand = new ExportModelCommand();
commandManager.Commands.Add(showCommand);
CommandBarManager commandBarManager = (CommandBarManager)serviceManager.GetService(typeof(CommandBarManager));
CommandBar commandBar = commandBarManager.CommandBars.AddCommandBar("Export Model");
commandBarManager.RootTools.AddButtonTool(showCommand.Key, "Export Model", null, showCommand);
commandBar.Tools.AddTool(showCommand.Key);
}
public void Stop()
{
}
}
}
| 26.846154 | 113 | 0.776504 | [
"Apache-2.0"
] | icedream2linxi/PDMS_ExportModel | ExportModel/ExportModelAddin.cs | 1,049 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace p04_LongestIncreasingSubsequence
{
class p04_LongestIncreasingSubsequence
{
static void Main(string[] args)
{
var sequence = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();
var longestSeq = FindLongestIncreasingSubsequence(sequence);
Console.WriteLine(string.Join(" ", longestSeq));
}
public static int[] FindLongestIncreasingSubsequence(int[] sequence)
{
int[] length = new int[sequence.Length];
int[] prev = new int[sequence.Length];
int maxLength = 0;
int lastIndex = -1;
for (int i = 0; i < sequence.Length; i++)
{
length[i] = 1;
prev[i] = -1;
for (int j = 0; j < i; j++)
{
if (sequence[j] < sequence[i] && length[j] >= length[i])
{
length[i] = 1 + length[j];
prev[i] = j;
}
}
if (length[i] > maxLength)
{
maxLength = length[i];
lastIndex = i;
}
}
var longestSeq = new List<int>();
for (int i = 0; i < maxLength; i++)
{
longestSeq.Add(sequence[lastIndex]);
lastIndex = prev[lastIndex];
}
longestSeq.Reverse();
return longestSeq.ToArray();
}
}
}
| 29.473684 | 147 | 0.455357 | [
"MIT"
] | Packo0/SoftUniProgrammingFundamentals | exercise/t09_Lists/p04_LongestIncreasingSubsequence/p04_LongestIncreasingSubsequence.cs | 1,682 | C# |
using System.ComponentModel.DataAnnotations;
using MediatR;
namespace WellBot.UseCases.Users.AuthenticateUser
{
/// <summary>
/// Refresh token command.
/// </summary>
public record RefreshTokenCommand : IRequest<TokenModel>
{
/// <summary>
/// User token.
/// </summary>
[Required]
public string Token { get; init; }
}
}
| 21.555556 | 60 | 0.603093 | [
"MIT"
] | ko-vasilev/WellBot | src/WellBot.UseCases/Users/AuthenticateUser/RefreshTokenCommand.cs | 390 | C# |
using BenchmarkDotNet.Attributes;
using GBX.NET.Engines.MwFoundations;
namespace GBX.NET.Benchmarks;
[MemoryDiagnoser]
public class LzoBenchmark : Benchmark
{
public MemoryStream MapCompressed { get; set; } = new();
public MemoryStream MapUncompressed { get; set; } = new();
[GlobalSetup]
public void Setup()
{
using var fs = File.OpenRead("Maps\\Community\\CCP#04 - ODYSSEY.Map.Gbx");
fs.CopyTo(MapCompressed);
MapCompressed.Seek(0, SeekOrigin.Begin);
GameBox.Decompress(MapCompressed, MapUncompressed);
MapCompressed.Seek(0, SeekOrigin.Begin);
MapUncompressed.Seek(0, SeekOrigin.Begin);
}
[Benchmark(Baseline = true)]
public CMwNod ParseMapCompressed()
{
MapCompressed.Position = 0;
return GameBox.ParseNode(MapCompressed)!;
}
[Benchmark]
public CMwNod ParseMapUncompressed()
{
MapUncompressed.Position = 0;
return GameBox.ParseNode(MapUncompressed)!;
}
}
| 24.487805 | 82 | 0.668327 | [
"Unlicense"
] | ArkadySK/gbx-net | Benchmarks/GBX.NET.Benchmarks/LzoBenchmark.cs | 1,006 | C# |
using Signum.Engine.Maps;
using Signum.Entities.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Utilities.Reflection;
namespace Signum.Engine.Basics;
public static class TypeLogic
{
public static Dictionary<PrimaryKey, Type> IdToType
{
get { return Schema.Current.typeCachesLazy.Value.IdToType; }
}
public static Dictionary<Type, PrimaryKey> TypeToId
{
get { return Schema.Current.typeCachesLazy.Value.TypeToId; }
}
public static Dictionary<Type, TypeEntity> TypeToEntity
{
get { return Schema.Current.typeCachesLazy.Value.TypeToEntity; }
}
public static Dictionary<TypeEntity, Type> EntityToType
{
get { return Schema.Current.typeCachesLazy.Value.EntityToType; }
}
public static Dictionary<Lite<TypeEntity>, Type> LiteToType
{
get { return Schema.Current.typeCachesLazy.Value.LiteToType; }
}
public static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!)));
}
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
Schema schema = Schema.Current;
sb.Include<TypeEntity>()
.WithQuery(() => t => new
{
Entity = t,
t.Id,
t.TableName,
t.CleanName,
t.ClassName,
t.Namespace,
});
schema.SchemaCompleted += () =>
{
var attributes = schema.Tables.Keys.Select(t => KeyValuePair.Create(t, t.GetCustomAttribute<EntityKindAttribute>(true))).ToList();
var errors = attributes.Where(a => a.Value == null).ToString(a => "Type {0} does not have an EntityTypeAttribute".FormatWith(a.Key.Name), "\r\n");
if (errors.HasText())
throw new InvalidOperationException(errors);
};
schema.Initializing += () =>
{
schema.typeCachesLazy.Load();
};
schema.typeCachesLazy = sb.GlobalLazy(() => new TypeCaches(schema), new InvalidateWith(typeof(TypeEntity)), Schema.Current.InvalidateMetadata);
TypeEntity.SetTypeEntityCallbacks(
t => TypeToEntity.GetOrThrow(t),
t => EntityToType.GetOrThrow(t),
t => LiteToType.GetOrThrow(t)
);
}
}
public static Dictionary<TypeEntity, Type> TryEntityToType(Replacements replacements)
{
return (from dn in Administrator.TryRetrieveAll<TypeEntity>(replacements)
join t in Schema.Current.Tables.Keys on dn.FullClassName equals (EnumEntity.Extract(t) ?? t).FullName
select (dn, t)).ToDictionary(a => a.dn, a => a.t);
}
public static SqlPreCommand? Schema_Synchronizing(Replacements replacements)
{
var schema = Schema.Current;
var isPostgres = schema.Settings.IsPostgres;
Dictionary<string, TypeEntity> should = GenerateSchemaTypes().ToDictionaryEx(s => s.TableName, "tableName in memory");
var currentList = Administrator.TryRetrieveAll<TypeEntity>(replacements);
{ //External entities are nt asked in SchemaSynchronizer
replacements.AskForReplacements(
currentList.Where(t => schema.IsExternalDatabase(ObjectName.Parse(t.TableName, isPostgres).Schema.Database)).Select(a => a.TableName).ToHashSet(),
should.Values.Where(t => schema.IsExternalDatabase(ObjectName.Parse(t.TableName, isPostgres).Schema.Database)).Select(a => a.TableName).ToHashSet(),
Replacements.KeyTables);
}
Dictionary<string, TypeEntity> current = ApplyReplacementsToOld(replacements,
currentList.ToDictionaryEx(c => c.TableName, "tableName in database"), Replacements.KeyTables);
{ //Temporal solution until applications are updated
var repeated =
should.Keys.Select(k => ObjectName.Parse(k, isPostgres)).GroupBy(a => a.Name).Where(a => a.Count() > 1).Select(a => a.Key).Concat(
current.Keys.Select(k => ObjectName.Parse(k, isPostgres)).GroupBy(a => a.Name).Where(a => a.Count() > 1).Select(a => a.Key)).ToList();
string simplify(string tn)
{
ObjectName name = ObjectName.Parse(tn, isPostgres);
return repeated.Contains(name.Name) ? name.ToString() : name.Name;
}
should = should.SelectDictionary(simplify, v => v);
current = current.SelectDictionary(simplify, v => v);
}
Table table = schema.Table<TypeEntity>();
using (replacements.WithReplacedDatabaseName())
return Synchronizer.SynchronizeScript(
Spacing.Double,
should,
current,
createNew: (tn, s) => table.InsertSqlSync(s),
removeOld: (tn, c) => table.DeleteSqlSync(c, t => t.CleanName == c.CleanName),
mergeBoth: (tn, s, c) =>
{
var originalCleanName = c.CleanName;
var originalFullName = c.FullClassName;
if (c.TableName != s.TableName)
{
var pc = ObjectName.Parse(c.TableName, isPostgres);
var ps = ObjectName.Parse(s.TableName, isPostgres);
if (!EqualsIgnoringDatabasePrefix(pc, ps))
{
c.TableName = ps.ToString();
}
}
c.CleanName = s.CleanName;
c.Namespace = s.Namespace;
c.ClassName = s.ClassName;
return table.UpdateSqlSync(c, t => t.CleanName == originalCleanName, comment: originalFullName);
});
}
static bool EqualsIgnoringDatabasePrefix(ObjectName pc, ObjectName ps) =>
ps.Name == pc.Name &&
pc.Schema.Name == ps.Schema.Name &&
Suffix(pc.Schema.Database?.Name) == Suffix(ps.Schema.Database?.Name);
static string? Suffix(string? name) => name.TryAfterLast("_") ?? name;
static Dictionary<string, O> ApplyReplacementsToOld<O>(this Replacements replacements, Dictionary<string, O> oldDictionary, string replacementsKey)
{
if (!replacements.ContainsKey(replacementsKey))
return oldDictionary;
Dictionary<string, string> dic = replacements[replacementsKey];
return oldDictionary.SelectDictionary(a => dic.TryGetC(a) ?? a, v => v);
}
internal static SqlPreCommand Schema_Generating()
{
Table table = Schema.Current.Table<TypeEntity>();
return GenerateSchemaTypes()
.Select((e, i) => table.InsertSqlSync(e, suffix: i.ToString()))
.Combine(Spacing.Simple)!
.PlainSqlCommand();
}
internal static List<TypeEntity> GenerateSchemaTypes()
{
var list = (from tab in Schema.Current.Tables.Values
let type = EnumEntity.Extract(tab.Type) ?? tab.Type
select new TypeEntity
{
TableName = tab.Name.ToString(),
CleanName = Reflector.CleanTypeName(type),
Namespace = type.Namespace!,
ClassName = type.Name,
}).ToList();
return list;
}
public static Dictionary<string, Type> NameToType
{
get { return Schema.Current.NameToType; }
}
public static Dictionary<Type, string> TypeToName
{
get { return Schema.Current.TypeToName; }
}
public static Type GetType(string cleanName)
{
return NameToType.GetOrThrow(cleanName, "Type {0} not found in the schema");
}
public static Type? TryGetType(string cleanName)
{
return NameToType.TryGetC(cleanName);
}
public static string GetCleanName(Type type)
{
return TypeToName.GetOrThrow(type, "Type {0} not found in the schema");
}
public static string? TryGetCleanName(Type type)
{
return TypeToName.TryGetC(type);
}
}
internal class TypeCaches
{
public readonly Dictionary<Type, TypeEntity> TypeToEntity;
public readonly Dictionary<TypeEntity, Type> EntityToType;
public readonly Dictionary<Lite<TypeEntity>, Type> LiteToType;
public readonly Dictionary<PrimaryKey, Type> IdToType;
public readonly Dictionary<Type, PrimaryKey> TypeToId;
public TypeCaches(Schema current)
{
TypeToEntity = EnumerableExtensions.JoinRelaxed(
Database.RetrieveAll<TypeEntity>(),
current.Tables.Keys,
t => t.FullClassName,
t => (EnumEntity.Extract(t) ?? t).FullName!,
(typeEntity, type) => (typeEntity, type),
"caching {0}".FormatWith(current.Table(typeof(TypeEntity)).Name)
).ToDictionary(a => a.type, a => a.typeEntity);
EntityToType = TypeToEntity.Inverse();
LiteToType = TypeToEntity.ToDictionaryEx(kvp => kvp.Value.ToLite(), kvp => kvp.Key);
TypeToId = TypeToEntity.SelectDictionary(k => k, v => v.Id);
IdToType = TypeToId.Inverse();
}
}
| 37.65625 | 165 | 0.577697 | [
"MIT"
] | goldenauge/framework | Signum.Engine/Basics/TypeLogic.cs | 9,640 | C# |
using System.Configuration;
namespace Lithnet.GoogleApps.MA
{
internal class ContactsApiElement : ConfigurationElement
{
private const string PropRateLimit = "rate-limit";
private const string PropPoolSize = "pool-size";
[ConfigurationProperty(ContactsApiElement.PropRateLimit, IsRequired = false, DefaultValue = 1500)]
public int RateLimit
{
get
{
return (int)this[ContactsApiElement.PropRateLimit];
}
set
{
this[ContactsApiElement.PropRateLimit] = value;
}
}
[ConfigurationProperty(ContactsApiElement.PropPoolSize, IsRequired = false, DefaultValue = 30)]
public int PoolSize
{
get
{
return (int)this[ContactsApiElement.PropPoolSize];
}
set
{
this[ContactsApiElement.PropPoolSize] = value;
}
}
}
} | 27.833333 | 106 | 0.555888 | [
"MIT"
] | leoerlandsson/googleapps-managementagent | src/Lithnet.GoogleApps.MA/ConfigSections/ContactsApiElement.cs | 1,004 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Toolbox.Extension.UI.Scaffolding.Converters
{
public class StepNumberToOkButtonVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (int.TryParse(value?.ToString(), out int stepNumber))
{
return stepNumber == 2 ? Visibility.Visible : Visibility.Hidden;
}
return Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
| 27.884615 | 103 | 0.648276 | [
"MIT"
] | ilchenkob/ef-core-toolbox | src/Toolbox.Extension/UI/Scaffolding/Converters/StepNumberToOkButtonVisibilityConverter.cs | 727 | C# |
// 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.
namespace Microsoft.Azure.Management.Sql.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Sql;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Import database parameters.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class ImportExtensionRequest
{
/// <summary>
/// Initializes a new instance of the ImportExtensionRequest class.
/// </summary>
public ImportExtensionRequest()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ImportExtensionRequest class.
/// </summary>
/// <param name="storageKeyType">The type of the storage key to use.
/// Possible values include: 'StorageAccessKey',
/// 'SharedAccessKey'</param>
/// <param name="storageKey">The storage key to use. If storage key
/// type is SharedAccessKey, it must be preceded with a "?."</param>
/// <param name="storageUri">The storage uri to use.</param>
/// <param name="administratorLogin">The name of the SQL
/// administrator.</param>
/// <param name="administratorLoginPassword">The password of the SQL
/// administrator.</param>
/// <param name="name">The name of the extension.</param>
/// <param name="type">The type of the extension.</param>
/// <param name="authenticationType">The authentication type. Possible
/// values include: 'SQL', 'ADPassword'</param>
public ImportExtensionRequest(StorageKeyType storageKeyType, string storageKey, string storageUri, string administratorLogin, string administratorLoginPassword, string name = default(string), string type = default(string), AuthenticationType? authenticationType = default(AuthenticationType?))
{
Name = name;
Type = type;
StorageKeyType = storageKeyType;
StorageKey = storageKey;
StorageUri = storageUri;
AdministratorLogin = administratorLogin;
AdministratorLoginPassword = administratorLoginPassword;
AuthenticationType = authenticationType;
CustomInit();
}
/// <summary>
/// Static constructor for ImportExtensionRequest class.
/// </summary>
static ImportExtensionRequest()
{
OperationMode = "Import";
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the name of the extension.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the type of the extension.
/// </summary>
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
/// <summary>
/// Gets or sets the type of the storage key to use. Possible values
/// include: 'StorageAccessKey', 'SharedAccessKey'
/// </summary>
[JsonProperty(PropertyName = "properties.storageKeyType")]
public StorageKeyType StorageKeyType { get; set; }
/// <summary>
/// Gets or sets the storage key to use. If storage key type is
/// SharedAccessKey, it must be preceded with a "?."
/// </summary>
[JsonProperty(PropertyName = "properties.storageKey")]
public string StorageKey { get; set; }
/// <summary>
/// Gets or sets the storage uri to use.
/// </summary>
[JsonProperty(PropertyName = "properties.storageUri")]
public string StorageUri { get; set; }
/// <summary>
/// Gets or sets the name of the SQL administrator.
/// </summary>
[JsonProperty(PropertyName = "properties.administratorLogin")]
public string AdministratorLogin { get; set; }
/// <summary>
/// Gets or sets the password of the SQL administrator.
/// </summary>
[JsonProperty(PropertyName = "properties.administratorLoginPassword")]
public string AdministratorLoginPassword { get; set; }
/// <summary>
/// Gets or sets the authentication type. Possible values include:
/// 'SQL', 'ADPassword'
/// </summary>
[JsonProperty(PropertyName = "properties.authenticationType")]
public AuthenticationType? AuthenticationType { get; set; }
/// <summary>
/// The type of import operation being performed. This is always
/// Import.
/// </summary>
[JsonProperty(PropertyName = "properties.operationMode")]
public static string OperationMode { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (StorageKey == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "StorageKey");
}
if (StorageUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "StorageUri");
}
if (AdministratorLogin == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "AdministratorLogin");
}
if (AdministratorLoginPassword == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "AdministratorLoginPassword");
}
}
}
}
| 38.6125 | 301 | 0.606021 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/SqlManagement/Management.Sql/Generated/Models/ImportExtensionRequest.cs | 6,178 | 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.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/34755", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public class ImageConverterTest
{
private readonly Image _image;
private readonly ImageConverter _imgConv;
private readonly ImageConverter _imgConvFrmTD;
private readonly string _imageStr;
private readonly byte[] _imageBytes;
public ImageConverterTest()
{
_image = Image.FromFile(Path.Combine("bitmaps", "TestImage.bmp"));
_imageStr = _image.ToString();
using (MemoryStream destStream = new MemoryStream())
{
_image.Save(destStream, _image.RawFormat);
_imageBytes = destStream.ToArray();
}
_imgConv = new ImageConverter();
_imgConvFrmTD = (ImageConverter)TypeDescriptor.GetConverter(_image);
}
[ConditionalTheory(Helpers.IsDrawingSupported)]
[InlineData("48x48_multiple_entries_4bit.ico")]
[InlineData("256x256_seven_entries_multiple_bits.ico")]
[InlineData("pngwithheight_icon.ico")]
public void ImageConverterFromIconTest(string name)
{
using (var icon = new Icon(Helpers.GetTestBitmapPath(name)))
{
Bitmap IconBitmap = (Bitmap)_imgConv.ConvertFrom(icon);
Assert.NotNull(IconBitmap);
Assert.Equal(32, IconBitmap.Width);
Assert.Equal(32, IconBitmap.Height);
Assert.Equal(new Size(32, 32), IconBitmap.Size);
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ImageWithOleHeader()
{
string path = Path.Combine("bitmaps", "TestImageWithOleHeader.bmp");
using (FileStream fileStream = File.Open(path, FileMode.Open))
{
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
var converter = new ImageConverter();
object image = converter.ConvertFrom(ms.ToArray());
Assert.NotNull(image);
}
}
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestCanConvertFrom()
{
Assert.True(_imgConv.CanConvertFrom(typeof(byte[])), "byte[] (no context)");
Assert.True(_imgConv.CanConvertFrom(null, typeof(byte[])), "byte[]");
Assert.True(_imgConv.CanConvertFrom(null, _imageBytes.GetType()), "_imageBytes.GetType()");
Assert.True(_imgConv.CanConvertFrom(typeof(Icon)), "Icon (no context)");
Assert.True(_imgConv.CanConvertFrom(null, typeof(Icon)), "Icon");
Assert.False(_imgConv.CanConvertFrom(null, typeof(string)), "string");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Rectangle)), "Rectangle");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Point)), "Point");
Assert.False(_imgConv.CanConvertFrom(null, typeof(PointF)), "PointF");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Size)), "Size");
Assert.False(_imgConv.CanConvertFrom(null, typeof(SizeF)), "SizeF");
Assert.False(_imgConv.CanConvertFrom(null, typeof(object)), "object");
Assert.False(_imgConv.CanConvertFrom(null, typeof(int)), "int");
Assert.False(_imgConv.CanConvertFrom(null, typeof(Metafile)), "Mefafile");
Assert.True(_imgConvFrmTD.CanConvertFrom(typeof(byte[])), "TD byte[] (no context)");
Assert.True(_imgConvFrmTD.CanConvertFrom(null, typeof(byte[])), "TD byte[]");
Assert.True(_imgConvFrmTD.CanConvertFrom(null, _imageBytes.GetType()), "TD _imageBytes.GetType()");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(string)), "TD string");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Rectangle)), "TD Rectangle");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Point)), "TD Point");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(PointF)), "TD PointF");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Size)), "TD Size");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(SizeF)), "TD SizeF");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(object)), "TD object");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(int)), "TD int");
Assert.False(_imgConvFrmTD.CanConvertFrom(null, typeof(Metafile)), "TD Metafile");
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestCanConvertTo()
{
Assert.True(_imgConv.CanConvertTo(typeof(string)), "stirng (no context)");
Assert.True(_imgConv.CanConvertTo(null, typeof(string)), "string");
Assert.True(_imgConv.CanConvertTo(null, _imageStr.GetType()), "_imageStr.GetType()");
Assert.True(_imgConv.CanConvertTo(typeof(byte[])), "byte[] (no context)");
Assert.True(_imgConv.CanConvertTo(null, typeof(byte[])), "byte[]");
Assert.True(_imgConv.CanConvertTo(null, _imageBytes.GetType()), "_imageBytes.GetType()");
Assert.False(_imgConv.CanConvertTo(null, typeof(Rectangle)), "Rectangle");
Assert.False(_imgConv.CanConvertTo(null, typeof(Point)), "Point");
Assert.False(_imgConv.CanConvertTo(null, typeof(PointF)), "PointF");
Assert.False(_imgConv.CanConvertTo(null, typeof(Size)), "Size");
Assert.False(_imgConv.CanConvertTo(null, typeof(SizeF)), "SizeF");
Assert.False(_imgConv.CanConvertTo(null, typeof(object)), "object");
Assert.False(_imgConv.CanConvertTo(null, typeof(int)), "int");
Assert.True(_imgConvFrmTD.CanConvertTo(typeof(string)), "TD string (no context)");
Assert.True(_imgConvFrmTD.CanConvertTo(null, typeof(string)), "TD string");
Assert.True(_imgConvFrmTD.CanConvertTo(null, _imageStr.GetType()), "TD _imageStr.GetType()");
Assert.True(_imgConvFrmTD.CanConvertTo(typeof(byte[])), "TD byte[] (no context)");
Assert.True(_imgConvFrmTD.CanConvertTo(null, typeof(byte[])), "TD byte[]");
Assert.True(_imgConvFrmTD.CanConvertTo(null, _imageBytes.GetType()), "TD _imageBytes.GetType()");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(Rectangle)), "TD Rectangle");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(Point)), "TD Point");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(PointF)), "TD PointF");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(Size)), "TD Size");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(SizeF)), "TD SizeF");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(object)), "TD object");
Assert.False(_imgConvFrmTD.CanConvertTo(null, typeof(int)), "TD int");
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertFrom()
{
Image newImage = (Image)_imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, _imageBytes);
Assert.Equal(_image.Height, newImage.Height);
Assert.Equal(_image.Width, newImage.Width);
Assert.Equal("(none)", _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, null, typeof(string)));
newImage = (Image)_imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, _imageBytes);
Assert.Equal(_image.Height, newImage.Height);
Assert.Equal(_image.Width, newImage.Width);
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertFrom_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom("System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, "System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new Bitmap(20, 20)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new Point(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new SizeF(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertFrom(null, CultureInfo.InvariantCulture, new object()));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom("System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, "System.Drawing.String"));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new Bitmap(20, 20)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new Point(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new SizeF(10, 10)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new object()));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_String()
{
Assert.Equal(_imageStr, (string)_imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(string)));
Assert.Equal(_imageStr, (string)_imgConv.ConvertTo(_image, typeof(string)));
Assert.Equal(_imageStr, (string)_imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(string)));
Assert.Equal(_imageStr, (string)_imgConvFrmTD.ConvertTo(_image, typeof(string)));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_ByteArray()
{
byte[] newImageBytes = (byte[])_imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, _imageBytes.GetType());
Assert.Equal(_imageBytes, newImageBytes);
newImageBytes = (byte[])_imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, _imageBytes.GetType());
Assert.Equal(_imageBytes, newImageBytes);
newImageBytes = (byte[])_imgConvFrmTD.ConvertTo(_image, _imageBytes.GetType());
Assert.Equal(_imageBytes, newImageBytes);
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_FromBitmapToByteArray()
{
Bitmap value = new Bitmap(64, 64);
ImageConverter converter = new ImageConverter();
byte[] converted = (byte[])converter.ConvertTo(value, typeof(byte[]));
Assert.NotNull(converted);
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void ConvertTo_ThrowsNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Rectangle)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, _image.GetType()));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Size)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Bitmap)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Point)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Metafile)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(object)));
Assert.Throws<NotSupportedException>(() => _imgConv.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(int)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Rectangle)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, _image.GetType()));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Size)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Bitmap)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Point)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(Metafile)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(object)));
Assert.Throws<NotSupportedException>(() => _imgConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _image, typeof(int)));
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestGetPropertiesSupported()
{
Assert.True(_imgConv.GetPropertiesSupported(), "GetPropertiesSupported()");
Assert.True(_imgConv.GetPropertiesSupported(null), "GetPropertiesSupported(null)");
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void TestGetProperties()
{
const int allPropertiesCount = 14; // Count of all properties in Image class.
const int browsablePropertiesCount = 7; // Count of browsable properties in Image class (BrowsableAttribute.Yes).
PropertyDescriptorCollection propsColl;
// Internally calls TypeDescriptor.GetProperties(typeof(Image), null), which returns all properties.
propsColl = _imgConv.GetProperties(null, _image, null);
Assert.Equal(allPropertiesCount, propsColl.Count);
// Internally calls TypeDescriptor.GetProperties(typeof(Image), new Attribute[] { BrowsableAttribute.Yes }).
propsColl = _imgConv.GetProperties(null, _image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
propsColl = _imgConv.GetProperties(_image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
// Returns all properties of Image class.
propsColl = TypeDescriptor.GetProperties(typeof(Image));
Assert.Equal(allPropertiesCount, propsColl.Count);
// Internally calls TypeDescriptor.GetProperties(typeof(Image), null), which returns all properties.
propsColl = _imgConvFrmTD.GetProperties(null, _image, null);
Assert.Equal(allPropertiesCount, propsColl.Count);
// Internally calls TypeDescriptor.GetProperties(typeof(Image), new Attribute[] { BrowsableAttribute.Yes }).
propsColl = _imgConvFrmTD.GetProperties(null, _image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
propsColl = _imgConvFrmTD.GetProperties(_image);
Assert.Equal(browsablePropertiesCount, propsColl.Count);
}
}
}
| 60.446565 | 145 | 0.671466 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Windows.Extensions/tests/System/Drawing/ImageConverterTests.cs | 15,837 | C# |
using Crash;
using System.Collections.Generic;
using System.Windows.Forms;
namespace CrashEdit
{
public sealed class ColoredFrameController : Controller
{
public ColoredFrameController(ColoredAnimationEntryController cutsceneanimationentrycontroller,OldFrame oldframe)
{
CutsceneAnimationEntryController = cutsceneanimationentrycontroller;
OldFrame = oldframe;
AddMenu("Export as OBJ", Menu_Export_OBJ);
InvalidateNode();
InvalidateNodeImage();
}
public override void InvalidateNode()
{
Node.Text = Crash.UI.Properties.Resources.FrameController_Text;
}
public override void InvalidateNodeImage()
{
Node.ImageKey = "arrow";
Node.SelectedImageKey = "arrowblue";
}
protected override Control CreateEditor()
{
OldModelEntry modelentry = CutsceneAnimationEntryController.EntryChunkController.NSFController.NSF.FindEID<OldModelEntry>(OldFrame.ModelEID);
Dictionary<int,TextureChunk> textures = new Dictionary<int,TextureChunk>();
foreach (OldModelStruct str in modelentry.Structs)
if (str is OldModelTexture tex && !textures.ContainsKey(tex.EID))
textures.Add(tex.EID,CutsceneAnimationEntryController.EntryChunkController.NSFController.NSF.FindEID<TextureChunk>(tex.EID));
return new UndockableControl(new OldAnimationEntryViewer(OldFrame,true,modelentry,textures));
}
public ColoredAnimationEntryController CutsceneAnimationEntryController { get; }
public OldFrame OldFrame { get; }
private void Menu_Export_OBJ()
{
OldModelEntry modelentry = CutsceneAnimationEntryController.EntryChunkController.NSFController.NSF.FindEID<OldModelEntry>(OldFrame.ModelEID);
if (modelentry == null)
{
throw new GUIException("The linked model entry could not be found.");
}
if (MessageBox.Show("Texture and color information will not be exported.\n\nContinue anyway?","Export as OBJ",MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
FileUtil.SaveFile(OldFrame.ToOBJ(modelentry),FileFilters.OBJ,FileFilters.Any);
}
}
}
| 41.508772 | 167 | 0.666103 | [
"MIT",
"BSD-3-Clause"
] | Hatry1337/CrashEdit | CrashEdit/Controllers/Animation/ColoredFrameController.cs | 2,366 | C# |
// Copyright Epic Games, Inc. All Rights Reserved.
// This file is automatically generated. Changes to this file may be overwritten.
namespace Epic.OnlineServices.AntiCheatClient
{
public class EndSessionOptions
{
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 8)]
internal struct EndSessionOptionsInternal : ISettable, System.IDisposable
{
private int m_ApiVersion;
public void Set(EndSessionOptions other)
{
if (other != null)
{
m_ApiVersion = AntiCheatClientInterface.EndsessionApiLatest;
}
}
public void Set(object other)
{
Set(other as EndSessionOptions);
}
public void Dispose()
{
}
}
} | 21.90625 | 110 | 0.74465 | [
"MIT"
] | CreepyAnt/EpicOnlineTransport | Mirror/Runtime/Transport/EpicOnlineTransport/EOSSDK/Generated/AntiCheatClient/EndSessionOptions.cs | 701 | C# |
namespace Nancy.Demo.PostSharp
{
using global::PostSharp.Aspects;
using System;
[Serializable]
public class CacheViewModelAttribute : MethodInterceptionAspect
{
/// <summary>
/// Cache name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Cache duration (in seconds).
/// </summary>
public int Duration { get; set; }
public override void OnInvoke(MethodInterceptionArgs args)
{
if (string.IsNullOrEmpty(this.Name))
{
throw new InvalidOperationException("Name property is null");
}
var viewModel = Cache.Get(this.Name);
if (viewModel == null)
{
base.OnInvoke(args);
Cache.Add(this.Name, args.ReturnValue, this.Duration);
}
else
{
var convertedVIewModel = (IViewModel)viewModel;
convertedVIewModel.Cached = true;
args.ReturnValue = convertedVIewModel;
}
}
}
} | 27.875 | 77 | 0.518386 | [
"MIT"
] | fagnercarvalho/Nancy.Demo.PostSharp | Nancy.Demo.PostSharp/CacheViewModelAttribute.cs | 1,117 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Globalization;
using Microsoft.AspNetCore.Testing;
namespace Microsoft.AspNetCore.Http;
public class PathStringTests
{
[Fact]
public void CtorThrows_IfPathDoesNotHaveLeadingSlash()
{
// Act and Assert
ExceptionAssert.ThrowsArgument(() => new PathString("hello"), "value", "The path in 'value' must start with '/'.");
}
[Fact]
public void Equals_EmptyPathStringAndDefaultPathString()
{
// Act and Assert
Assert.Equal(default(PathString), PathString.Empty);
Assert.Equal(default(PathString), PathString.Empty);
Assert.True(PathString.Empty == default(PathString));
Assert.True(default(PathString) == PathString.Empty);
Assert.True(PathString.Empty.Equals(default(PathString)));
Assert.True(default(PathString).Equals(PathString.Empty));
}
[Fact]
public void NotEquals_DefaultPathStringAndNonNullPathString()
{
// Arrange
var pathString = new PathString("/hello");
// Act and Assert
Assert.NotEqual(default(PathString), pathString);
}
[Fact]
public void NotEquals_EmptyPathStringAndNonNullPathString()
{
// Arrange
var pathString = new PathString("/hello");
// Act and Assert
Assert.NotEqual(pathString, PathString.Empty);
}
[Fact]
public void HashCode_CheckNullAndEmptyHaveSameHashcodes()
{
Assert.Equal(PathString.Empty.GetHashCode(), default(PathString).GetHashCode());
}
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
public void AddPathString_HandlesNullAndEmptyStrings(string appString, string concatString)
{
// Arrange
var appPath = new PathString(appString);
var concatPath = new PathString(concatString);
// Act
var result = appPath.Add(concatPath);
// Assert
Assert.False(result.HasValue);
}
[Theory]
[InlineData("", "/", "/")]
[InlineData("/", null, "/")]
[InlineData("/", "", "/")]
[InlineData("/", "/test", "/test")]
[InlineData("/myapp/", "/test/bar", "/myapp/test/bar")]
[InlineData("/myapp/", "/test/bar/", "/myapp/test/bar/")]
public void AddPathString_HandlesLeadingAndTrailingSlashes(string appString, string concatString, string expected)
{
// Arrange
var appPath = new PathString(appString);
var concatPath = new PathString(concatString);
// Act
var result = appPath.Add(concatPath);
// Assert
Assert.Equal(expected, result.Value);
}
[Fact]
public void ImplicitStringConverters_WorksWithAdd()
{
var scheme = "http";
var host = new HostString("localhost:80");
var pathBase = new PathString("/base");
var path = new PathString("/path");
var query = new QueryString("?query");
var fragment = new FragmentString("#frag");
var result = scheme + "://" + host + pathBase + path + query + fragment;
Assert.Equal("http://localhost:80/base/path?query#frag", result);
result = pathBase + path + query + fragment;
Assert.Equal("/base/path?query#frag", result);
result = path + "text";
Assert.Equal("/pathtext", result);
}
[Theory]
[InlineData("/test/path", "/TEST", true)]
[InlineData("/test/path", "/TEST/pa", false)]
[InlineData("/TEST/PATH", "/test", true)]
[InlineData("/TEST/path", "/test/pa", false)]
[InlineData("/test/PATH/path/TEST", "/TEST/path/PATH", true)]
public void StartsWithSegments_DoesACaseInsensitiveMatch(string sourcePath, string testPath, bool expectedResult)
{
var source = new PathString(sourcePath);
var test = new PathString(testPath);
var result = source.StartsWithSegments(test);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData("/test/path", "/TEST", true)]
[InlineData("/test/path", "/TEST/pa", false)]
[InlineData("/TEST/PATH", "/test", true)]
[InlineData("/TEST/path", "/test/pa", false)]
[InlineData("/test/PATH/path/TEST", "/TEST/path/PATH", true)]
public void StartsWithSegmentsWithRemainder_DoesACaseInsensitiveMatch(string sourcePath, string testPath, bool expectedResult)
{
var source = new PathString(sourcePath);
var test = new PathString(testPath);
var result = source.StartsWithSegments(test, out var remaining);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData("/test/path", "/TEST", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("/test/path", "/TEST", StringComparison.Ordinal, false)]
[InlineData("/test/path", "/TEST/pa", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("/test/path", "/TEST/pa", StringComparison.Ordinal, false)]
[InlineData("/TEST/PATH", "/test", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("/TEST/PATH", "/test", StringComparison.Ordinal, false)]
[InlineData("/TEST/path", "/test/pa", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("/TEST/path", "/test/pa", StringComparison.Ordinal, false)]
[InlineData("/test/PATH/path/TEST", "/TEST/path/PATH", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("/test/PATH/path/TEST", "/TEST/path/PATH", StringComparison.Ordinal, false)]
public void StartsWithSegments_DoesMatchUsingSpecifiedComparison(string sourcePath, string testPath, StringComparison comparison, bool expectedResult)
{
var source = new PathString(sourcePath);
var test = new PathString(testPath);
var result = source.StartsWithSegments(test, comparison);
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData("/test/path", "/TEST", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("/test/path", "/TEST", StringComparison.Ordinal, false)]
[InlineData("/test/path", "/TEST/pa", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("/test/path", "/TEST/pa", StringComparison.Ordinal, false)]
[InlineData("/TEST/PATH", "/test", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("/TEST/PATH", "/test", StringComparison.Ordinal, false)]
[InlineData("/TEST/path", "/test/pa", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("/TEST/path", "/test/pa", StringComparison.Ordinal, false)]
[InlineData("/test/PATH/path/TEST", "/TEST/path/PATH", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("/test/PATH/path/TEST", "/TEST/path/PATH", StringComparison.Ordinal, false)]
public void StartsWithSegmentsWithRemainder_DoesMatchUsingSpecifiedComparison(string sourcePath, string testPath, StringComparison comparison, bool expectedResult)
{
var source = new PathString(sourcePath);
var test = new PathString(testPath);
var result = source.StartsWithSegments(test, comparison, out var remaining);
Assert.Equal(expectedResult, result);
}
[Theory]
// unreserved
[InlineData("/abc123.-_~", "/abc123.-_~")]
// colon
[InlineData("/:", "/:")]
// at
[InlineData("/@", "/@")]
// sub-delims
[InlineData("/!$&'()*+,;=", "/!$&'()*+,;=")]
// reserved
[InlineData("/?#[]", "/%3F%23%5B%5D")]
// pct-encoding
[InlineData("/单行道", "/%E5%8D%95%E8%A1%8C%E9%81%93")]
// mixed
[InlineData("/index/单行道=(x*y)[abc]", "/index/%E5%8D%95%E8%A1%8C%E9%81%93=(x*y)%5Babc%5D")]
[InlineData("/index/单行道=(x*y)[abc]_", "/index/%E5%8D%95%E8%A1%8C%E9%81%93=(x*y)%5Babc%5D_")]
// encoded
[InlineData("/http%3a%2f%2f[foo]%3A5000/", "/http%3a%2f%2f%5Bfoo%5D%3A5000/")]
[InlineData("/http%3a%2f%2f[foo]%3A5000/%", "/http%3a%2f%2f%5Bfoo%5D%3A5000/%25")]
[InlineData("/http%3a%2f%2f[foo]%3A5000/%2", "/http%3a%2f%2f%5Bfoo%5D%3A5000/%252")]
[InlineData("/http%3a%2f%2f[foo]%3A5000/%2F", "/http%3a%2f%2f%5Bfoo%5D%3A5000/%2F")]
public void ToUriComponentEscapeCorrectly(string input, string expected)
{
var path = new PathString(input);
Assert.Equal(expected, path.ToUriComponent());
}
[Fact]
public void PathStringConvertsOnlyToAndFromString()
{
var converter = TypeDescriptor.GetConverter(typeof(PathString));
PathString result = (PathString)converter.ConvertFromInvariantString("/foo")!;
Assert.Equal("/foo", result.ToString());
Assert.Equal("/foo", converter.ConvertTo(result, typeof(string)));
Assert.True(converter.CanConvertFrom(typeof(string)));
Assert.False(converter.CanConvertFrom(typeof(int)));
Assert.False(converter.CanConvertFrom(typeof(bool)));
Assert.True(converter.CanConvertTo(typeof(string)));
Assert.False(converter.CanConvertTo(typeof(int)));
Assert.False(converter.CanConvertTo(typeof(bool)));
}
[Fact]
public void PathStringStaysEqualAfterAssignments()
{
PathString p1 = "/?";
string s1 = p1;
PathString p2 = s1;
Assert.Equal(p1, p2);
}
[Theory]
[InlineData("/a%2Fb")]
[InlineData("/a%2F")]
[InlineData("/%2fb")]
[InlineData("/a%2Fb/c%2Fd/e")]
public void StringFromUriComponentLeavesForwardSlashEscaped(string input)
{
var sut = PathString.FromUriComponent(input);
Assert.Equal(input, sut.Value);
}
[Theory]
[InlineData("/a%2Fb")]
[InlineData("/a%2F")]
[InlineData("/%2fb")]
[InlineData("/a%2Fb/c%2Fd/e")]
public void UriFromUriComponentLeavesForwardSlashEscaped(string input)
{
var uri = new Uri($"https://localhost:5001{input}");
var sut = PathString.FromUriComponent(uri);
Assert.Equal(input, sut.Value);
}
[Theory]
[InlineData("/a%20b", "/a b")]
[InlineData("/thisMustBeAVeryLongPath/SoLongThatItCouldActuallyBeLargerToTheStackAllocThresholdValue/PathsShorterToThisAllocateLessOnHeapByUsingStackAllocation/api/a%20b",
"/thisMustBeAVeryLongPath/SoLongThatItCouldActuallyBeLargerToTheStackAllocThresholdValue/PathsShorterToThisAllocateLessOnHeapByUsingStackAllocation/api/a b")]
public void StringFromUriComponentUnescapes(string input, string expected)
{
var sut = PathString.FromUriComponent(input);
Assert.Equal(expected, sut.Value);
}
[Theory]
[InlineData("/a%20b", "/a b")]
[InlineData("/thisMustBeAVeryLongPath/SoLongThatItCouldActuallyBeLargerToTheStackAllocThresholdValue/PathsShorterToThisAllocateLessOnHeapByUsingStackAllocation/api/a%20b",
"/thisMustBeAVeryLongPath/SoLongThatItCouldActuallyBeLargerToTheStackAllocThresholdValue/PathsShorterToThisAllocateLessOnHeapByUsingStackAllocation/api/a b")]
public void UriFromUriComponentUnescapes(string input, string expected)
{
var uri = new Uri($"https://localhost:5001{input}");
var sut = PathString.FromUriComponent(uri);
Assert.Equal(expected, sut.Value);
}
[Theory]
[InlineData("/a%2Fb")]
[InlineData("/a%2F")]
[InlineData("/%2fb")]
[InlineData("/%2Fb%20c")]
[InlineData("/a%2Fb%20c")]
[InlineData("/a%20b")]
[InlineData("/a%2Fb/c%2Fd/e%20f")]
[InlineData("/%E4%BD%A0%E5%A5%BD")]
public void FromUriComponentToUriComponent(string input)
{
var sut = PathString.FromUriComponent(input);
Assert.Equal(input, sut.ToUriComponent());
}
[Theory]
[MemberData(nameof(CharsToUnescape))]
[InlineData("/%E4%BD%A0%E5%A5%BD", "/你好")]
public void FromUriComponentUnescapesAllExceptForwardSlash(string input, string expected)
{
var sut = PathString.FromUriComponent(input);
Assert.Equal(expected, sut.Value);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void ExercisingStringFromUriComponentOnStackAllocLimit(int offset)
{
var path = "/";
var testString = new string('a', PathString.StackAllocThreshold + offset - path.Length);
var sut = PathString.FromUriComponent(path + testString);
Assert.Equal(PathString.StackAllocThreshold + offset, sut.Value!.Length);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void ExercisingUriFromUriComponentOnStackAllocLimit(int offset)
{
var localhost = "https://localhost:5001/";
var testString = new string('a', PathString.StackAllocThreshold + offset);
var sut = PathString.FromUriComponent(new Uri(localhost + testString));
Assert.Equal(PathString.StackAllocThreshold + offset + 1, sut.Value!.Length);
}
public static IEnumerable<object[]> CharsToUnescape
{
get
{
foreach (var item in Enumerable.Range(1, 127))
{
// %2F is '/' not escaped for paths
if (item != 0x2f)
{
var hexEscapedValue = "%" + item.ToString("x2", CultureInfo.InvariantCulture);
var expected = Uri.UnescapeDataString(hexEscapedValue);
yield return new object[] { "/a" + hexEscapedValue, "/a" + expected };
}
}
}
}
}
| 38.189655 | 175 | 0.652445 | [
"MIT"
] | 3ejki/aspnetcore | src/Http/Http.Abstractions/test/PathStringTests.cs | 13,312 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpReplIntellisense : AbstractInteractiveWindowTest
{
public CSharpReplIntellisense(VisualStudioInstanceFactory instanceFactory, ITestOutputHelper testOutputHelper)
: base(instanceFactory, testOutputHelper)
{
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyCompletionListOnEmptyTextAtTopLevel()
{
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("var", "public", "readonly", "goto");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifySharpRCompletionList()
{
VisualStudio.InteractiveWindow.InsertCode("#r \"");
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("System");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyCommitCompletionOnTopLevel()
{
VisualStudio.InteractiveWindow.InsertCode("pub");
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("public");
VisualStudio.SendKeys.Send(VirtualKey.Tab);
VisualStudio.InteractiveWindow.Verify.LastReplInput("public");
VisualStudio.SendKeys.Send(VirtualKey.Escape);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyCompletionListForAmbiguousParsingCases()
{
VisualStudio.InteractiveWindow.InsertCode(@"class C { }
public delegate R Del<T, R>(T arg);
Del<C, System");
VisualStudio.SendKeys.Send(VirtualKey.Period);
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("ArgumentException");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifySharpLoadCompletionList()
{
VisualStudio.InteractiveWindow.InsertCode("#load \"");
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("C:");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyNoCrashOnEnter()
{
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.SendKeys.Send("#help", VirtualKey.Enter, VirtualKey.Enter);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyCorrectIntellisenseSelectionOnEnter()
{
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.SendKeys.Send("TimeSpan.FromMin");
VisualStudio.SendKeys.Send(VirtualKey.Enter, "(0d)", VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForReplOutput("[00:00:00]");
}
[WpfFact]
public void VerifyCompletionListForLoadMembers()
{
using var temporaryTextFile = new TemporaryTextFile(
"c.csx",
"int x = 2; class Complex { public int goo() { return 4; } }");
temporaryTextFile.Create();
VisualStudio.InteractiveWindow.SubmitText(string.Format("#load \"{0}\"", temporaryTextFile.FullName));
VisualStudio.InteractiveWindow.InvokeCompletionList();
VisualStudio.InteractiveWindow.Verify.CompletionItemsExist("x", "Complex");
VisualStudio.SendKeys.Send(VirtualKey.Escape);
}
}
}
| 44.347368 | 161 | 0.679563 | [
"Apache-2.0"
] | DongchengWang/roslyn | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIntellisense.cs | 4,215 | C# |
using Dutiful.ViewModels.User;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dutiful.Services.Rules;
public interface IAccountRules : IAsyncDisposable
{
Task<UserViewModel?> GetUserAsync(HttpContext httpContext);
}
| 22.333333 | 63 | 0.814925 | [
"Apache-2.0"
] | Ftmco/Dutiful | Dutiful/Dutiful.Services/Rules/IAccountRules.cs | 337 | C# |
namespace Digimezzo.Foundation.Core.Win32
{
internal enum SHFileOperationReturnCode : ulong
{
/// <summary>
/// Operation completed successfully.
/// </summary>
SUCCESSFUL = 0L,
/// <summary>
/// The process cannot access the file because it is being used by another process.
/// </summary>
ERROR_SHARING_VIOLATION = 32L,
/// <summary>
/// MAX_PATH was exceeded during the operation.
/// </summary>
DE_ERROR_MAX = 0xB7,
/// <summary>
/// An unspecified error occurred on the destination.
/// </summary>
ERRORONDEST = 0x10000
}
} | 26.88 | 91 | 0.566964 | [
"MIT"
] | digimezzo/Foundation | Digimezzo.Foundation.Core/Win32/SHFileOperationReturnCode.cs | 674 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dal.Models.Entities;
namespace dal.Repositories.Abstract
{
public interface ICompanyRepository : IEntitiesRepository<Company>
{
IEnumerable<Company> GetByDealerId(int dealerId);
bool IsOwner(int id, int userId);
}
}
| 22.625 | 68 | 0.759669 | [
"MIT"
] | MarinTerentiev/mag | dal/Repositories/Abstract/ICompanyRepository.cs | 364 | C# |
/*
* Copyright 2013 Outercurve Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace PclUnit.Style.Xunit.Exceptions
{
/// <summary>
/// Exception thrown when code unexpectedly fails change a property.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
public class PropertyChangedException : AssertException
{
/// <summary>
/// Creates a new instance of the <see cref="PropertyChangedException"/> class. Call this constructor
/// when no exception was thrown.
/// </summary>
/// <param name="propertyName">The name of the property that was expected to be changed.</param>
public PropertyChangedException(string propertyName)
: base(String.Format(CultureInfo.CurrentCulture, "Assert.PropertyChanged failure: Property {0} was not set", propertyName)) { }
}
}
| 39.789474 | 139 | 0.71627 | [
"Apache-2.0"
] | Acidburn0zzz/PclUnit | Contrib/PclUnit.Style.Xunit/Exceptions/PropertyChangedException.cs | 1,514 | C# |
using System;
using System.Runtime.InteropServices;
using Windows.ApplicationModel.Resources;
namespace EAShow.Core.Helpers
{
internal static class ResourceExtensions
{
private static ResourceLoader _resLoader = new ResourceLoader();
public static string GetLocalized(this string resourceKey)
{
return _resLoader.GetString(resourceKey);
}
}
}
| 22.388889 | 72 | 0.707196 | [
"MIT"
] | MikelThief/EAShow | EAShow.Core/Helpers/ResourceExtensions.cs | 405 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClashRoyaleDashBoard
{
class ClashWar
{
public int SeasonId { get; set; }
public string CreatedDate { get; set; }
public List<ClashWarParticipant> Participants { get; set; }
public List<ClashWarStandings> Standings { get; set; }
}
}
| 20.6 | 67 | 0.674757 | [
"MIT"
] | rcornejo/clashRoyaleDashBoard | ClashRoyaleDashBoard/ClashRoyaleDashBoard/ClashWar.cs | 414 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osuTK;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Skinning;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableOsuJudgement : DrawableJudgement
{
protected SkinnableSprite Lighting;
private Bindable<Color4> lightingColour;
[Resolved]
private OsuConfigManager config { get; set; }
public DrawableOsuJudgement(JudgementResult result, DrawableHitObject judgedObject)
: base(result, judgedObject)
{
}
public DrawableOsuJudgement()
{
}
[BackgroundDependencyLoader]
private void load()
{
AddInternal(Lighting = new SkinnableSprite("lighting")
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Blending = BlendingParameters.Additive,
Depth = float.MaxValue,
Alpha = 0
});
}
public override void Apply(JudgementResult result, DrawableHitObject judgedObject)
{
base.Apply(result, judgedObject);
if (judgedObject?.HitObject is OsuHitObject osuObject)
{
Position = osuObject.StackedPosition;
Scale = new Vector2(osuObject.Scale);
}
}
protected override void PrepareForUse()
{
base.PrepareForUse();
lightingColour?.UnbindAll();
Lighting.ResetAnimation();
if (JudgedObject != null)
{
lightingColour = JudgedObject.AccentColour.GetBoundCopy();
lightingColour.BindValueChanged(colour => Lighting.Colour = Result.IsHit ? colour.NewValue : Color4.Transparent, true);
}
else
{
Lighting.Colour = Color4.White;
}
}
private double fadeOutDelay;
protected override double FadeOutDelay => fadeOutDelay;
protected override void ApplyHitAnimations()
{
bool hitLightingEnabled = config.Get<bool>(OsuSetting.HitLighting);
if (hitLightingEnabled)
{
JudgementBody.FadeIn().Delay(FadeInDuration).FadeOut(400);
Lighting.ScaleTo(0.8f).ScaleTo(1.2f, 600, Easing.Out);
Lighting.FadeIn(200).Then().Delay(200).FadeOut(1000);
}
else
{
JudgementBody.Alpha = 1;
}
fadeOutDelay = hitLightingEnabled ? 1400 : base.FadeOutDelay;
JudgementText?.TransformSpacingTo(Vector2.Zero).Then().TransformSpacingTo(new Vector2(14, 0), 1800, Easing.OutQuint);
base.ApplyHitAnimations();
}
}
}
| 31 | 136 | 0.574381 | [
"MIT"
] | AaqibAhamed/osu | osu.Game.Rulesets.Osu/Objects/Drawables/DrawableOsuJudgement.cs | 3,093 | C# |
using System.Collections.Immutable;
using TPP.ArgsParsing;
namespace TPP.Core.Commands
{
public readonly struct CommandContext
{
public Message Message { get; }
public IImmutableList<string> Args { get; }
public ArgsParser ArgsParser { get; }
public CommandContext(Message message, IImmutableList<string> args, ArgsParser argsParser)
{
Message = message;
Args = args;
ArgsParser = argsParser;
}
}
}
| 24.85 | 98 | 0.629779 | [
"MIT"
] | Dnantz/tpp-core | TPP.Core/Commands/CommandContext.cs | 497 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tigerbox.Exceptions;
using Tigerbox.Spec;
namespace Tigerbox.Objects
{
public class TigerSharedData
{
private int _credits;
public int Credits
{
get
{
return _credits;
}
}
private IConfigurationService _configuration;
private IJsonService _jsonService;
public TigerSharedData(IConfigurationService configuration, IJsonService service)
{
this._mutexList = new Mutex();
this._mutexCredit = new Mutex();
this._configuration = configuration;
this._jsonService = service;
this.LoadSharedData();
}
private IList<TigerMedia> _sharedList;
public IList<TigerMedia> SharedList
{
get
{
return _sharedList;
}
}
private Mutex _mutexList;
private Mutex _mutexCredit;
public void InsertNewMedia<V>(V media)
{
_mutexList.WaitOne();
object auxiliar = media;
_sharedList.Add((TigerMedia)auxiliar);
_mutexList.ReleaseMutex();
}
public V GetFirstMedia<V>()
{
object auxiliar = null;
if (_sharedList.Count > 0)
{
_mutexList.WaitOne();
auxiliar = _sharedList.ElementAt(0);
_sharedList.RemoveAt(0);
_mutexList.ReleaseMutex();
}
try
{
if (auxiliar==null)
{
throw new NoMediaSelectedException();
}
return (V)auxiliar;
}
catch
{
throw;
}
}
/// <summary>
/// Increase shared credit
/// </summary>
public void IncreaseCredit()
{
_mutexCredit.WaitOne();
_credits++;
_mutexCredit.ReleaseMutex();
}
/// <summary>
/// Decrease shared credit
/// </summary>
public void DecreaseCredit()
{
if (_credits == 0)
{
throw new NoCreditsException();
}
_mutexCredit.WaitOne();
_credits--;
_mutexCredit.ReleaseMutex();
}
/// <summary>
/// Save shared data into a json
/// </summary>
public void SaveSharedData()
{
string dataPath = GetSharedDataPath();
try
{
var sharedData = new Dictionary<string, object>();
sharedData.Add("Credits", _credits);
sharedData.Add("SharedList", _sharedList);
string data = _jsonService.SerializeJson(sharedData);
File.WriteAllText(dataPath, data);
}
catch
{
throw;
}
}
/// <summary>
/// Load shared data from json
/// </summary>
private void LoadSharedData()
{
string dataPath = GetSharedDataPath();
if (File.Exists(dataPath))
{
var data = File.ReadAllText(dataPath);
var sharedData = _jsonService.FileToJson<Dictionary<string, object>>(data);
_credits = Convert.ToInt32(sharedData["Credits"]);
_sharedList = ((Newtonsoft.Json.Linq.JArray)sharedData["SharedList"]).ToObject<List<TigerMedia>>();
}
else
{
_credits = 0;
_sharedList = new List<TigerMedia>();
}
}
/// <summary>
/// Get's the SharedDataPath setted into appConfig
/// </summary>
/// <returns>path</returns>
private string GetSharedDataPath()
{
string dataPath = _configuration.GetConfiguration<string>(Constants.SharedListPath);
if (string.IsNullOrWhiteSpace(dataPath))
{
throw new NoSharedListPathFound();
}
return dataPath;
}
}
}
| 24.372222 | 130 | 0.490084 | [
"MIT"
] | dynagita/Jukebox-Tigerbox | TigerboxPlayer/TigerSharedData.cs | 4,389 | C# |
using System.Threading.Tasks;
using AspnetboilerplateDemo.Models.TokenAuth;
using AspnetboilerplateDemo.Web.Controllers;
using Shouldly;
using Xunit;
namespace AspnetboilerplateDemo.Web.Tests.Controllers
{
public class HomeController_Tests: AspnetboilerplateDemoWebTestBase
{
[Fact]
public async Task Index_Test()
{
await AuthenticateAsync(null, new AuthenticateModel
{
UserNameOrEmailAddress = "admin",
Password = "123qwe"
});
//Act
var response = await GetResponseAsStringAsync(
GetUrl<HomeController>(nameof(HomeController.Index))
);
//Assert
response.ShouldNotBeNullOrEmpty();
}
}
} | 26.827586 | 71 | 0.618252 | [
"MIT"
] | arvindaspnetdev/AspNetZeroDemo | aspnet-core/test/AspnetboilerplateDemo.Web.Tests/Controllers/HomeController_Tests.cs | 780 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
namespace Paramore.Brighter.Tests.CommandProcessors.TestDoubles
{
internal class MyPostLoggingHandlerAttribute : RequestHandlerAttribute
{
public MyPostLoggingHandlerAttribute(int step, HandlerTiming timing)
: base(step, timing)
{
}
public override Type GetHandlerType()
{
return typeof(MyLoggingHandler<>);
}
}
} | 37.926829 | 77 | 0.760129 | [
"MIT"
] | DejanMilicic/Brighter | tests/Paramore.Brighter.Tests/CommandProcessors/TestDoubles/MyPostLoggingHandlerAttribute.cs | 1,564 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace a
{
class Program
{
static void Main(string[] args)
{
int s = int.Parse(Console.ReadLine());
double ans = 50.0 / s;
Console.WriteLine(ans);
}
}
}
| 17.555556 | 50 | 0.553797 | [
"MIT"
] | yu3mars/procon | atcoder/others/code_festival/2014/final/a/a/Program.cs | 318 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.