content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using DemoWebApi.Controllers.Client; using System; using Xunit; namespace IntegrationTests { public class BasicHealthIntegration { [Fact] public void TestNullHttpClientThrows() { Assert.Throws<ArgumentNullException>(() => new Values(null, new Uri("http://www.fonlow.com"))); } [Fact] public void TestNullUriThrows() { Assert.Throws<ArgumentNullException>(() => { using (var client = new System.Net.Http.HttpClient()) new Values(client, null); }); } } }
22.333333
107
0.563847
[ "MIT" ]
anthrax3/webapiclientgen
Tests/IntegrationTestsShared/BasicHealthIntegration.cs
605
C#
using System; using Xunit; using Exercism.Tests; public class WeighingMachineTests { [Fact] public void Set_weight_and_get_weight() { var wm = new WeighingMachine(); wm.InputWeight = 60m; Assert.Equal(60m, wm.InputWeight, precision: 3); } [Fact] public void Negative_weight_is_invalid() { var wm = new WeighingMachine(); Assert.Throws<ArgumentOutOfRangeException>(() => wm.InputWeight = -10); } [Fact] public void Get_us_display_weight_pounds() { var wm = new WeighingMachine(); wm.InputWeight = 60m; Assert.Equal(132, wm.USDisplayWeight.Pounds); } [Fact] public void Get_us_display_weight_ounces() { var wm = new WeighingMachine(); wm.InputWeight = 60m; Assert.Equal(4, wm.USDisplayWeight.Ounces); } [Fact] public void Input_pounds_and_get_us_display_weight_pounds() { var wm = new WeighingMachine(); wm.Units = Units.Pounds; wm.InputWeight = 175.5m; Assert.Equal(175, wm.USDisplayWeight.Pounds); } [Fact] public void Input_pounds_and_get_is_display_weight_ounces() { var wm = new WeighingMachine(); wm.Units = Units.Pounds; wm.InputWeight = 175.5m; Assert.Equal(8, wm.USDisplayWeight.Ounces); } [Fact] public void Apply_tare_adjustment_and_get_display_weight() { var wm = new WeighingMachine(); wm.InputWeight = 100; wm.TareAdjustment = 10; Assert.Equal(90, wm.DisplayWeight); } [Fact] public void Apply_negative_tare_adjustment() { var wm = new WeighingMachine(); wm.InputWeight = 100; wm.TareAdjustment = -10; Assert.Equal(110, wm.DisplayWeight); } [Fact] public void Apply_large_tare_adjustment_to_allow_negative_display_weight() { var wm = new WeighingMachine(); wm.InputWeight = 100; wm.TareAdjustment = 110; Assert.Equal(-10, wm.DisplayWeight); } }
24.795181
79
0.620505
[ "Apache-2.0" ]
ErikSchierboom/exercism
csharp/weighing-machine/WeighingMachineTests.cs
2,058
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Wyam.Common.Configuration; using Wyam.Common.Documents; using Wyam.Common.Meta; using Wyam.Common.Modules; using Wyam.Common.Execution; using Wyam.Core.Documents; using Wyam.Core.Meta; namespace Wyam.Core.Modules.Control { /// <summary> /// Splits a sequence of documents into multiple pages. /// </summary> /// <remarks> /// This module forms pages from the output documents of the specified modules. /// Each input document is cloned for each page and metadata related /// to the pages, including the sequence of documents for each page, /// is added to each clone. For example, if you have 2 input documents /// and the result of paging is 3 pages, this module will output 6 documents. /// </remarks> /// <example> /// If your input document is a Razor template for a blog archive, you can use /// Paginate to get pages of 10 blog posts each. If you have 50 blog posts, the /// result of the Paginate module will be 5 copies of your input archive template, /// one for each page. Your configuration file might look something like this: /// <code> /// Pipelines.Add("Posts", /// ReadFiles("*.md"), /// Markdown(), /// WriteFiles("html") /// ); /// /// Pipelines.Add("Archive", /// ReadFiles("archive.cshtml"), /// Paginate(10, /// Documents("Posts") /// ), /// Razor(), /// WriteFiles(string.Format("archive-{0}.html", @doc["CurrentPage"])) /// ); /// </code> /// </example> /// <metadata name="PageDocuments" type="IEnumerable&lt;IDocument&gt;">Contains all the documents for the current page.</metadata> /// <metadata name="CurrentPage" type="int">The index of the current page (1 based).</metadata> /// <metadata name="TotalPages" type="int">The total number of pages.</metadata> /// <metadata name="HasNextPage" type="bool">Whether there is another page after this one.</metadata> /// <metadata name="HasPreviousPage" type="bool">Whether there is another page before this one.</metadata> /// <category>Control</category> public class Paginate : IModule { private readonly int _pageSize; private readonly IModule[] _modules; private Func<IDocument, IExecutionContext, bool> _predicate; /// <summary> /// Partitions the result of the specified modules into the specified number of pages. The /// input documents to Paginate are used as the initial input documents to the specified modules. /// </summary> /// <param name="pageSize">The number of documents on each page.</param> /// <param name="modules">The modules to execute to get the documents to page.</param> /// <exception cref="System.ArgumentException"></exception> public Paginate(int pageSize, params IModule[] modules) { if (pageSize <= 0) { throw new ArgumentException(nameof(pageSize)); } _pageSize = pageSize; _modules = modules; } /// <summary> /// Limits the documents to be paged to those that satisfy the supplied predicate. /// </summary> /// <param name="predicate">A delegate that should return a <c>bool</c>.</param> public Paginate Where(DocumentConfig predicate) { Func<IDocument, IExecutionContext, bool> currentPredicate = _predicate; _predicate = currentPredicate == null ? (Func<IDocument, IExecutionContext, bool>)(predicate.Invoke<bool>) : ((x, c) => currentPredicate(x, c) && predicate.Invoke<bool>(x, c)); return this; } public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { ImmutableArray<ImmutableArray<IDocument>> partitions = Partition( context.Execute(_modules, inputs).Where(x => _predicate?.Invoke(x, context) ?? true).ToList(), _pageSize) .ToImmutableArray(); if (partitions.Length == 0) { return inputs; } return inputs.SelectMany(input => { return partitions.Select((x, i) => context.GetDocument(input, new Dictionary<string, object> { {Keys.PageDocuments, partitions[i]}, {Keys.CurrentPage, i + 1}, {Keys.TotalPages, partitions.Length}, {Keys.HasNextPage, partitions.Length > i + 1}, {Keys.HasPreviousPage, i != 0} }) ); }); } // Interesting discussion of partitioning at // http://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq // Note that this implementation won't work for very long sequences because it enumerates twice per chunk private static IEnumerable<ImmutableArray<T>> Partition<T>(IReadOnlyList<T> source, int size) { int pos = 0; while (source.Skip(pos).Any()) { yield return source.Skip(pos).Take(size).ToImmutableArray(); pos += size; } } } }
42.284615
134
0.592323
[ "MIT" ]
deanebarker/Wyam
src/core/Wyam.Core/Modules/Control/Paginate.cs
5,499
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SDPCRL.IBussiness; using SDPCRL.COM; using SDPCRL.CORE; namespace SDPCRL.BLL.BUS { public class BllBus { #region 私有属性 private IDALBus _bus = null; private IDALBus _dalBus { get { if(_bus==null) { _bus = (IDALBus)Activator.GetObject(typeof(IDALBus), string.Format("{0}://{1}:{2}/{3}", ServerInfo.ConnectType, ServerInfo.IPAddress, ServerInfo.Point, ServerInfo.DalServerName)); } return _bus; } } //private string _accoutId = string.Empty; #endregion #region 公开属性 public string AccoutId { get; set; } #endregion #region 构造函数 public BllBus() { } #endregion #region 受保护函数 protected virtual object ExecuteDalMethod(LibClientInfo clientInfo, string funcId, string method, LibTable[] libTables, params object[] param) { SDPCRL .COM.DalResult result= _dalBus.ExecuteDalMethod2(clientInfo , AccoutId,funcId, method,libTables , param); if (result.ErrorMsglst != null && result.ErrorMsglst.Count > 0) { throw new LibExceptionBase(result.ErrorMsglst[0].Message, result.ErrorMsglst[0].Stack); } return result; //return _dalBus.ExecuteDalMethod(AccoutId,funcId, method, param); } protected object ExecuteSysDalMethod(int language, string funcId, string method, params object[] param) { return _dalBus.ExecuteSysDalMethod(language , funcId, method, param); } protected object ExecuteSaveMethod(LibClientInfo clientInfo, string funcId, string method, LibTable[] param) { return _dalBus.ExecuteSaveMethod(clientInfo,AccoutId, funcId, method, param); } protected object ExecuteLogDalMethod(int language, string funcId, string method, params object[] param) { return _dalBus.ExecuteLogDalMethod(language, funcId, method, param); } #endregion } }
30.297297
150
0.600357
[ "Apache-2.0" ]
zyylonghai/BWYSDP
SDPCRL.BLL.BUS/BllBus.cs
2,278
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/directmanipulation.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 System.Runtime.Versioning; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.DirectX.UnitTests; /// <summary>Provides validation of the <see cref="IDirectManipulationManager3" /> struct.</summary> [SupportedOSPlatform("windows10.0")] public static unsafe partial class IDirectManipulationManager3Tests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDirectManipulationManager3" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IDirectManipulationManager3).GUID, Is.EqualTo(IID_IDirectManipulationManager3)); } /// <summary>Validates that the <see cref="IDirectManipulationManager3" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IDirectManipulationManager3>(), Is.EqualTo(sizeof(IDirectManipulationManager3))); } /// <summary>Validates that the <see cref="IDirectManipulationManager3" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IDirectManipulationManager3).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IDirectManipulationManager3" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IDirectManipulationManager3), Is.EqualTo(8)); } else { Assert.That(sizeof(IDirectManipulationManager3), Is.EqualTo(4)); } } }
38.075472
145
0.716056
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/DirectX/um/directmanipulation/IDirectManipulationManager3Tests.cs
2,020
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. namespace Develappers.BillomatNet.Types { /// <summary> /// Represents the tax of an invoice. /// </summary> public class InvoiceTax { public string Name { get; set; } public float Rate { get; set; } public float Amount { get; set; } public float AmountPlain { get; set; } public float AmountRounded { get; set; } public float AmountNet { get; set; } public float AmountNetPlain { get; set; } public float AmountNetRounded { get; set; } public float AmountGross { get; set; } public float AmountGrossPlain { get; set; } public float AmountGrossRounded { get; set; } } }
25.628571
71
0.628763
[ "MIT" ]
DevelappersGmbH/BillomatNet
Develappers.BillomatNet/Types/InvoiceTax.cs
899
C#
using System; using System.Collections.Generic; using System.Linq; namespace LinqLib.Sequence { /// <summary> /// Provides methods that return a subset of provided sequences. /// </summary> public static class Subset { #region Take Pattern /// <summary> /// Takes all elements that are in odd index position in the sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <returns>A sequence of all elements in odd index position.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeOdd<TSource>(this IEnumerable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); using (IEnumerator<TSource> iter = source.GetEnumerator()) while (iter.MoveNext()) { yield return iter.Current; if (!iter.MoveNext()) yield break; } } /// <summary> /// Takes all elements that are in even index position in the sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <returns>A sequence of all elements in even index position.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeEven<TSource>(this IEnumerable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Skip(1).TakeOdd(); } /// <summary> /// Takes all elements that are within the take/skip pattern provided. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="take">The number of elements to take.</param> /// <param name="skip">The number of elements to skip.</param> /// <returns>A sequence of all elements in matching the take/skip pattern provided.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> /// <exception cref="System.ArgumentException">take must and skip be larger than 0</exception> public static IEnumerable<TSource> TakePattern<TSource>(this IEnumerable<TSource> source, int take, int skip) { return TakePattern(source, 0, take, skip); } /// <summary> /// Takes all elements that are within the take/skip pattern provided. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="initialSkip">The number of elements to skip from the start of the sequence.</param> /// <param name="take">The number of elements to take.</param> /// <param name="skip">The number of elements to skip.</param> /// <returns>A sequence of all elements in matching the take/skip pattern provided.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> /// <exception cref="System.ArgumentException">take must and skip be larger than 0</exception> public static IEnumerable<TSource> TakePattern<TSource>(this IEnumerable<TSource> source, int initialSkip, int take, int skip) { if (source == null) throw Error.ArgumentNull("source"); if (take < 1) throw Error.InvalidTakeCount("take"); if (skip < 1) throw Error.InvalidSkipCount("skip"); using (IEnumerator<TSource> iter = source.GetEnumerator()) { for (int s = 0; s <= initialSkip; s++) if (!iter.MoveNext()) yield break; while (true) { for (int t = 0; t < take; t++) { yield return iter.Current; if (!iter.MoveNext()) yield break; } for (int s = 0; s < skip; s++) if (!iter.MoveNext()) yield break; } } } #endregion #region Take Before #region Plain /// <summary> /// Returns a all elements from the start of a sequence up to the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation stops.</param> /// <returns>All elements from the start of a sequence up to the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBefore<TSource>(this IEnumerable<TSource> source, TSource item) { return TakeBefore(source, item, new SimpleEqualityComparer<TSource>()); } /// <summary> /// Returns the Specified number of elements prior to the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation stops.</param> /// <param name="count">Number of elements to take.</param> /// <returns>The Specified number of elements prior to the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBefore<TSource>(this IEnumerable<TSource> source, TSource item, int count) { if (source == null) throw Error.ArgumentNull("source"); return source.Reverse().TakeAfter(item, count).Reverse(); } /// <summary> /// Returns a all elements from the start of a sequence up to and including the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The last element to take.</param> /// <returns>All elements from the start of a sequence up to and including the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndBefore<TSource>(this IEnumerable<TSource> source, TSource item) { return TakeSelfAndBefore(source, item, new SimpleEqualityComparer<TSource>()); } /// <summary> /// Returns the Specified number of elements prior to and including the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation stops.</param> /// <param name="count">Number of elements to take.</param> /// <returns>The Specified number of elements prior to and including the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndBefore<TSource>(this IEnumerable<TSource> source, TSource item, int count) { if (source == null) throw Error.ArgumentNull("source"); return source.Reverse().TakeSelfAndAfter(item, count).Reverse(); } #endregion #region Custom Compare /// <summary> /// Returns all elements from the start of a sequence up to the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation stops.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>All elements from the start of a sequence up to the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBefore<TSource>(this IEnumerable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (comparer == null) throw Error.ArgumentNull("comparer"); foreach (TSource current in source) { if (comparer.Equals(current, item)) break; yield return current; } } /// <summary> /// Returns the Specified number of elements prior to the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation stops.</param> /// <param name="count">Number of elements to take.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>The Specified number of elements prior to the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBefore<TSource>(this IEnumerable<TSource> source, TSource item, int count, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); return source.Reverse().TakeAfter(item, count, comparer).Reverse(); } /// <summary> /// Returns a all elements from the start of a sequence up to and including the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The last element to take.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>All elements from the start of a sequence up to and including the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndBefore<TSource>(this IEnumerable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (comparer == null) throw Error.ArgumentNull("comparer"); foreach (TSource current in source) { yield return current; if (comparer.Equals(current, item)) break; } } /// <summary> /// Returns the Specified number of elements prior to and including the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation stops.</param> /// <param name="count">Number of elements to take.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>The Specified number of elements prior to and including the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndBefore<TSource>(this IEnumerable<TSource> source, TSource item, int count, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); return source.Reverse().TakeSelfAndAfter(item, count, comparer).Reverse(); } #endregion #endregion #region Take After #region Plain /// <summary> /// Returns all elements after the specified item to end of sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts after.</param> /// <returns>All elements after the specified item to end of sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeAfter<TSource>(this IEnumerable<TSource> source, TSource item) { return TakeAfter(source, item, new SimpleEqualityComparer<TSource>()); } /// <summary> /// Returns the Specified number elements after the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts after.</param> /// <param name="count">Number of elements to take.</param> /// <returns>The Specified number elements after the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeAfter<TSource>(this IEnumerable<TSource> source, TSource item, int count) { return TakeAfter(source, item, count, new SimpleEqualityComparer<TSource>()); } /// <summary> /// Returns all elements after and including the specified item to end of sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts.</param> /// <returns>All elements after and including the specified item to end of sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndAfter<TSource>(this IEnumerable<TSource> source, TSource item) { return TakeSelfAndAfter(source, item, new SimpleEqualityComparer<TSource>()); } /// <summary> /// Returns the Specified number elements after and including the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts.</param> /// <param name="count">Number of elements to take.</param> /// <returns>The Specified number elements after and including the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndAfter<TSource>(this IEnumerable<TSource> source, TSource item, int count) { return TakeSelfAndAfter(source, item, count, new SimpleEqualityComparer<TSource>()); } #endregion #region Custom Compare /// <summary> /// Returns all elements after the specified item to end of sequence using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts after.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>All elements after the specified item to end of sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeAfter<TSource>(this IEnumerable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (comparer == null) throw Error.ArgumentNull("comparer"); bool found = false; foreach (TSource current in source) if (!found) found = comparer.Equals(current, item); else yield return current; } /// <summary> /// Returns the Specified number elements after the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts after.</param> /// <param name="count">Number of elements to take.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>The Specified number elements after the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeAfter<TSource>(this IEnumerable<TSource> source, TSource item, int count, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (comparer == null) throw Error.ArgumentNull("comparer"); bool found = false; foreach (TSource current in source) if (!found) found = comparer.Equals(current, item); else { yield return current; count--; if (count == 0) break; } } /// <summary> /// Returns all elements after and including the specified item to end of sequence using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>All elements after and including the specified item to end of sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndAfter<TSource>(this IEnumerable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (comparer == null) throw Error.ArgumentNull("comparer"); bool found = false; foreach (TSource current in source) { if (!found) found = comparer.Equals(current, item); if (found) yield return current; } } /// <summary> /// Returns the Specified number elements after and including the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation starts.</param> /// <param name="count">Number of elements to take.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>The Specified number elements after and including the specified item.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeSelfAndAfter<TSource>(this IEnumerable<TSource> source, TSource item, int count, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (comparer == null) throw Error.ArgumentNull("comparer"); bool found = false; foreach (TSource current in source) { if (!found) { found = comparer.Equals(current, item); if (!found) continue; } yield return current; count--; if (count < 0) break; } } #endregion #endregion #region Take Around #region Plain /// <summary> /// Takes the specified number of items before and after the the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation occurs.</param> /// <param name="count">number of items to take (total items will be up to count*2 + 1).</param> /// <returns>The specified number of items before and after the the specified item.</returns> public static IEnumerable<TSource> TakeAround<TSource>(this IEnumerable<TSource> source, TSource item, int count) { return TakeAround(source, item, count, count); } /// <summary> /// Takes the specified number of items before and after the the specified item. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation occurs.</param> /// <param name="before">number of items to take before the instance of item.</param> /// <param name="after">number of items to take after the instance of item.</param> /// <returns>The specified number of items before and after the the specified item.</returns> public static IEnumerable<TSource> TakeAround<TSource>(this IEnumerable<TSource> source, TSource item, int before, int after) { TSource[] sourceArr = source.ToArray(); foreach (TSource current in TakeSelfAndBefore(sourceArr, item, before)) yield return current; foreach (TSource current in TakeAfter(sourceArr, item, after)) yield return current; } #endregion #region Custom Compare /// <summary> /// Takes the specified number of items before and after the the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation occurs.</param> /// <param name="count">number of items to take (total items will be up to count*2 + 1).</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>The specified number of items before and after the the specified item.</returns> public static IEnumerable<TSource> TakeAround<TSource>(this IEnumerable<TSource> source, TSource item, int count, IEqualityComparer<TSource> comparer) { return TakeAround(source, item, count, count, comparer); } /// <summary> /// Takes the specified number of items before and after the the specified item using a custom comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="item">The element where operation occurs.</param> /// <param name="before">number of items to take before the instance of item.</param> /// <param name="after">number of items to take after the instance of item.</param> /// <param name="comparer">A IEqualityComparer comparer to use when evaluating items</param> /// <returns>The specified number of items before and after the the specified item.</returns> public static IEnumerable<TSource> TakeAround<TSource>(this IEnumerable<TSource> source, TSource item, int before, int after, IEqualityComparer<TSource> comparer) { TSource[] sourceArr = source.ToArray(); foreach (TSource current in TakeSelfAndBefore(sourceArr, item, before, comparer)) yield return current; foreach (TSource current in TakeAfter(sourceArr, item, after, comparer)) yield return current; } #endregion #endregion #region Take Top /// <summary> /// Returns a specified number of elements from the start of a sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="count">The number of elements to return.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified number of elements from the top of the input sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeTop<TSource>(this IEnumerable<TSource> source, int count) { if (source == null) throw Error.ArgumentNull("source"); foreach (TSource current in source) { if (count == 0) break; yield return current; count--; } } /// <summary> /// Returns a specified number of elements from the start of a sequence based on a predicate. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="count">The number of elements to return.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified number of elements from the top of the input sequence based on a predicate.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeTop<TSource>(this IEnumerable<TSource> source, int count, Func<TSource, bool> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Where(predicate).TakeTop(count); } /// <summary> /// Returns a specified percent of elements from the start of a sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="percent">The percent of elements to return. user 1.00 to indicate 100%.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified percent of elements from the top of the input sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeTopPercent<TSource>(this IEnumerable<TSource> source, double percent) // 1 == 100% { if (source == null) throw Error.ArgumentNull("source"); TSource[] sourceArr = source.ToArray(); int count = (int)(sourceArr.Count() * percent); return sourceArr.TakeTop(count); } /// <summary> /// Returns a specified percent of elements from the start of a sequence based on a predicate. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="percent">The percent of elements to return. user 1.00 to indicate 100%.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified percent of elements from the top of the input sequence based on a predicate.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeTopPercent<TSource>(this IEnumerable<TSource> source, double percent, Func<TSource, bool> predicate) // 1 == 100% { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); TSource[] sourceArr = source.ToArray(); int count = (int)(sourceArr.Length * percent); return sourceArr.TakeTop(count, predicate); } #endregion #region Take Bottom /// <summary> /// Returns a specified number of elements from the end of a sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="count">The number of elements to return.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified number of elements from the bottom of the input sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBottom<TSource>(this IEnumerable<TSource> source, int count) { if (source == null) throw Error.ArgumentNull("source"); return source.Reverse().TakeTop(count).Reverse(); } /// <summary> /// Returns a specified number of elements from the end of a sequence based on a predicate. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="count">The number of elements to return.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified number of elements from the bottom of the input sequence based on a predicate.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBottom<TSource>(this IEnumerable<TSource> source, int count, Func<TSource, bool> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Where(predicate).Reverse().TakeTop(count).Reverse(); } /// <summary> /// Returns a specified percent of elements from the end of a sequence. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="percent">The percent of elements to return. user 1.00 to indicate 100%.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified percent of elements from the bottom of the input sequence.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBottomPercent<TSource>(this IEnumerable<TSource> source, double percent) // 1 == 100% { if (source == null) throw Error.ArgumentNull("source"); TSource[] sourceArr = source.ToArray(); int count = (int)(sourceArr.Count() * percent); return sourceArr.Reverse().TakeTop(count).Reverse(); } /// <summary> /// Returns a specified percent of elements from the end of a sequence based on a predicate. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">The sequence to return elements from.</param> /// <param name="percent">The percent of elements to return. user 1.00 to indicate 100%.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <returns>An System.Collections.Generic.IEnumerable&lt;T&gt; that contains the specified percent of elements from the bottom of the input sequence based on a predicate.</returns> /// <exception cref="System.ArgumentNullException">source is null</exception> public static IEnumerable<TSource> TakeBottomPercent<TSource>(this IEnumerable<TSource> source, double percent, Func<TSource, bool> predicate) // 1 == 100% { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); TSource[] sourceArr = source.ToArray(); int count = (int)(sourceArr.Count() * percent); return sourceArr.Where(predicate).Reverse().TakeTop(count).Reverse(); } #endregion } }
47.137226
185
0.674719
[ "Apache-2.0" ]
AmirLiberman/LinqLib
src/LinqLib/Sequence/Subset.cs
32,291
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.FinancialManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Customer_Payment_Application_Rule_SetObjectIDType : INotifyPropertyChanged { private string typeField; private string valueField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string type { get { return this.typeField; } set { this.typeField = value; this.RaisePropertyChanged("type"); } } [XmlText] public string Value { get { return this.valueField; } set { this.valueField = value; this.RaisePropertyChanged("Value"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.163934
136
0.73354
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.FinancialManagement/Customer_Payment_Application_Rule_SetObjectIDType.cs
1,291
C#
/* * Payment Gateway API Specification. * * The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. * * The version of the OpenAPI document: 6.14.0.20201015.001 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ICurrencyConversionApiSync : IApiAccessor { #region Synchronous Operations /// <summary> /// Generate dynamic currency conversion transactions. /// </summary> /// <remarks> /// Sale, return and lookup exchange rate with dynamic currency conversion option. /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>ExchangeRateResponse</returns> ExchangeRateResponse GetExchangeRate (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null); /// <summary> /// Generate dynamic currency conversion transactions. /// </summary> /// <remarks> /// Sale, return and lookup exchange rate with dynamic currency conversion option. /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>ApiResponse of ExchangeRateResponse</returns> ApiResponse<ExchangeRateResponse> GetExchangeRateWithHttpInfo (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null); #endregion Synchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ICurrencyConversionApiAsync : IApiAccessor { #region Asynchronous Operations /// <summary> /// Generate dynamic currency conversion transactions. /// </summary> /// <remarks> /// Sale, return and lookup exchange rate with dynamic currency conversion option. /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>Task of ExchangeRateResponse</returns> System.Threading.Tasks.Task<ExchangeRateResponse> GetExchangeRateAsync (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null); /// <summary> /// Generate dynamic currency conversion transactions. /// </summary> /// <remarks> /// Sale, return and lookup exchange rate with dynamic currency conversion option. /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>Task of ApiResponse (ExchangeRateResponse)</returns> System.Threading.Tasks.Task<ApiResponse<ExchangeRateResponse>> GetExchangeRateAsyncWithHttpInfo (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ICurrencyConversionApi : ICurrencyConversionApiSync, ICurrencyConversionApiAsync { } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class CurrencyConversionApi : ICurrencyConversionApi { private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="CurrencyConversionApi"/> class. /// </summary> /// <returns></returns> public CurrencyConversionApi() : this((string) null) { } /// <summary> /// Initializes a new instance of the <see cref="CurrencyConversionApi"/> class. /// </summary> /// <returns></returns> public CurrencyConversionApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="CurrencyConversionApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public CurrencyConversionApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="CurrencyConversionApi"/> class /// using a Configuration object and client instance. /// </summary> /// <param name="client">The client interface for synchronous API access.</param> /// <param name="asyncClient">The client interface for asynchronous API access.</param> /// <param name="configuration">The configuration object.</param> public CurrencyConversionApi(Org.OpenAPITools.Client.ISynchronousClient client,Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) { if(client == null) throw new ArgumentNullException("client"); if(asyncClient == null) throw new ArgumentNullException("asyncClient"); if(configuration == null) throw new ArgumentNullException("configuration"); this.Client = client; this.AsynchronousClient = asyncClient; this.Configuration = configuration; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// The client for accessing this underlying API asynchronously. /// </summary> public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } /// <summary> /// The client for accessing this underlying API synchronously. /// </summary> public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.BasePath; } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Org.OpenAPITools.Client.IReadableConfiguration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Generate dynamic currency conversion transactions. Sale, return and lookup exchange rate with dynamic currency conversion option. /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>ExchangeRateResponse</returns> public ExchangeRateResponse GetExchangeRate (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null) { Org.OpenAPITools.Client.ApiResponse<ExchangeRateResponse> localVarResponse = GetExchangeRateWithHttpInfo(contentType, clientRequestId, apiKey, timestamp, exchangeRateRequest, messageSignature, region); return localVarResponse.Data; } /// <summary> /// Generate dynamic currency conversion transactions. Sale, return and lookup exchange rate with dynamic currency conversion option. /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>ApiResponse of ExchangeRateResponse</returns> public Org.OpenAPITools.Client.ApiResponse< ExchangeRateResponse > GetExchangeRateWithHttpInfo (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null) { // verify the required parameter 'contentType' is set if (contentType == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'contentType' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'clientRequestId' is set if (clientRequestId == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'clientRequestId' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'apiKey' is set if (apiKey == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'apiKey' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'timestamp' is set if (timestamp == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'timestamp' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'exchangeRateRequest' is set if (exchangeRateRequest == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'exchangeRateRequest' when calling CurrencyConversionApi->GetExchangeRate"); Org.OpenAPITools.Client.RequestOptions requestOptions = new Org.OpenAPITools.Client.RequestOptions(); String[] @contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] @accepts = new String[] { "application/json" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(@contentTypes); if (localVarContentType != null) requestOptions.HeaderParameters.Add("Content-Type", localVarContentType); var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(@accepts); if (localVarAccept != null) requestOptions.HeaderParameters.Add("Accept", localVarAccept); if (contentType != null) requestOptions.HeaderParameters.Add("Content-Type", Org.OpenAPITools.Client.ClientUtils.ParameterToString(contentType)); // header parameter if (clientRequestId != null) requestOptions.HeaderParameters.Add("Client-Request-Id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(clientRequestId)); // header parameter if (apiKey != null) requestOptions.HeaderParameters.Add("Api-Key", Org.OpenAPITools.Client.ClientUtils.ParameterToString(apiKey)); // header parameter if (timestamp != null) requestOptions.HeaderParameters.Add("Timestamp", Org.OpenAPITools.Client.ClientUtils.ParameterToString(timestamp)); // header parameter if (messageSignature != null) requestOptions.HeaderParameters.Add("Message-Signature", Org.OpenAPITools.Client.ClientUtils.ParameterToString(messageSignature)); // header parameter if (region != null) requestOptions.HeaderParameters.Add("Region", Org.OpenAPITools.Client.ClientUtils.ParameterToString(region)); // header parameter requestOptions.Data = exchangeRateRequest; // make the HTTP request var response = this.Client.Post< ExchangeRateResponse >("/exchange-rates", requestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception exception = this.ExceptionFactory("GetExchangeRate", response); if (exception != null) throw exception; } return response; } /// <summary> /// Generate dynamic currency conversion transactions. Sale, return and lookup exchange rate with dynamic currency conversion option. /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>Task of ExchangeRateResponse</returns> public async System.Threading.Tasks.Task<ExchangeRateResponse> GetExchangeRateAsync (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null) { Org.OpenAPITools.Client.ApiResponse<ExchangeRateResponse> localVarResponse = await GetExchangeRateAsyncWithHttpInfo(contentType, clientRequestId, apiKey, timestamp, exchangeRateRequest, messageSignature, region); return localVarResponse.Data; } /// <summary> /// Generate dynamic currency conversion transactions. Sale, return and lookup exchange rate with dynamic currency conversion option. /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="contentType">Content type.</param> /// <param name="clientRequestId">A client-generated ID for request tracking and signature creation, unique per request. This is also used for idempotency control. We recommend 128-bit UUID format.</param> /// <param name="apiKey">Key given to merchant after boarding associating their requests with the appropriate app in Apigee.</param> /// <param name="timestamp">Epoch timestamp in milliseconds in the request from a client system. Used for Message Signature generation and time limit (5 mins).</param> /// <param name="exchangeRateRequest">Accepted request types: DCCExchangeRateRequest and DynamicPricingExchangeRateRequest.</param> /// <param name="messageSignature">Used to ensure the request has not been tampered with during transmission. The Message-Signature is the Base64 encoded HMAC hash (SHA256 algorithm with the API Secret as the key.) For more information, refer to the supporting documentation on the Developer Portal. (optional)</param> /// <param name="region">Indicates the region where the client wants the transaction to be processed. This will override the default processing region identified for the client. Available options are argentina, brazil, germany, india and northamerica. Region specific store setup and APIGEE boarding is required in order to use an alternate region for processing. (optional)</param> /// <returns>Task of ApiResponse (ExchangeRateResponse)</returns> public async System.Threading.Tasks.Task<Org.OpenAPITools.Client.ApiResponse<ExchangeRateResponse>> GetExchangeRateAsyncWithHttpInfo (string contentType, string clientRequestId, string apiKey, long timestamp, ExchangeRateRequest exchangeRateRequest, string messageSignature = null, string region = null) { // verify the required parameter 'contentType' is set if (contentType == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'contentType' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'clientRequestId' is set if (clientRequestId == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'clientRequestId' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'apiKey' is set if (apiKey == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'apiKey' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'timestamp' is set if (timestamp == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'timestamp' when calling CurrencyConversionApi->GetExchangeRate"); // verify the required parameter 'exchangeRateRequest' is set if (exchangeRateRequest == null) throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'exchangeRateRequest' when calling CurrencyConversionApi->GetExchangeRate"); Org.OpenAPITools.Client.RequestOptions requestOptions = new Org.OpenAPITools.Client.RequestOptions(); String[] @contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] @accepts = new String[] { "application/json" }; foreach (var _contentType in @contentTypes) requestOptions.HeaderParameters.Add("Content-Type", _contentType); foreach (var accept in @accepts) requestOptions.HeaderParameters.Add("Accept", accept); if (contentType != null) requestOptions.HeaderParameters.Add("Content-Type", Org.OpenAPITools.Client.ClientUtils.ParameterToString(contentType)); // header parameter if (clientRequestId != null) requestOptions.HeaderParameters.Add("Client-Request-Id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(clientRequestId)); // header parameter if (apiKey != null) requestOptions.HeaderParameters.Add("Api-Key", Org.OpenAPITools.Client.ClientUtils.ParameterToString(apiKey)); // header parameter if (timestamp != null) requestOptions.HeaderParameters.Add("Timestamp", Org.OpenAPITools.Client.ClientUtils.ParameterToString(timestamp)); // header parameter if (messageSignature != null) requestOptions.HeaderParameters.Add("Message-Signature", Org.OpenAPITools.Client.ClientUtils.ParameterToString(messageSignature)); // header parameter if (region != null) requestOptions.HeaderParameters.Add("Region", Org.OpenAPITools.Client.ClientUtils.ParameterToString(region)); // header parameter requestOptions.Data = exchangeRateRequest; // make the HTTP request var response = await this.AsynchronousClient.PostAsync<ExchangeRateResponse>("/exchange-rates", requestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception exception = this.ExceptionFactory("GetExchangeRate", response); if (exception != null) throw exception; } return response; } } }
73.98818
390
0.709812
[ "MIT" ]
mrtristan/DotNet
src/Org.OpenAPITools/Api/CurrencyConversionApi.cs
31,297
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> //------------------------------------------------------------------------------ namespace DAO.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DAO.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Bag_Labels_{0}_{1}_{2}.docx. /// </summary> public static string BagLabelBaseFilename { get { return ResourceManager.GetString("BagLabelBaseFilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Writing {0} {1} to file {2}. /// </summary> public static string CountWritingMsg { get { return ResourceManager.GetString("CountWritingMsg", resourceCulture); } } /// <summary> /// Looks up a localized string similar to *.bak????.*. /// </summary> public static string db_backup_glob { get { return ResourceManager.GetString("db_backup_glob", resourceCulture); } } /// <summary> /// Looks up a localized string similar to hll_data.litedb. /// </summary> public static string db_filename { get { return ResourceManager.GetString("db_filename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Donor_List_{0}_{1}_{2}.xlsx. /// </summary> public static string DonorListBasefilename { get { return ResourceManager.GetString("DonorListBasefilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Donor List, {0}, {1}, {2}. /// </summary> public static string DonorListHeader { get { return ResourceManager.GetString("DonorListHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} {1} DL {2}. /// </summary> public static string DonorListWorksheetName { get { return ResourceManager.GetString("DonorListWorksheetName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Successfully created file {0} . /// </summary> public static string FileCreationSuccessMsg { get { return ResourceManager.GetString("FileCreationSuccessMsg", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An error occurred trying to work with file {0}. ///The error message was {1}. Here is the stack trace: {2}. /// </summary> public static string FileExceptionErrorMsg { get { return ResourceManager.GetString("FileExceptionErrorMsg", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Gift_Labels_{0}_{1}_{2}.docx. /// </summary> public static string GiftLabelBaseFilename { get { return ResourceManager.GetString("GiftLabelBaseFilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please include gift receipt.. /// </summary> public static string GiftReceiptRequest { get { return ResourceManager.GetString("GiftReceiptRequest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Master_List_{0}_{1}_{2}.xlsx. /// </summary> public static string MasterListBasefilename { get { return ResourceManager.GetString("MasterListBasefilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Master List, {0}, {1}, {2}. /// </summary> public static string MasterListHeader { get { return ResourceManager.GetString("MasterListHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} {1} ML {2}. /// </summary> public static string MasterListWorksheetName { get { return ResourceManager.GetString("MasterListWorksheetName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to --- NO DATA ---. /// </summary> public static string NoDataMsg { get { return ResourceManager.GetString("NoDataMsg", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &amp;Bpage &amp;P of &amp;N. /// </summary> public static string PageNumbers { get { return ResourceManager.GetString("PageNumbers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Participant_List_{0}_{1}.xlsx. /// </summary> public static string ParticipantListBasefilename { get { return ResourceManager.GetString("ParticipantListBasefilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Participant List, {0}, {1}. /// </summary> public static string ParticipantListHeader { get { return ResourceManager.GetString("ParticipantListHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Participant_Summary_Labels_{0}.docx. /// </summary> public static string ParticipantSummaryLabelsBaseFilename { get { return ResourceManager.GetString("ParticipantSummaryLabelsBaseFilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Postcard_Labels_{0}_{1}.docx. /// </summary> public static string PostcardLabelBaseFilename { get { return ResourceManager.GetString("PostcardLabelBaseFilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Thanksgiving_Delivery_List_{0}.xlsx. /// </summary> public static string ThanksgivingDeliveryBaseFilename { get { return ResourceManager.GetString("ThanksgivingDeliveryBaseFilename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Thanksgiving Delivery List, {0}. /// </summary> public static string ThanksgivingDeliveryListHeader { get { return ResourceManager.GetString("ThanksgivingDeliveryListHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Thanksgiving Delivery List. /// </summary> public static string ThanksgivingDeliveryListSheetName { get { return ResourceManager.GetString("ThanksgivingDeliveryListSheetName", resourceCulture); } } } }
37.650735
169
0.557172
[ "MIT" ]
tonyrein/HolidayLabelsAndLists_Public
DAO/Properties/Resources.Designer.cs
10,243
C#
namespace WebPlex.Services.Impl.Configuration { using WebPlex.Core.Domain.Settings; public interface IContactFormSettingsService : IDbSettingsService<ContactFormSettings> {} }
35.8
90
0.837989
[ "MIT" ]
m-sadegh-sh/WebPlex
src/WebPlex.Services/Impl/Configuration/IContactFormSettingsService.cs
181
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Packaging.Core; namespace Sleet { /// <summary> /// A virtual catalog that is not written to the feed. /// </summary> public class VirtualCatalog : ISleetService, IRootIndex, IAddRemovePackages { private readonly SleetContext _context; public string Name { get; } = "VirtualCatalog"; /// <summary> /// Example: virtualcatalog/index.json /// </summary> public string RootIndex { get { var rootURI = UriUtility.GetPath(CatalogBaseURI, "index.json"); return UriUtility.GetRelativePath(_context.Source.BaseURI, rootURI); } } /// <summary> /// Catalog index.json file /// </summary> public ISleetFile RootIndexFile => _context.Source.Get(RootIndex); /// <summary> /// Example: http://tempuri.org/virtualcatalog/ /// </summary> public Uri CatalogBaseURI { get; } public VirtualCatalog(SleetContext context) : this(context, UriUtility.GetPath(context.Source.BaseURI, "virtualcatalog/")) { } public VirtualCatalog(SleetContext context, Uri catalogBaseURI) { _context = context; CatalogBaseURI = catalogBaseURI; } public Task AddPackageAsync(PackageInput packageInput) { return AddPackagesAsync(new[] { packageInput }); } public Task RemovePackageAsync(PackageIdentity package) { // No actions needed return Task.FromResult(true); } public Task RemovePackagesAsync(IEnumerable<PackageIdentity> packages) { // No actions needed return Task.FromResult(true); } public Task FetchAsync() { return RootIndexFile.FetchAsync(_context.Log, _context.Token); } public Task AddPackagesAsync(IEnumerable<PackageInput> packageInputs) { // Create package details page var tasks = packageInputs.Select(e => new Func<Task>(() => CreateDetailsForAdd(e))); return TaskUtils.RunAsync(tasks, useTaskRun: true, token: CancellationToken.None); } private async Task CreateDetailsForAdd(PackageInput packageInput) { // Create a a details page and assign it to the input var nupkgUri = packageInput.GetNupkgUri(_context); var iconUri = packageInput.GetIconUri(_context); var packageDetails = await CatalogUtility.CreatePackageDetailsAsync(packageInput, CatalogBaseURI, nupkgUri, iconUri, _context.CommitId, writeFileList: false); packageInput.PackageDetails = packageDetails; } public Task ApplyOperationsAsync(SleetOperations operations) { return OperationsUtility.ApplyAddRemoveAsync(this, operations); } public Task PreLoadAsync(SleetOperations operations) { return Task.FromResult(true); } } }
31.382353
170
0.614808
[ "MIT" ]
biohazard999/Sleet
src/SleetLib/Services/VirtualCatalog.cs
3,201
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Model\EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Mac OSEnterprise Wi Fi Configuration. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class MacOSEnterpriseWiFiConfiguration : MacOSWiFiConfiguration { ///<summary> /// The MacOSEnterpriseWiFiConfiguration constructor ///</summary> public MacOSEnterpriseWiFiConfiguration() { this.ODataType = "microsoft.graph.macOSEnterpriseWiFiConfiguration"; } /// <summary> /// Gets or sets eap type. /// Extensible Authentication Protocol (EAP). Indicates the type of EAP protocol set on the Wi-Fi endpoint (router). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "eapType", Required = Newtonsoft.Json.Required.Default)] public EapType? EapType { get; set; } /// <summary> /// Gets or sets eap fast configuration. /// EAP-FAST Configuration Option when EAP-FAST is the selected EAP Type. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "eapFastConfiguration", Required = Newtonsoft.Json.Required.Default)] public EapFastConfiguration? EapFastConfiguration { get; set; } /// <summary> /// Gets or sets trusted server certificate names. /// Trusted server certificate names when EAP Type is configured to EAP-TLS/TTLS/FAST or PEAP. This is the common name used in the certificates issued by your trusted certificate authority (CA). If you provide this information, you can bypass the dynamic trust dialog that is displayed on end users devices when they connect to this Wi-Fi network. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "trustedServerCertificateNames", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<string> TrustedServerCertificateNames { get; set; } /// <summary> /// Gets or sets authentication method. /// Authentication Method when EAP Type is configured to PEAP or EAP-TTLS. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "authenticationMethod", Required = Newtonsoft.Json.Required.Default)] public WiFiAuthenticationMethod? AuthenticationMethod { get; set; } /// <summary> /// Gets or sets inner authentication protocol for eap ttls. /// Non-EAP Method for Authentication (Inner Identity) when EAP Type is EAP-TTLS and Authenticationmethod is Username and Password. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "innerAuthenticationProtocolForEapTtls", Required = Newtonsoft.Json.Required.Default)] public NonEapAuthenticationMethodForEapTtlsType? InnerAuthenticationProtocolForEapTtls { get; set; } /// <summary> /// Gets or sets outer identity privacy temporary value. /// Enable identity privacy (Outer Identity) when EAP Type is configured to EAP-TTLS, EAP-FAST or PEAP. This property masks usernames with the text you enter. For example, if you use 'anonymous', each user that authenticates with this Wi-Fi connection using their real username is displayed as 'anonymous'. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "outerIdentityPrivacyTemporaryValue", Required = Newtonsoft.Json.Required.Default)] public string OuterIdentityPrivacyTemporaryValue { get; set; } /// <summary> /// Gets or sets root certificate for server validation. /// Trusted Root Certificate for Server Validation when EAP Type is configured to EAP-TLS/TTLS/FAST or PEAP. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "rootCertificateForServerValidation", Required = Newtonsoft.Json.Required.Default)] public MacOSTrustedRootCertificate RootCertificateForServerValidation { get; set; } /// <summary> /// Gets or sets identity certificate for client authentication. /// Identity Certificate for client authentication when EAP Type is configured to EAP-TLS, EAP-TTLS (with Certificate Authentication), or PEAP (with Certificate Authentication). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "identityCertificateForClientAuthentication", Required = Newtonsoft.Json.Required.Default)] public MacOSCertificateProfileBase IdentityCertificateForClientAuthentication { get; set; } } }
58.228261
355
0.690312
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/MacOSEnterpriseWiFiConfiguration.cs
5,357
C#
using System; namespace _8._1.StringManipulator { class Program { static void Main(string[] args) { string text = Console.ReadLine(); string input = Console.ReadLine(); while (input != "End") { string[] command = input.Split(); string action = command[0]; switch (action) { case "Translate": text = text.Replace(char.Parse(command[1]), char.Parse(command[2])); Console.WriteLine(text); break; case "Includes": if (text.Contains(command[1])) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } break; case "Start": if (text.StartsWith(command[1])) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } break; case "Lowercase": if (text != null) { text = text.ToLower(); Console.WriteLine(text); ; } break; case "FindIndex": int charIndex = text.LastIndexOf(command[1]); if (charIndex >= 0) { Console.WriteLine(charIndex); } break; case "Remove": text = text.Remove(int.Parse(command[1]), int.Parse(command[2])); Console.WriteLine(text); break; } input = Console.ReadLine(); } } } }
33.606061
92
0.317403
[ "MIT" ]
DeyanDanailov/SoftUniCSharpFundamentals
repos/9.1.StringManipulator1/Program.cs
2,220
C#
#pragma warning disable 649 using System; using System.Diagnostics; using UnityEngine; using UnityEngine.UI; using Debug = UnityEngine.Debug; namespace TriLib { namespace Samples { /// <summary> /// Represents the asset loader UI component. /// </summary> [RequireComponent(typeof(AssetDownloader))] public class AssetLoaderWindow : MonoBehaviour { /// <summary> /// Class singleton. /// </summary> public static AssetLoaderWindow Instance { get; private set; } /// <summary> /// Turn on this field to enable async loading. /// </summary> public bool Async; /// <summary> /// "Load local asset button" reference. /// </summary> [SerializeField] private UnityEngine.UI.Button _loadLocalAssetButton; /// <summary> /// "Load remote button" reference. /// </summary> [SerializeField] private UnityEngine.UI.Button _loadRemoteAssetButton; /// <summary> /// "Spinning text" reference. /// </summary> [SerializeField] private UnityEngine.UI.Text _spinningText; /// <summary> /// "Transparency dropdown" reference. /// </summary> [SerializeField] private UnityEngine.UI.Dropdown _transparencyModeDropdown; /// <summary> /// "Shading dropdown" reference. /// </summary> [SerializeField] private UnityEngine.UI.Dropdown _shadingDropdown; /// <summary> /// "Spin X toggle" reference. /// </summary> [SerializeField] private UnityEngine.UI.Toggle _spinXToggle; /// <summary> /// "Spin Y toggle" reference. /// </summary> [SerializeField] private UnityEngine.UI.Toggle _spinYToggle; /// <summary> /// "Reset rotation button" reference. /// </summary> [SerializeField] private UnityEngine.UI.Button _resetRotationButton; /// <summary> /// "Stop animation button" reference. /// </summary> [SerializeField] private UnityEngine.UI.Button _stopAnimationButton; /// <summary> /// "Animations text" reference. /// </summary> [SerializeField] private UnityEngine.UI.Text _animationsText; /// <summary> /// "Blend Shapes text" reference. /// </summary> [SerializeField] private UnityEngine.UI.Text _blendShapesText; /// <summary> /// "Animations scroll rect "reference. /// </summary> [SerializeField] private UnityEngine.UI.ScrollRect _animationsScrollRect; /// <summary> /// "Blend Shapes scroll rect "reference. /// </summary> [SerializeField] private UnityEngine.UI.ScrollRect _blendShapesScrollRect; /// <summary> /// "Animations scroll rect container" reference. /// </summary> [SerializeField] private Transform _containerTransform; /// <summary> /// "Blend Shapes scroll rect container" reference. /// </summary> [SerializeField] private Transform _blendShapesContainerTransform; /// <summary> /// <see cref="AnimationText"/> prefab reference. /// </summary> [SerializeField] private AnimationText _animationTextPrefab; /// <summary> /// <see cref="BlendShapeControl"/> prefab reference. /// </summary> [SerializeField] private BlendShapeControl _blendShapeControlPrefab; /// <summary> /// "Background (gradient) canvas" reference. /// </summary> [SerializeField] private Canvas _backgroundCanvas; /// <summary> /// Loaded Game Object reference. /// </summary> private GameObject _rootGameObject; /// <summary> /// Total loading time Text reference. /// </summary> [SerializeField] private Text _loadingTimeText; /// <summary> /// WebGL drag and drop Text reference. /// </summary> [SerializeField] private Text _dragAndDropText; /// <summary> /// Loading timer. /// </summary> private Stopwatch _loadingTimer = new Stopwatch(); /// <summary> /// Handles events from <see cref="AnimationText"/>. /// </summary> /// <param name="animationName">Chosen animation name.</param> public void HandleEvent(string animationName) { _rootGameObject.GetComponent<Animation>().Play(animationName); _stopAnimationButton.interactable = true; } /// <summary> /// Handles events from <see cref="BlendShapeControl"/>. /// </summary> /// <param name="skinnedMeshRenderer">Skinned Mesh Renderer to set the blend shape.</param> /// <param name="index">Blend Shape index.</param> /// <param name="value">Blend Shape value.</param> public void HandleBlendEvent(SkinnedMeshRenderer skinnedMeshRenderer, int index, float value) { skinnedMeshRenderer.SetBlendShapeWeight(index, value); } /// <summary> /// Destroys all objects in the containers. /// </summary> public void DestroyItems() { foreach (Transform innerTransform in _containerTransform) { Destroy(innerTransform.gameObject); } foreach (Transform innerTransform in _blendShapesContainerTransform) { Destroy(innerTransform.gameObject); } } /// <summary> /// Initializes variables. /// </summary> protected void Awake() { _loadLocalAssetButton.onClick.AddListener(LoadLocalAssetButtonClick); _loadRemoteAssetButton.onClick.AddListener(LoadRemoteAssetButtonClick); _stopAnimationButton.onClick.AddListener(StopAnimationButtonClick); _resetRotationButton.onClick.AddListener(ResetRotationButtonClick); #if !UNITY_EDITOR && UNITY_WEBGL _dragAndDropText.gameObject.SetActive(true); #endif HideControls(); Instance = this; } /// <summary> /// Spins the loaded Game Object if options are enabled. /// </summary> protected void Update() { if (_rootGameObject != null) { _rootGameObject.transform.Rotate(_spinXToggle.isOn ? 20f * Time.deltaTime : 0f, _spinYToggle.isOn ? -20f * Time.deltaTime : 0f, 0f, Space.World); } } /// <summary> /// Hides user controls. /// </summary> private void HideControls() { _loadLocalAssetButton.interactable = true; _loadRemoteAssetButton.interactable = true; _spinningText.gameObject.SetActive(false); _spinXToggle.gameObject.SetActive(false); _spinYToggle.gameObject.SetActive(false); _resetRotationButton.gameObject.SetActive(false); _stopAnimationButton.gameObject.SetActive(false); _animationsText.gameObject.SetActive(false); _animationsScrollRect.gameObject.SetActive(false); _blendShapesText.gameObject.SetActive(false); _blendShapesScrollRect.gameObject.SetActive(false); } /// <summary> /// Handles "Load local asset button" click event and tries to load an asset at chosen path. /// </summary> private void LoadLocalAssetButtonClick() { #if !UNITY_EDITOR && UNITY_WEBGL ErrorDialog.Instance.ShowDialog("Please drag and drop your model files into the browser window."); #else var fileOpenDialog = FileOpenDialog.Instance; fileOpenDialog.Title = "Please select a File"; fileOpenDialog.Filter = AssetLoaderBase.GetSupportedFileExtensions() + ";*.zip;"; #if !UNITY_EDITOR && UNITY_WINRT && (NET_4_6 || NETFX_CORE || NET_STANDARD_2_0) fileOpenDialog.ShowFileOpenDialog(delegate (byte[] fileBytes, string filename) { LoadInternal(filename, fileBytes); #else fileOpenDialog.ShowFileOpenDialog(delegate (string filename) { LoadInternal(filename); #endif } ); #endif } //#if !UNITY_EDITOR && UNITY_WEBGL /// <summary> /// Loads the model from browser files. /// </summary> /// <param name="filesCount">Browser files count.</param> public void LoadFromBrowserFiles(int filesCount) { LoadInternal(null, null, filesCount); } //#endif /// <summary> /// Executes the post model loading steps. /// </summary> private void FullPostLoadSetup() { if (_rootGameObject != null) { PostLoadSetup(); ShowLoadingTime(); } else { HideLoadingTime(); } } /// <summary> /// Displays a <see cref="System.Exception"/>. /// </summary> /// <param name="exception"><see cref="System.Exception"/> to display.</param> private void HandleException(Exception exception) { if (_rootGameObject != null) { Destroy(_rootGameObject); } _rootGameObject = null; HideLoadingTime(); ErrorDialog.Instance.ShowDialog(exception.ToString()); } /// <summary> /// Checks for a valid model (a model should contain meshes to be displayed). /// </summary> /// <param name="assetLoader"><see cref="AssetLoaderBase"/> used to load the model.</param> private void CheckForValidModel(AssetLoaderBase assetLoader) { if (assetLoader.MeshData == null || assetLoader.MeshData.Length == 0) { throw new Exception("File contains no meshes"); } } /// <summary> /// Loads a model from the given filename, file bytes or browser files. /// </summary> /// <param name="filename">Model filename.</param> /// <param name="fileBytes">Model file bytes.</param> /// <param name="browserFilesCount">Browser files count.</param> private void LoadInternal(string filename, byte[] fileBytes = null, int browserFilesCount = -1) { PreLoadSetup(); var assetLoaderOptions = GetAssetLoaderOptions(); if (!Async) { using (var assetLoader = new AssetLoader()) { assetLoader.OnMetadataProcessed += AssetLoader_OnMetadataProcessed; try { #if !UNITY_EDITOR && UNITY_WEBGL if (browserFilesCount >= 0) { _rootGameObject = assetLoader.LoadFromBrowserFilesWithTextures(browserFilesCount, assetLoaderOptions); } else #endif if (fileBytes != null && fileBytes.Length > 0) { _rootGameObject = assetLoader.LoadFromMemoryWithTextures(fileBytes, FileUtils.GetFileExtension(filename), assetLoaderOptions, _rootGameObject); } else if (!string.IsNullOrEmpty(filename)) { _rootGameObject = assetLoader.LoadFromFileWithTextures(filename, assetLoaderOptions); } else { throw new Exception("File not selected"); } CheckForValidModel(assetLoader); } catch (Exception exception) { HandleException(exception); } } FullPostLoadSetup(); } else { using (var assetLoader = new AssetLoaderAsync()) { assetLoader.OnMetadataProcessed += AssetLoader_OnMetadataProcessed; try { #if !UNITY_EDITOR && UNITY_WEBGL if (browserFilesCount >= 0) { assetLoader.LoadFromBrowserFilesWithTextures(browserFilesCount, assetLoaderOptions, null, delegate (GameObject loadedGameObject) { CheckForValidModel(assetLoader); _rootGameObject = loadedGameObject; FullPostLoadSetup(); }); } else #endif if (fileBytes != null && fileBytes.Length > 0) { assetLoader.LoadFromMemoryWithTextures(fileBytes, FileUtils.GetFileExtension(filename), assetLoaderOptions, null, delegate (GameObject loadedGameObject) { CheckForValidModel(assetLoader); _rootGameObject = loadedGameObject; FullPostLoadSetup(); }); } else if (!string.IsNullOrEmpty(filename)) { assetLoader.LoadFromFileWithTextures(filename, assetLoaderOptions, null, delegate (GameObject loadedGameObject) { CheckForValidModel(assetLoader); _rootGameObject = loadedGameObject; FullPostLoadSetup(); }); } else { throw new Exception("File not selected"); } } catch (Exception exception) { HandleException(exception); } } } } /// <summary> /// Shows the total asset loading time. /// </summary> private void ShowLoadingTime() { _loadingTimeText.text = string.Format("Loading time: {0:00}:{1:00}.{2:00}", _loadingTimer.Elapsed.Minutes, _loadingTimer.Elapsed.Seconds, _loadingTimer.Elapsed.Milliseconds / 10); _loadingTimer.Stop(); } /// <summary> /// Hides the total asset loading time. /// </summary> private void HideLoadingTime() { _loadingTimeText.text = null; } /// <summary> /// Event assigned to FBX metadata loading. Editor debug purposes only. /// </summary> /// <param name="metadataType">Type of loaded metadata</param> /// <param name="metadataIndex">Index of loaded metadata</param> /// <param name="metadataKey">Key of loaded metadata</param> /// <param name="metadataValue">Value of loaded metadata</param> private void AssetLoader_OnMetadataProcessed(AssimpMetadataType metadataType, uint metadataIndex, string metadataKey, object metadataValue) { Debug.Log("Found metadata of type [" + metadataType + "] at index [" + metadataIndex + "] and key [" + metadataKey + "] with value [" + metadataValue + "]"); } /// <summary> /// Gets the asset loader options. /// </summary> /// <returns>The asset loader options.</returns> private AssetLoaderOptions GetAssetLoaderOptions() { var assetLoaderOptions = AssetLoaderOptions.CreateInstance(); assetLoaderOptions.DontLoadCameras = false; assetLoaderOptions.DontLoadLights = false; assetLoaderOptions.UseOriginalPositionRotationAndScale = true; switch (_transparencyModeDropdown.value) { case 0: assetLoaderOptions.DisableAlphaMaterials = true; break; case 1: assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Alpha; break; case 2: assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Cutout; break; case 3: assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Fade; break; } switch (_shadingDropdown.value) { case 1: assetLoaderOptions.MaterialShadingMode = MaterialShadingMode.Roughness; break; case 2: assetLoaderOptions.MaterialShadingMode = MaterialShadingMode.Specular; break; } assetLoaderOptions.AddAssetUnloader = true; assetLoaderOptions.AdvancedConfigs.Add(AssetAdvancedConfig.CreateConfig(AssetAdvancedPropertyClassNames.FBXImportDisableDiffuseFactor, true)); return assetLoaderOptions; } /// <summary> /// Pre Load setup. /// </summary> private void PreLoadSetup() { _loadingTimer.Reset(); _loadingTimer.Start(); HideControls(); if (_rootGameObject != null) { Destroy(_rootGameObject); _rootGameObject = null; } } /// <summary> /// Post load setup. /// </summary> private void PostLoadSetup() { var mainCamera = Camera.main; mainCamera.FitToBounds(_rootGameObject.transform, 3f); _backgroundCanvas.planeDistance = mainCamera.farClipPlane * 0.99f; _spinningText.gameObject.SetActive(true); _spinXToggle.isOn = false; _spinXToggle.gameObject.SetActive(true); _spinYToggle.isOn = false; _spinYToggle.gameObject.SetActive(true); _resetRotationButton.gameObject.SetActive(true); DestroyItems(); var rootAnimation = _rootGameObject.GetComponent<Animation>(); if (rootAnimation != null) { _animationsText.gameObject.SetActive(true); _animationsScrollRect.gameObject.SetActive(true); _stopAnimationButton.gameObject.SetActive(true); _stopAnimationButton.interactable = true; foreach (AnimationState animationState in rootAnimation) { CreateItem(animationState.name); } } var skinnedMeshRenderers = _rootGameObject.GetComponentsInChildren<SkinnedMeshRenderer>(); if (skinnedMeshRenderers != null) { var hasBlendShapes = false; foreach (var skinnedMeshRenderer in skinnedMeshRenderers) { if (!hasBlendShapes && skinnedMeshRenderer.sharedMesh.blendShapeCount > 0) { _blendShapesText.gameObject.SetActive(true); _blendShapesScrollRect.gameObject.SetActive(true); hasBlendShapes = true; } for (var i = 0; i < skinnedMeshRenderer.sharedMesh.blendShapeCount; i++) { CreateBlendShapeItem(skinnedMeshRenderer, skinnedMeshRenderer.sharedMesh.GetBlendShapeName(i), i); } } } } /// <summary> /// Handles "Load remote asset button" click event and tries to load the asset at chosen URI. /// </summary> private void LoadRemoteAssetButtonClick() { URIDialog.Instance.ShowDialog(delegate (string assetUri, string assetExtension) { var assetDownloader = GetComponent<AssetDownloader>(); assetDownloader.DownloadAsset(assetUri, assetExtension, LoadDownloadedAsset, null, GetAssetLoaderOptions()); _loadLocalAssetButton.interactable = false; _loadRemoteAssetButton.interactable = false; }); } /// <summary> /// Loads the downloaded asset. /// </summary> /// <param name="loadedGameObject">Loaded game object.</param> private void LoadDownloadedAsset(GameObject loadedGameObject) { PreLoadSetup(); if (loadedGameObject != null) { _rootGameObject = loadedGameObject; PostLoadSetup(); } else { var assetDownloader = GetComponent<AssetDownloader>(); ErrorDialog.Instance.ShowDialog(assetDownloader.Error); } } /// <summary> /// Creates a <see cref="AnimationText"/> item in the container. /// </summary> /// <param name="text">Text of the <see cref="AnimationText"/> item.</param> private void CreateItem(string text) { var instantiated = Instantiate(_animationTextPrefab, _containerTransform); instantiated.Text = text; } /// <summary> /// Creates a <see cref="BlendShapeControl"/> item in the container. /// </summary> /// <param name="skinnedMeshRenderer"><see cref="UnityEngine.SkinnedMeshRenderer"/> assigned to the control.</param> /// <param name="name">Blend Shape name assigned to the control.</param> /// <param name="index">Blend Shape index assigned to the control.</param> private void CreateBlendShapeItem(SkinnedMeshRenderer skinnedMeshRenderer, string name, int index) { var instantiated = Instantiate(_blendShapeControlPrefab, _blendShapesContainerTransform); instantiated.SkinnedMeshRenderer = skinnedMeshRenderer; instantiated.Text = name; instantiated.BlendShapeIndex = index; } /// <summary> /// Handles the "Reset Rotation button" click event and stops the loaded Game Object spinning. /// </summary> private void ResetRotationButtonClick() { _spinXToggle.isOn = false; _spinYToggle.isOn = false; _rootGameObject.transform.rotation = Quaternion.Euler(0f, 180f, 0f); } /// <summary> /// Handles the "Stop Animation button" click event and stops the loaded Game Object animation. /// </summary> private void StopAnimationButtonClick() { _rootGameObject.GetComponent<Animation>().Stop(); _stopAnimationButton.interactable = false; } } } } #pragma warning restore 649
42.234711
195
0.501252
[ "MIT" ]
davtamay/DecisionIntervention
DecisionIntervention/Assets/TriLib/TriLib/Samples/Scripts/AssetLoaderWindow.cs
25,554
C#
using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using System; namespace FinancialTransactionsApi.V1.Infrastructure.Converters { // TODO: This should go in a common NuGet package... /// <summary> /// Converter for enums where the value stored should be the enum value name (not the numeric value) /// </summary> public class DynamoDbBooleanConverter : IPropertyConverter { public DynamoDBEntry ToEntry(object value) { if (null == value) { return new DynamoDBNull(); } return new Primitive { Value = (bool) value == true ? "true" : "false" }; } public object FromEntry(DynamoDBEntry entry) { var primitive = entry as Primitive; return primitive?.AsBoolean(); } } }
26.382353
104
0.580825
[ "MIT" ]
LBHackney-IT/financial-transactions-api
FinancialTransactionsApi/V1/Infrastructure/Converters/DynamoDbBooleanConverter.cs
897
C#
using Microsoft.Azure.NotificationHubs; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NotificationHub.Sample.API.Models; using NotificationHub.Sample.API.Models.Dashboard; using NotificationHub.Sample.API.Models.Notifications; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace NotificationHub.Sample.API.Services.Notifications { public class NotificationHubService : INotificationService { private readonly NotificationHubClient _hub; private readonly Dictionary<string, NotificationPlatform> _installationPlatform; private readonly ILogger<NotificationHubService> _logger; public NotificationHubService(IOptions<NotificationHubOptions> options, ILogger<NotificationHubService> logger) { _logger = logger; _hub = NotificationHubClient.CreateClientFromConnectionString(options.Value.ConnectionString, options.Value.Name); _installationPlatform = new Dictionary<string, NotificationPlatform> { { nameof(NotificationPlatform.Fcm).ToLower(), NotificationPlatform.Fcm } }; } public async Task<bool> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(deviceInstallation?.InstallationId) || string.IsNullOrWhiteSpace(deviceInstallation?.Platform) || string.IsNullOrWhiteSpace(deviceInstallation?.PushChannel)) return false; var installation = new Installation() { InstallationId = deviceInstallation.InstallationId, PushChannel = deviceInstallation.PushChannel, Tags = deviceInstallation.Tags }; if (_installationPlatform.TryGetValue(deviceInstallation.Platform, out var platform)) installation.Platform = platform; else return false; try { await _hub.CreateOrUpdateInstallationAsync(installation, cancellationToken); } catch { return false; } return true; } public async Task<bool> DeleteInstallationByIdAsync(string installationId, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(installationId)) return false; try { await _hub.DeleteInstallationAsync(installationId, cancellationToken); } catch { return false; } return true; } public async Task<List<DeviceTrend>> GetAllRegistrationInfoAsync() { List<DeviceTrend> deviceRegistrationTrends = new List<DeviceTrend>(); int windowsRegistrationCount = 0; int fcmRegistrationCount = 0; int apnsRegistrationCount = 0; var allRegistrations = await _hub.GetAllRegistrationsAsync(0); foreach(var registration in allRegistrations) { if (registration is WindowsRegistrationDescription) { windowsRegistrationCount++; } else if (registration is FcmRegistrationDescription) { fcmRegistrationCount++; } else if (registration is AppleRegistrationDescription) { apnsRegistrationCount++; } } deviceRegistrationTrends.Add(new DeviceTrend() { DeviceType = "Windows", RegistrationCount = windowsRegistrationCount }); deviceRegistrationTrends.Add(new DeviceTrend() { DeviceType = "Android", RegistrationCount = fcmRegistrationCount }); deviceRegistrationTrends.Add(new DeviceTrend() { DeviceType = "Apple", RegistrationCount = apnsRegistrationCount }); return deviceRegistrationTrends; } public async Task<bool> RequestNotificationAsync(NotificationMessage notificationMessage, IList<string> tags, CancellationToken token) { var androidPushTemplate = PushTemplates.Generic.Android; var iOSPushTemplate = PushTemplates.Generic.iOS; var androidPayload = PrepareNotificationPayload( androidPushTemplate, notificationMessage.NotificationTitle, notificationMessage.NotificationDescription); var iOSPayload = PrepareNotificationPayload( iOSPushTemplate, notificationMessage.NotificationTitle, notificationMessage.NotificationDescription); try { if (tags.Count == 0) { // This will broadcast to all users registered in the notification hub await SendPlatformNotificationsAsync(androidPayload, iOSPayload, token); } else { await SendPlatformNotificationsAsync(androidPayload, iOSPayload, tags, token); } return true; } catch (Exception e) { _logger.LogError(e, "Unexpected error sending notification"); return false; } } private string PrepareNotificationPayload(string template, string title, string text) => template .Replace("$(title)", title, StringComparison.InvariantCulture) .Replace("$(alertMessage)", text, StringComparison.InvariantCulture); private Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, CancellationToken token) { var sendTasks = new Task[] { _hub.SendFcmNativeNotificationAsync(androidPayload, token) }; return Task.WhenAll(sendTasks); } Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, IEnumerable<string> tags, CancellationToken token) { var sendTasks = new Task[] { _hub.SendFcmNativeNotificationAsync(androidPayload, tags, token) }; return Task.WhenAll(sendTasks); } } }
37.333333
142
0.613147
[ "Apache-2.0" ]
deepakrout/azure-notificationhubs-samples
NotificationHubSample/NotificationHub.Sample.API/NotificationHub.Sample.API/Services/Notifications/NotificationHubService.cs
6,496
C#
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using NUnit.Framework; using Avro.Specific; namespace Avro.Test.AvroGen { class AvroGenToolResult { public int ExitCode { get; set; } public string[] StdOut { get; set; } public string[] StdErr { get; set; } } class AvroGenHelper { public static AvroGenToolResult RunAvroGenTool(params string[] args) { // Save stdout and stderr TextWriter conOut = Console.Out; TextWriter conErr = Console.Error; try { AvroGenToolResult result = new AvroGenToolResult(); StringBuilder strBuilderOut = new StringBuilder(); StringBuilder strBuilderErr = new StringBuilder(); using (StringWriter writerOut = new StringWriter(strBuilderOut)) using (StringWriter writerErr = new StringWriter(strBuilderErr)) { writerOut.NewLine = "\n"; writerErr.NewLine = "\n"; // Overwrite stdout and stderr to be able to capture console output Console.SetOut(writerOut); Console.SetError(writerErr); result.ExitCode = AvroGenTool.Main(args.ToArray()); writerOut.Flush(); writerErr.Flush(); result.StdOut = strBuilderOut.Length == 0 ? Array.Empty<string>() : strBuilderOut.ToString().Split(writerOut.NewLine); result.StdErr = strBuilderErr.Length == 0 ? Array.Empty<string>() : strBuilderErr.ToString().Split(writerErr.NewLine); } return result; } finally { // Restore console Console.SetOut(conOut); Console.SetError(conErr); } } public static Assembly CompileCSharpFilesIntoLibrary(IEnumerable<string> sourceFiles, string assemblyName = null, bool loadAssembly = true) { // Create random assembly name if not specified if (assemblyName == null) assemblyName = Path.GetRandomFileName(); // Base path to assemblies .NET assemblies var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); using (var compilerStream = new MemoryStream()) { List<string> assemblies = new List<string>() { typeof(object).Assembly.Location, typeof(Schema).Assembly.Location, typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).Assembly.Location, Path.Combine(assemblyPath, "System.Runtime.dll"), Path.Combine(assemblyPath, "netstandard.dll") }; // Create compiler CSharpCompilation compilation = CSharpCompilation .Create(assemblyName) .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(assemblies.Select(path => MetadataReference.CreateFromFile(path))) .AddSyntaxTrees(sourceFiles.Select(sourceFile => { string sourceText = System.IO.File.ReadAllText(sourceFile); return CSharpSyntaxTree.ParseText(sourceText); })); // Compile EmitResult compilationResult = compilation.Emit(compilerStream); #if DEBUG if (!compilationResult.Success) { foreach (Diagnostic diagnostic in compilationResult.Diagnostics) { if (diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error) { TestContext.WriteLine($"{diagnostic.Id} - {diagnostic.GetMessage()} - {diagnostic.Location}"); } } } #endif Assert.That(compilationResult.Success, Is.True); if (!loadAssembly) { return null; } // Load assembly from stream compilerStream.Seek(0, SeekOrigin.Begin); return Assembly.Load(compilerStream.ToArray()); } } public static string CreateEmptyTemporyFolder(out string uniqueId, string path = null) { // Create unique id uniqueId = Guid.NewGuid().ToString(); // Temporary folder name in working folder or the specified path string tempFolder = Path.Combine(path ?? TestContext.CurrentContext.WorkDirectory, uniqueId); // Create folder Directory.CreateDirectory(tempFolder); // Make sure it is empty Assert.That(new DirectoryInfo(tempFolder), Is.Empty); return tempFolder; } public static Assembly CompileCSharpFilesAndCheckTypes( string outputDir, string assemblyName, IEnumerable<string> typeNamesToCheck = null, IEnumerable<string> generatedFilesToCheck = null) { // Check if all generated files exist if (generatedFilesToCheck != null) { foreach (string generatedFile in generatedFilesToCheck) { Assert.That(new FileInfo(Path.Combine(outputDir, generatedFile)), Does.Exist); } } // Compile into netstandard library and load assembly Assembly assembly = CompileCSharpFilesIntoLibrary( new DirectoryInfo(outputDir) .EnumerateFiles("*.cs", SearchOption.AllDirectories) .Select(fi => fi.FullName), assemblyName); if (typeNamesToCheck != null) { // Check if the compiled code has the same number of types defined as the check list Assert.That(typeNamesToCheck.Count(), Is.EqualTo(assembly.DefinedTypes.Count())); // Check if types available in compiled assembly foreach (string typeName in typeNamesToCheck) { Type type = assembly.GetType(typeName); Assert.That(type, Is.Not.Null); // Protocols are abstract and cannot be instantiated if (typeof(ISpecificProtocol).IsAssignableFrom(type)) { Assert.That(type.IsAbstract, Is.True); // If directly inherited from ISpecificProtocol, use reflection to read static private field // holding the protocol. Callback objects are not directly inherited from ISpecificProtocol, // so private fields in the base class cannot be accessed if (type.BaseType.Equals(typeof(ISpecificProtocol))) { // Use reflection to read static field, holding the protocol FieldInfo protocolField = type.GetField("protocol", BindingFlags.NonPublic | BindingFlags.Static); Protocol protocol = protocolField.GetValue(null) as Protocol; Assert.That(protocol, Is.Not.Null); } } else { Assert.That(type.IsClass || type.IsEnum, Is.True); // Instantiate object object obj = Activator.CreateInstance(type); Assert.That(obj, Is.Not.Null); // If ISpecificRecord, call its member for sanity check if (obj is ISpecificRecord record) { // Read record's schema object Assert.That(record.Schema, Is.Not.Null); // Force exception by reading/writing invalid field Assert.Throws<AvroRuntimeException>(() => record.Get(-1)); Assert.Throws<AvroRuntimeException>(() => record.Put(-1, null)); } } } } return assembly; } public static Assembly TestSchema( string schema, IEnumerable<string> typeNamesToCheck = null, IEnumerable<KeyValuePair<string, string>> namespaceMapping = null, IEnumerable<string> generatedFilesToCheck = null) { // Create temp folder string outputDir = CreateEmptyTemporyFolder(out string uniqueId); try { // Save schema string schemaFileName = Path.Combine(outputDir, $"{uniqueId}.avsc"); System.IO.File.WriteAllText(schemaFileName, schema); // Generate from schema file Assert.That(AvroGenTool.GenSchema(schemaFileName, outputDir, namespaceMapping ?? new Dictionary<string, string>()), Is.EqualTo(0)); return CompileCSharpFilesAndCheckTypes(outputDir, uniqueId, typeNamesToCheck, generatedFilesToCheck); } finally { Directory.Delete(outputDir, true); } } public static Assembly TestProtocol( string protocol, IEnumerable<string> typeNamesToCheck = null, IEnumerable<KeyValuePair<string, string>> namespaceMapping = null, IEnumerable<string> generatedFilesToCheck = null) { // Create temp folder string outputDir = CreateEmptyTemporyFolder(out string uniqueId); try { // Save protocol string schemaFileName = Path.Combine(outputDir, $"{uniqueId}.avpr"); System.IO.File.WriteAllText(schemaFileName, protocol); // Generate from protocol file Assert.That(AvroGenTool.GenProtocol(schemaFileName, outputDir, namespaceMapping ?? new Dictionary<string, string>()), Is.EqualTo(0)); return CompileCSharpFilesAndCheckTypes(outputDir, uniqueId, typeNamesToCheck, generatedFilesToCheck); } finally { Directory.Delete(outputDir, true); } } } }
40.713287
149
0.560031
[ "Apache-2.0" ]
KyleSchoonover/avro
lang/csharp/src/apache/test/AvroGen/AvroGenHelper.cs
11,644
C#
namespace MassTransit.Azure.ServiceBus.Core { using System; using System.Threading.Tasks; public interface MessageLockContext { Task Complete(); Task Abandon(Exception exception); } }
15.928571
43
0.668161
[ "ECL-2.0", "Apache-2.0" ]
jahav/MassTransit
src/MassTransit.Azure.ServiceBus.Core/MessageLockContext.cs
223
C#
using System; using System.Collections.Generic; using VBScriptTranslator.StageTwoParser.ExpressionParsing; namespace VBScriptTranslator.UnitTests.Shared.Comparers { public class BuiltInValueExpressionSegmentComparer : IEqualityComparer<BuiltInValueExpressionSegment> { public bool Equals(BuiltInValueExpressionSegment x, BuiltInValueExpressionSegment y) { if (x == null) throw new ArgumentNullException("x"); if (y == null) throw new ArgumentNullException("y"); var tokenComparer = new TokenComparer(); return tokenComparer.Equals(x.Token, y.Token); } public int GetHashCode(BuiltInValueExpressionSegment obj) { if (obj == null) throw new ArgumentNullException("obj"); return 0; } } }
30.965517
106
0.621381
[ "MIT" ]
Magicianred/vbscripttranslator
UnitTests/Shared/Comparers/BuiltInValueExpressionSegmentComparer.cs
900
C#
using ECS; using UnityEngine; namespace Module.Components { public struct FollowTarget : IComponent { public GameObject Target; public bool HasBeenCalmDown; public FollowTarget(GameObject target, bool hasBeenCalmDown) { Target = target; HasBeenCalmDown = hasBeenCalmDown; } } }
17.588235
62
0.752508
[ "MIT" ]
Cewein/pecs-man
Assets/src/Tradional/Components/FollowTarget.cs
301
C#
using Microsoft.AspNet.SignalR.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReportLogRun { class Program { public static System.Random _random = new System.Random(); public static IList<string> _statuses = new List<string>(); public static CommonClient _commonClient; static void Main(string[] args) { _commonClient = new CommonClient("http://localhost:64686/"); //_commonClient = new CommonClient("http://localhost:55999/"); _statuses = new List<string> { "Bulldozed", "Carry a Towel", "Time is an illusion", "Fourty-Two", "Ask a glass of water", "Don't Panic" }; // clear it out before each run using (var db = new ReportLogModel()) { var logs = db.ReportLogs; db.ReportLogs.RemoveRange(logs); db.SaveChanges(); } while (true) { int nextRandom = _random.Next(1, 10000); System.Threading.Thread.Sleep(nextRandom); WriteToLog(); System.Console.WriteLine(nextRandom); } } private static void WriteToLog() { var reportLog = new ReportLog { Stamp = DateTime.Now, Status = GetRandomStatus() }; using (var db = new ReportLogModel()) { db.ReportLogs.Add(reportLog); db.SaveChanges(); } System.Console.WriteLine("{0} {1}", reportLog.Status, reportLog.Stamp); // add code to broadcast to SignalR clients _commonClient.AddLog(reportLog).Wait(); } private static string GetRandomStatus() { int nextRandom = _random.Next(1, _statuses.Count()); return _statuses[nextRandom]; } } }
30.19403
150
0.539792
[ "CC0-1.0" ]
robcube/SingalRSilently
d3ssignalr/ReportLogRun/Program.cs
2,025
C#
/** * Copyright 2017-2021 Plexus Interop Deutsche Bank AG * SPDX-License-Identifier: Apache-2.0 * * 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 Plexus.Interop.Protocol { public interface IProtocolImplementation { IProtocolMessageFactory MessageFactory { get; } IProtocolSerializer Serializer { get; } } }
33.115385
75
0.730546
[ "Apache-2.0" ]
deutschebank/Plexus-interop
desktop/src/Plexus.Interop.Protocol.Contracts/IProtocolImplementation.cs
863
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GUIPopup : MonoBehaviour { float startY; public float appearDistance; public float appearDelay = 0; float delayTimer; public float lerpSpeed = 10; public bool affectedBySpeed; // Start is called before the first frame update void Start() { startY = transform.position.y; transform.position = transform.position + Vector3.up * appearDistance; delayTimer = appearDelay; } // Update is called once per frame void Update() { float timestep = affectedBySpeed ? GameHandler.timeStep : Time.deltaTime; delayTimer = Mathf.MoveTowards(delayTimer, 0, timestep); if(delayTimer == 0) { transform.position = new Vector3(transform.position.x, Mathf.Lerp(transform.position.y, startY, timestep * lerpSpeed)); } } }
26.65625
122
0.724502
[ "MIT" ]
Suhbahstiejaan/Nichiware
Assets/Scripts/GUI/GUIPopup.cs
855
C#
//----------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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 Microsoft.Practices.ServiceLocation; using PhotoSharingApp.Universal.Models; using PhotoSharingApp.Universal.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace PhotoSharingApp.Universal.Views { /// <summary> /// The dialog that allows the user to choose a category. /// </summary> public sealed partial class CategoriesChooserDialog : ContentDialog { public CategoriesChooserDialog() { InitializeComponent(); ViewModel = ServiceLocator.Current.GetInstance<CategoriesChooserViewModel>(); DataContext = ViewModel; // Register for events Loaded += CategoriesChooserDialog_Loaded; } public CategoriesChooserViewModel ViewModel { get; } private void CancelButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { ViewModel.SelectedCategory = null; } private async void CategoriesChooserDialog_Loaded(object sender, RoutedEventArgs e) { await ViewModel.LoadState(); if (AppEnvironment.Instance.IsDesktopDeviceFamily) { // On desktop we set the focus instantly to // the search box so that the user is able // type search text right away. // On mobile, this would expand the virtual keyboard // and takes away too much space by default. searchTextBox.Focus(FocusState.Keyboard); } } } }
41.628571
100
0.646534
[ "MIT" ]
Bhaskers-Blu-Org2/Appsample-Photosharing
PhotoSharingApp/PhotoSharingApp.Universal/Views/CategoriesChooserDialog.xaml.cs
2,916
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the dax-2017-04-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DAX.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DAX.Model.Internal.MarshallTransformations { /// <summary> /// DescribeSubnetGroups Request Marshaller /// </summary> public class DescribeSubnetGroupsRequestMarshaller : IMarshaller<IRequest, DescribeSubnetGroupsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeSubnetGroupsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeSubnetGroupsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DAX"); string target = "AmazonDAXV3.DescribeSubnetGroups"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-04-19"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetMaxResults()) { context.Writer.WritePropertyName("MaxResults"); context.Writer.Write(publicRequest.MaxResults); } if(publicRequest.IsSetNextToken()) { context.Writer.WritePropertyName("NextToken"); context.Writer.Write(publicRequest.NextToken); } if(publicRequest.IsSetSubnetGroupNames()) { context.Writer.WritePropertyName("SubnetGroupNames"); context.Writer.WriteArrayStart(); foreach(var publicRequestSubnetGroupNamesListValue in publicRequest.SubnetGroupNames) { context.Writer.Write(publicRequestSubnetGroupNamesListValue); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeSubnetGroupsRequestMarshaller _instance = new DescribeSubnetGroupsRequestMarshaller(); internal static DescribeSubnetGroupsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeSubnetGroupsRequestMarshaller Instance { get { return _instance; } } } }
36.45082
155
0.612548
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/DAX/Generated/Model/Internal/MarshallTransformations/DescribeSubnetGroupsRequestMarshaller.cs
4,447
C#
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ModCache { public static void RescanModCacheFolder() { Directory.CreateDirectory(Serializer.GetModsCacheFolder()); string[] modFiles = Directory.GetFiles(Serializer.GetModsCacheFolder(), "*", SearchOption.AllDirectories); CheckAddNewMods(modFiles); MainForm.SaveData(); MainForm.RefreshListView(); } public static void CheckAddNewMods(string[] paths) { IEnumerable<string> newMods = paths.Where(filePath => !MainForm.instance.modsData.modInfos.Exists(mI => mI.modPath == filePath)); foreach (string file in newMods) { ModInfo matchMod = MainForm.instance.modsData.modInfos.Find(x => x.modName == Path.GetFileName(file)); if (matchMod) { matchMod.modPath = file; } else { ModInfo tMod = new ModInfo(file); if (tMod.archiveFiles != null) { MainForm.instance.modsData.modInfos.Add(tMod); foreach (var archFile in tMod.archiveFiles) { if (!archFile.parent) archFile.GetInstalled(); } } } } } public static void ReCheckMods(IEnumerable<ModInfo> modInfos) { foreach (var mod in modInfos) { if (!mod.archiveExists) continue; mod.archiveFiles = ArchiveManager.GetArchiveFiles(mod); if (mod.archiveFiles != null) { foreach (var archFile in mod.archiveFiles) { if (!archFile.parent) archFile.GetInstalled(); } } } } }
29.190476
137
0.565525
[ "MIT" ]
HalcyonAlcedo/MHWModManager
MHW_ModManager/Classes/ModCache.cs
1,841
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace SysmonConfigPusher { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.444444
42
0.710843
[ "MIT" ]
LaresLLC/SysmonConfigPusher
App.xaml.cs
334
C#
using System; using System.Text; namespace MarkdownToDocx { internal static class ExceptionTrapper { public static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) { var ex = (Exception)e.ExceptionObject; var exceptionInfoText = BuildExceptionInformationText(ex); Console.Error.WriteLine("**** EXCEPTION ****"); Console.Error.WriteLine(exceptionInfoText); } public static string BuildExceptionInformationText(Exception exception) { var builder = new StringBuilder(); var ex = exception; while (true) { builder.AppendFormat("{0}: {1}", ex.GetType().FullName, ex.Message); builder.AppendLine(); if (ex.Data.Count != 0) { builder.AppendLine("Data:"); foreach (string key in ex.Data.Keys) { builder.AppendLine(string.Format(" {0}: {1}", key, ex.Data[key])); } } builder.AppendLine("Stack Trace:"); builder.AppendLine(ex.StackTrace); if (ex.InnerException == null) break; ex = ex.InnerException; builder.AppendLine(@"--- Inner exception is below ---"); } return builder.ToString(); } } }
30.541667
98
0.517053
[ "MIT" ]
tksh164/MarkdownToDocx
MarkdownToDocx/MarkdownToDocx/ExceptionTrapper.cs
1,468
C#
using EasyAbp.Abp.WeChat.MiniProgram.Infrastructure.Models; using System; using System.Collections.Generic; using System.Text; namespace EasyAbp.Abp.WeChat.MiniProgram.Services.Broadcast.Response { public class DeleteInRoomGoodsResponse : IMiniProgramResponse { public string ErrorMessage { get; set; } public int ErrorCode { get; set; } } }
23.375
68
0.743316
[ "MIT" ]
Jy1233456/Abp.WeChat
src/MiniProgram/EasyAbp.Abp.WeChat.MiniProgram/Services/Broadcast/Response/DeleteInRoomGoodsResponse.cs
376
C#
namespace SkuckCardGameCP.Cards; public class SkuckCardGameCardInformation : RegularTrickCard, IDeckObject { }
55
77
0.863636
[ "MIT" ]
musictopia2/GamingPackXV3
CP/Games/SkuckCardGameCP/Cards/SkuckCardGameCardInformation.cs
110
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using Data.DbClient.Fluent.Enums; using Data.DbClient.Fluent.Extensions; using Data.DbClient.Fluent.Model; namespace Data.DbClient.Fluent.Select { /* https://github.com/thoss/select-query-builder*/ public class QueryBuilderBase : IQueryBuilder { #region Class Initialization public QueryBuilderBase() { //Allcolumns(); } public QueryBuilderBase(SqlLanguageType languageType = SqlLanguageType.SqlServer) : this() { LanguageType = languageType; } #endregion Class Initialization #region Fields and Properties protected string SelectedTable; protected List<IWhereClause> WhereClauses = new List<IWhereClause>(); protected List<string> SelectedColumns = new List<string>(); protected List<JoinClause> JoinClauses = new List<JoinClause>(); protected List<OrderClause> SortClauses = new List<OrderClause>(); protected List<SchemaObject> GroupByClauses = new List<SchemaObject>(); protected List<HavingClause> HavingClauses = new List<HavingClause>(); protected TopClause TopClause = new TopClause(0); protected LimitClause LimitClause = new LimitClause(0); protected OffsetClause OffsetClause = new OffsetClause(0); protected SqlLanguageType LanguageType = SqlLanguageType.SqlServer; //protected string Schema = "dbo"; #endregion Fields and Properties #region Fluent Methods #region SELECT Fluent Methods public QueryBuilderBase SelectAllColumns() { //SelectedColumns.Clear(); SelectedColumns.Add("*"); return this; } public QueryBuilderBase Top(int quantity) { TopClause.Quantity = quantity; return this; } public QueryBuilderBase SelectColumns(params string[] columns) { return SelectColumns(columns, false); } public QueryBuilderBase SelectColumns(IEnumerable<string> columns, bool clearExisting = false) { if (clearExisting) SelectedColumns.Clear(); foreach (var column in columns) { SelectedColumns.Add(column); } return this; } public QueryBuilderBase SelectColumns(string columnsString, bool clearExisting = false) { return SelectColumns(columnsString.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries), clearExisting); } #endregion #region FROM Fluent Methods public QueryBuilderBase FromTable(string table) { SelectedTable = table; return this; } public QueryBuilderBase Join(JoinClause joinClause) { JoinClauses.Add(joinClause); return this; } public QueryBuilderBase Join(JoinType join, string toTableName, string toColumnName, ComparisonOperatorType comparisonOperator, string fromTableName, string fromColumnName) { return Join(new JoinClause(join, toTableName, toColumnName, comparisonOperator, fromTableName, fromColumnName)); } #endregion #region WHERE Fluent Methods public QueryBuilderBase Where(IWhereClause whereClause) { WhereClauses.Add(whereClause); return this; } public QueryBuilderBase Where(string columNameOrScalarFunction, ComparisonOperatorType comparisonOperator, object value, LogicalOperatorType logicalOperatorType = LogicalOperatorType.Or) { return Where(new WhereClause(columNameOrScalarFunction, comparisonOperator, value, logicalOperatorType)); } public QueryBuilderBase WhereAnd(string columNameOrScalarFunction, ComparisonOperatorType comparisonOperator, object value) { return Where(new WhereClause(columNameOrScalarFunction, comparisonOperator, value, LogicalOperatorType.And)); } public QueryBuilderBase WhereOr(string columNameOrScalarFunction, ComparisonOperatorType comparisonOperator, object value) { return Where(new WhereClause(columNameOrScalarFunction, comparisonOperator, value, LogicalOperatorType.Or)); } #endregion #region GROUP BY Fluent Methods public QueryBuilderBase GroupBy(params string[] columns) { return GroupBy(columns, false); } public QueryBuilderBase GroupBy(IEnumerable<string> columns, bool clearExisting = false) { if (clearExisting) GroupByClauses.Clear(); foreach (var column in columns) { GroupByClauses.Add(new SchemaObject(column, null, null, SchemaValueType.Preformatted)); } return this; } public QueryBuilderBase GroupBy(string columnsString, bool clearExisting = false) { return GroupBy(columnsString.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries), clearExisting); } #endregion #region HAVING Fluent Methods public QueryBuilderBase Having(HavingClause havingClause) { HavingClauses.Add(havingClause); return this; } public QueryBuilderBase Having(string columNameOrAggregateFunction, ComparisonOperatorType comparisonOperator, object value, LogicalOperatorType logicalOperatorType = LogicalOperatorType.Or) { return Having(new HavingClause(columNameOrAggregateFunction, comparisonOperator, value, logicalOperatorType)); } public QueryBuilderBase HavingAnd(string columNameOrScalarFunction, ComparisonOperatorType comparisonOperator, object value) { return Having(new HavingClause(columNameOrScalarFunction, comparisonOperator, value, LogicalOperatorType.And)); } public QueryBuilderBase HavingOr(string columNameOrScalarFunction, ComparisonOperatorType comparisonOperator, object value) { return Having(new HavingClause(columNameOrScalarFunction, comparisonOperator, value, LogicalOperatorType.Or)); } #endregion #region ORDER BY Fluent Methods public QueryBuilderBase OrderBy(OrderClause sortClause) { SortClauses.Add(sortClause); return this; } public QueryBuilderBase OrderBy(string column, OrderType sorting = OrderType.Ascending) { return OrderBy(new OrderClause(column, sorting)); } #endregion #region SKIP/TAKE (LIMIT/OFFSET) Fluent Methods public QueryBuilderBase Take(int take) { LimitClause.Take = take; return this; } public QueryBuilderBase Skip(int skip) { OffsetClause.Skip = skip; return this; } #endregion #endregion Fluent Methods #region IQueryBuilder Methods public string BuildQuery() { var query = CompileSelectSegment(); /* SELECT */ query += CompileWhereSegment(); /* Append WHERE */ query += CompileGroupBySegment(); /* Append GROUP BY */ query += CompileHavingSegment(); /* Append HAVING */ query += CompileOrderBySegment(); /* Append ORDER BY */ /* TODO: Implement specific SQL language methods here - (JKOSH) */ if (LanguageType == SqlLanguageType.SqlServer) { query += CompileOffsetSegment(); /* Append OFFSET BY (SKIP) */ query += CompileLimitSegment(); /* Append LIMIT BY (TAKE) */ } else { query += CompileLimitSegment(); /* Append LIMIT BY */ query += CompileOffsetSegment(); /* Append OFFSET BY */ } return query; } public IQueryObject GetQueryObject() { // TODO: make language specific implementations here? var o = new QueryObjectBase { SelectColumns = SelectedColumns.Select(x=> new SchemaObject() { Value = x, ValueType = SchemaValueType.Preformatted}).ToList(), Top = TopClause.Quantity, FromTable = new SchemaObject(SelectedTable, null, null, SchemaValueType.Preformatted), Joins = JoinClauses.Select(x=> (Join)x).ToList(), WhereFilters = WhereClauses.Select(x=>(Where)(WhereClause)x).ToList(), GroupBy = GroupByClauses.Select(x=>x).ToList(), HavingClauses = HavingClauses.Select(x => (Having)x).ToList(), OrderByClauses = SortClauses.Select(x => (OrderBy)x).ToList(), Skip = OffsetClause.Skip, Take = LimitClause.Take }; return o; } #endregion IQueryBuilder Methods #region Private Methods #region Build Query Methods private string CompileSelectSegment() { if (!SelectedColumns.Any()) SelectAllColumns(); if (OffsetClause.Skip > 0) { TopClause.Quantity = 0; if (!SortClauses.Any()) { SortClauses.Add(new OrderClause("1")); } } var query = $"SELECT{(TopClause.Quantity > 0 ? $" TOP {TopClause.Quantity} " : " ")}{GetSelectedColumnString()}{CompileFromSegment()}"; return ApplyJoins(query); } private string GetSelectedColumnString() { return string.Join("\r\n\t,", SelectedColumns); } private string CompileFromSegment() { return $"\r\nFROM {SelectedTable}"; } private string ApplyJoins(string query) { return JoinClauses.Aggregate(query, (current, joinClause) => current + $" {GetJoinType(joinClause.JoinType)} {joinClause.ToTable} \r\nON {RemoveTableSchema(GetTableAlias(joinClause.FromTable))}.{joinClause.FromColumn} {GetComparisonOperator(joinClause.ComparisonOperator)} {GetTableAlias(joinClause.ToTable)}.{joinClause.ToColumn}"); } private static string RemoveTableSchema(string tableName) { return tableName.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase) > 0 ? tableName.Substring(tableName.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase) + ".".Length) : tableName; } private static string RemoveTableAlias(string tableName) { return tableName.IndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase) > 0 ? tableName.Substring(0, tableName.LastIndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase)): tableName; } private static string GetTableAlias(string tableName) { return tableName.IndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase) > 0 ? tableName.Substring(tableName.LastIndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase) + " AS ".Length) : tableName; } private string CompileWhereSegment() { var rv = WhereClauses.Count > 0 ? "\r\nWHERE " : ""; foreach (var whereClause in WhereClauses) { if (whereClause is WhereClause) { rv += $"{GetFilterStatement(new List<WhereClause> { whereClause as WhereClause }, !whereClause.Equals(WhereClauses.Last()))}"; } else if (whereClause is GroupWhereClause) { rv += $"({GetFilterStatement((whereClause as GroupWhereClause).WhereClauses)})"; if (!whereClause.Equals(WhereClauses.Last())) { // Build Logicoperator rv += $"{GetLogicOperator((whereClause as GroupWhereClause).LogicalOperatorType)} "; } } } return rv; } private string CompileGroupBySegment() { var query = GroupByClauses.Count > 0 ? "\r\nGROUP BY " : ""; foreach (var groupByClause in GroupByClauses) { query += $"{groupByClause.AsString()}"; if (!groupByClause.Equals(GroupByClauses.Last())) { query += "\r\n\t, "; } } return query; } private string CompileHavingSegment() { var query = HavingClauses.Count > 0 ? "\r\nHAVING " : ""; return HavingClauses.Aggregate(query, (current, havingClause) => current + GetFilterStatement(new List<HavingClause> { havingClause }, !havingClause.Equals(HavingClauses.Last()))); } private string CompileOrderBySegment() { var query = SortClauses.Count > 0 ? "\r\nORDER BY " : ""; /* TODO: Fix the logic here for correct formatting - (JKOSH) */ foreach (var sortClause in SortClauses) { query += $"{sortClause.Column} {GetSortingType(sortClause.Sorting)}"; if (!sortClause.Equals(SortClauses.Last())) { query += ", "; } } return query; } /// <summary> /// Generates the LIMIT or TAKE clause. e.g. FETCH NEXT 10 ROWS ONLY /// </summary> /// <returns>string</returns> private string CompileLimitSegment() { switch (LanguageType) { case SqlLanguageType.SqlServer: return $"{(LimitClause.Take > 0 ? $"\r\nFETCH NEXT {LimitClause.Take} ROWS ONLY " : "")}"; case SqlLanguageType.PostgreSql: return $"{(LimitClause.Take > 0 ? $" LIMIT {LimitClause.Take} " : "")}"; default: return $"{(LimitClause.Take > 0 ? $" LIMIT {LimitClause.Take} " : "")}"; /* TODO: Implement and Test all specific language types - (JKOSH) */ } } /// <summary> /// Generates the OFFSET or SKIP clause. e.g. OFFSET 2 ROWS /// </summary> /// <returns>string</returns> private string CompileOffsetSegment() { switch (LanguageType) { case SqlLanguageType.SqlServer: return LimitClause.Take > 0 ? $"{(OffsetClause.Skip > 0 ? $"\r\nOFFSET {OffsetClause.Skip} ROWS " : "\r\nOFFSET 0 ROWS ")}" : $"{(OffsetClause.Skip > 0 ? $"\r\nOFFSET {OffsetClause.Skip} ROWS " : "")}"; case SqlLanguageType.PostgreSql: return $"{(OffsetClause.Skip > 0 ? $" OFFSET {OffsetClause.Skip} " : "")}"; default: return $"{(OffsetClause.Skip > 0 ? $" OFFSET {OffsetClause.Skip} " : "")}"; /* TODO: Implement and Test all specific language types - (JKOSH) */ } } #endregion Build Query Methods #region Utility Methods private static string FormatSqlValue(object value) { if (value == null) { return "NULL"; } switch (value.GetType().Name) { case "String": return "'" + ((string)value).Replace("'", "''") + "'"; case "Boolean": return (bool)value ? "1" : "0"; case "DateTime": //return $"CONVERT (DATETIME,'{((DateTime)value).ToString("yyyy-dd-MM HH:mm:ss")}')"; return $"'{((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss")}'"; // TODO: review this!!!!! case "SqlLiteral": // ReSharper disable once PossibleNullReferenceException return (value as SqlLiteral).Expression; case "SqlParameter": // ReSharper disable once PossibleNullReferenceException return (value as SqlParameter).ParameterName; default: return value.ToString(); } } private static string GetFilterStatement<T>(List<T> filterClauses, bool ignoreCheckLastClause = false) where T : FilterClause { var output = ""; foreach (var clause in filterClauses) { output = output + GetComparisonClause(clause); if (ignoreCheckLastClause || !clause.Equals(filterClauses.Last())) { output += $" {GetLogicOperator(clause.LogicalOperatorType)} "; } } return output; } private static string GetComparisonClause(FilterClause filterClause) { if (filterClause.ComparisonOperator == ComparisonOperatorType.In || filterClause.ComparisonOperator == ComparisonOperatorType.NotIn) { return $"{filterClause.FieldName} {GetComparisonOperator(filterClause.ComparisonOperator, filterClause.Value == null)} ({FormatSqlValue(filterClause.Value)})"; } else { return $"{filterClause.FieldName} {GetComparisonOperator(filterClause.ComparisonOperator, filterClause.Value == null)} {FormatSqlValue(filterClause.Value)}"; } } private static string GetJoinType(JoinType joinType) { switch (joinType) { case JoinType.InnerJoin: return "\r\nINNER JOIN"; case JoinType.LeftJoin: return "\r\nLEFT OUTER JOIN"; case JoinType.RightJoin: return "\r\nRIGHT OUTER JOIN"; case JoinType.OuterJoin: return "\r\nFULL OUTER JOIN"; default: return ""; } } private static string GetLogicOperator(LogicalOperatorType logicalOperatorType) { switch (logicalOperatorType) { case LogicalOperatorType.And: return "\r\nAND"; case LogicalOperatorType.Or: return "\r\nOR"; default: return ""; } } private static string GetSortingType(OrderType sorting) { switch (sorting) { case OrderType.Ascending: return "ASC"; case OrderType.Descending: return "DESC"; default: return ""; } } private static string GetComparisonOperator(ComparisonOperatorType comparisonOperator, bool isNull = false) { if (isNull) { switch (comparisonOperator) { case ComparisonOperatorType.Equals: return "IS"; case ComparisonOperatorType.NotEquals: return "IS NOT"; } } switch (comparisonOperator) { case ComparisonOperatorType.Equals: return "="; case ComparisonOperatorType.NotEquals: return "!="; case ComparisonOperatorType.GreaterThan: return ">"; case ComparisonOperatorType.GreaterOrEquals: return ">="; case ComparisonOperatorType.LessThan: return "<"; case ComparisonOperatorType.LessOrEquals: return "<="; case ComparisonOperatorType.Like: return "LIKE"; case ComparisonOperatorType.NotLike: return "NOT LIKE"; case ComparisonOperatorType.In: return "IN"; case ComparisonOperatorType.NotIn: return "NOT IN"; default: return ""; } } #endregion Utility Methods #endregion Private Methods } }
36.005263
284
0.565366
[ "MIT" ]
JohnPKosh/IODataBlock
IODataBlock/Data.DbClient/Fluent/Select/QueryBuilderBase.cs
20,525
C#
namespace MassEffect.Engine.Commands { using System; using Exceptions; using Interfaces; public class PlotJumpCommand : Command { public PlotJumpCommand(IGameEngine gameEngine) : base(gameEngine) { } public override void Execute(string[] commandArgs) { //plot-jump {shipName} {starSystem} var shipName = commandArgs[1]; var starSystemName = commandArgs[2]; var ship = this.GetStarshipByName(shipName); this.ValidateAlive(ship); var previousLocation = ship.Location; var destination = this.GameEngine.Galaxy.GetStarSystemByName(starSystemName); if (previousLocation.Name == destination.Name) { throw new ShipException(string.Format(Messages.ShipAlreadyInStarSystem, destination.Name)); } this.GameEngine.Galaxy.TravelTo(ship, destination); Console.WriteLine(Messages.ShipTraveled, shipName, previousLocation.Name, destination.Name); } } }
30.25
107
0.620753
[ "MIT" ]
pirocorp/C-OOP-Basics-
16. Projects/03. Mass Effect/MassEffect/Engine/Commands/PlotJumpCommand.cs
1,091
C#
using UnityEngine; namespace ThinkingAnalytics.Utils { public class TD_Log { private static bool enableLog; public static void EnableLog(bool enabled) { enableLog = enabled; } public static void d(string message) { if (enableLog) { Debug.Log(message); } } public static void e(string message) { if (enableLog) { Debug.LogError(message); } } public static void w(string message) { if (enableLog) { Debug.LogWarning(message); } } } }
19.459459
50
0.447222
[ "Apache-2.0" ]
ThinkingDataAnalytics/unity-sdk
Assets/ThinkingAnalytics/Utils/TD_Log.cs
722
C#
using Okra; using Okra.Navigation; using Okra.Sharing; using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.Resources; using Windows.UI.ApplicationSettings; namespace Okra.TodoSample { public class AppBootstrapper : OkraBootstrapper { [Import] public ISettingsPaneManager SettingsPaneManager { get; set; } [Import] public IShareSourceManager ShareSourceManager { get; set; } [Import] public IShareTargetManager ShareTargetManager { get; set; } /// <summary> /// Perform general initialization of application services. /// </summary> protected override void SetupServices() { // Configure the navigation manager to preseve application state in local storage NavigationManager.NavigationStorageType = NavigationStorageType.Local; // Register with Windows to display items in the settings pane SettingsPane.GetForCurrentView().CommandsRequested += SettingsPane_CommandsRequested; // Set the page name to act as a share target ShareTargetManager.ShareTargetPageName = "ShareTarget"; } void SettingsPane_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args) { // The settings names should be localised so create a ResourceLoader to gather these from ResourceLoader resourceLoader = new ResourceLoader(); // Add each settings item in the order you wish them to appear // NB: Since we want the SettingsPaneManager to navigate when the item is selected we use the GetNavigateToSettingsCommand helper args.Request.ApplicationCommands.Add(SettingsPaneManager.GetNavigateToSettingsCommand(resourceLoader.GetString("AboutCommandLabel"), "AboutPage")); args.Request.ApplicationCommands.Add(SettingsPaneManager.GetNavigateToSettingsCommand(resourceLoader.GetString("SettingsCommandLabel"), "Settings")); } } }
38.781818
161
0.715893
[ "Apache-2.0" ]
OkraFramework/Okra-Todo
Okra-Todo/AppBootstrapper.cs
2,135
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Spellbook.Models { public class SpellList { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int SpellListId { get; set; } public string Name { get; set; } public virtual ICollection<Spell> Spells { get; set; } } }
23.888889
62
0.695349
[ "MIT" ]
1804-Apr-USFdotnet/project2-spellbook2
SpellbookAPI/Spellbook/Spellbook.Models/SpellList.cs
432
C#
//***** AUTO-GENERATED - DO NOT EDIT *****// using BlueprintCore.Blueprints.Configurators.Items.Equipment; using BlueprintCore.Utils; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Items.Shields; using System; namespace BlueprintCore.Blueprints.Configurators.Items.Shields { /// <summary> /// Implements common fields and components for blueprints inheriting from <see cref="BlueprintItemShield"/>. /// </summary> /// <inheritdoc/> public abstract class BaseItemShieldConfigurator<T, TBuilder> : BaseItemEquipmentHandConfigurator<T, TBuilder> where T : BlueprintItemShield where TBuilder : BaseItemShieldConfigurator<T, TBuilder> { protected BaseItemShieldConfigurator(Blueprint<BlueprintReference<T>> blueprint) : base(blueprint) { } /// <summary> /// Sets the value of <see cref="BlueprintItemShield.m_WeaponComponent"/> /// </summary> /// /// <param name="weaponComponent"> /// <para> /// Blueprint of type BlueprintItemWeapon. You can pass in the blueprint using: /// <list type ="bullet"> /// <item><term>A blueprint instance</term></item> /// <item><term>A blueprint reference</term></item> /// <item><term>A blueprint id as a string, Guid, or BlueprintGuid</term></item> /// <item><term>A blueprint name registered with <see cref="BlueprintTool">BlueprintTool</see></term></item> /// </list> /// See <see cref="Blueprint{TRef}">Blueprint</see> for more details. /// </para> /// </param> public TBuilder SetWeaponComponent(Blueprint<BlueprintItemWeaponReference> weaponComponent) { return OnConfigureInternal( bp => { bp.m_WeaponComponent = weaponComponent?.Reference; }); } /// <summary> /// Modifies <see cref="BlueprintItemShield.m_WeaponComponent"/> by invoking the provided action. /// </summary> public TBuilder ModifyWeaponComponent(Action<BlueprintItemWeaponReference> action) { return OnConfigureInternal( bp => { if (bp.m_WeaponComponent is null) { return; } action.Invoke(bp.m_WeaponComponent); }); } /// <summary> /// Sets the value of <see cref="BlueprintItemShield.m_ArmorComponent"/> /// </summary> /// /// <param name="armorComponent"> /// <para> /// Blueprint of type BlueprintItemArmor. You can pass in the blueprint using: /// <list type ="bullet"> /// <item><term>A blueprint instance</term></item> /// <item><term>A blueprint reference</term></item> /// <item><term>A blueprint id as a string, Guid, or BlueprintGuid</term></item> /// <item><term>A blueprint name registered with <see cref="BlueprintTool">BlueprintTool</see></term></item> /// </list> /// See <see cref="Blueprint{TRef}">Blueprint</see> for more details. /// </para> /// </param> public TBuilder SetArmorComponent(Blueprint<BlueprintItemArmorReference> armorComponent) { return OnConfigureInternal( bp => { bp.m_ArmorComponent = armorComponent?.Reference; }); } /// <summary> /// Modifies <see cref="BlueprintItemShield.m_ArmorComponent"/> by invoking the provided action. /// </summary> public TBuilder ModifyArmorComponent(Action<BlueprintItemArmorReference> action) { return OnConfigureInternal( bp => { if (bp.m_ArmorComponent is null) { return; } action.Invoke(bp.m_ArmorComponent); }); } } }
35.676768
114
0.648641
[ "MIT" ]
TylerGoeringer/WW-Blueprint-Core
BlueprintCore/BlueprintCore/Blueprints/Configurators/Items/Shields/BaseItemShield.cs
3,532
C#
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace OpenCvSharp { /// <inheritdoc /> /// <summary> /// File Storage Node class /// </summary> public class FileNodeIterator : DisposableCvObject, IEquatable<FileNodeIterator>/*, IEnumerator<FileNode>*/ { /// <summary> /// The default constructor /// </summary> public FileNodeIterator() { ptr = NativeMethods.core_FileNodeIterator_new1(); } /// <summary> /// Initializes from cv::FileNode* /// </summary> /// <param name="ptr"></param> public FileNodeIterator(IntPtr ptr) { this.ptr = ptr; } /// <summary> /// Releases unmanaged resources /// </summary> protected override void DisposeUnmanaged() { NativeMethods.core_FileNodeIterator_delete(ptr); base.DisposeUnmanaged(); } /// <summary> /// Reads node elements to the buffer with the specified format. /// Usually it is more convenient to use operator `>>` instead of this method. /// </summary> /// <param name="fmt">Specification of each array element.See @ref format_spec "format specification"</param> /// <param name="vec">Pointer to the destination array.</param> /// <param name="maxCount">Number of elements to read. If it is greater than number of remaining elements then all of them will be read.</param> /// <returns></returns> public FileNodeIterator ReadRaw(string fmt, IntPtr vec, long maxCount = int.MaxValue) { if (fmt == null) throw new ArgumentNullException(nameof(fmt)); NativeMethods.core_FileNodeIterator_readRaw(ptr, fmt, vec, new IntPtr(maxCount)); GC.KeepAlive(this); return this; } /// <inheritdoc /> /// <summary> /// *iterator /// </summary> public FileNode Current { get { ThrowIfDisposed(); IntPtr p = NativeMethods.core_FileNodeIterator_operatorAsterisk(ptr); GC.KeepAlive(this); return new FileNode(p); } } //object IEnumerator.Current => Current; /// <summary> /// iterator++ /// </summary> /// <returns></returns> public bool MoveNext() { ThrowIfDisposed(); int changed = NativeMethods.core_FileNodeIterator_operatorIncrement(ptr); GC.KeepAlive(this); return changed != 0; } /// <summary> /// iterator += ofs /// </summary> /// <param name="ofs"></param> /// <returns></returns> public bool MoveNext(int ofs) { ThrowIfDisposed(); int changed = NativeMethods.core_FileNodeIterator_operatorPlusEqual(ptr, ofs); GC.KeepAlive(this); return changed != 0; } /// <summary> /// iterator-- /// </summary> /// <returns></returns> public bool MoveBack() { ThrowIfDisposed(); int changed = NativeMethods.core_FileNodeIterator_operatorDecrement(ptr); GC.KeepAlive(this); return changed != 0; } /// <summary> /// iterator -= ofs /// </summary> /// <param name="ofs"></param> /// <returns></returns> public bool MoveBack(int ofs) { ThrowIfDisposed(); int changed = NativeMethods.core_FileNodeIterator_operatorMinusEqual(ptr, ofs); GC.KeepAlive(this); return changed != 0; } /// <summary> /// iterator -= INT_MAX /// </summary> public void Reset() { ThrowIfDisposed(); int changed = NativeMethods.core_FileNodeIterator_operatorMinusEqual(ptr, Int32.MaxValue); GC.KeepAlive(this); } /// <summary> /// Reads node elements to the buffer with the specified format. /// Usually it is more convenient to use operator `>>` instead of this method. /// </summary> /// <param name="fmt">Specification of each array element.See @ref format_spec "format specification"</param> /// <param name="vec">Pointer to the destination array.</param> /// <param name="maxCount">Number of elements to read. If it is greater than number of remaining elements then all of them will be read.</param> /// <returns></returns> public FileNodeIterator ReadRaw(string fmt, byte[] vec, long maxCount = int.MaxValue) { if (fmt == null) throw new ArgumentNullException(nameof(fmt)); if (vec == null) throw new ArgumentNullException(nameof(vec)); unsafe { fixed (byte* vecPtr = vec) { NativeMethods.core_FileNodeIterator_readRaw(ptr, fmt, new IntPtr(vecPtr), new IntPtr(maxCount)); } } GC.KeepAlive(this); return this; } /// <summary> /// /// </summary> /// <param name="it"></param> /// <returns></returns> public bool Equals(FileNodeIterator it) { if (it is null) return false; ThrowIfDisposed(); it.ThrowIfDisposed(); int ret = NativeMethods.core_FileNodeIterator_operatorEqual(ptr, it.CvPtr); GC.KeepAlive(this); GC.KeepAlive(it); return ret != 0; } /// <summary> /// /// </summary> /// <param name="it"></param> /// <returns></returns> public long Minus(FileNodeIterator it) { if (it == null) throw new ArgumentNullException(nameof(it)); ThrowIfDisposed(); it.ThrowIfDisposed(); IntPtr ret = NativeMethods.core_FileNodeIterator_operatorMinus(ptr, it.CvPtr); GC.KeepAlive(this); GC.KeepAlive(it); return ret.ToInt64(); } /// <summary> /// /// </summary> /// <param name="it"></param> /// <returns></returns> public bool LessThan(FileNodeIterator it) { if (it == null) throw new ArgumentNullException(nameof(it)); ThrowIfDisposed(); it.ThrowIfDisposed(); int ret = NativeMethods.core_FileNodeIterator_operatorLessThan(ptr, it.CvPtr); GC.KeepAlive(this); GC.KeepAlive(it); return ret != 0; } } }
31.352941
152
0.529369
[ "BSD-3-Clause" ]
DiomedesDominguez/opencvsharp
src/OpenCvSharp/Modules/core/FileNodeIterator.cs
6,931
C#
using System; using Masb.Yai.Markers; namespace Masb.Yai { [Obsolete] public class RelativeTypeChangerExpressionFilter : TypeChangerExpressionFilter { protected override Type ChangeType(ExpressionFilterContext context, Type type) { var context2 = this.GetContext(context, type); return context2.ComponentType; } private CompositionContext GetContext(ExpressionFilterContext context, Type type) { if (type == typeof(M.Current)) return context; if (type == typeof(M.Current.New)) return context; if (type == typeof(M.Current.Struct)) return context; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(M.Parent<>)) return this.GetContext(context, type.GetGenericArguments()[0]).ParentContext; if (type.TypeHandle == typeof(M.Parent<>.New).TypeHandle) // todo: check this TypeHandle return this.GetContext(context, type.GetGenericArguments()[0]).ParentContext; if (type.TypeHandle == typeof(M.Parent<>.Struct).TypeHandle) // todo: check this TypeHandle return this.GetContext(context, type.GetGenericArguments()[0]).ParentContext; throw new Exception("Invalid GetContext call"); } } }
36.131579
103
0.628551
[ "Apache-2.0" ]
masbicudo/InterSiteLogin
Masb.Yai/RelativeTypeChangerExpressionFilter.cs
1,373
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V271.Segment; using NHapi.Model.V271.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V271.Group { ///<summary> ///Represents the CSU_C09_STUDY_PHASE Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: CSP (Clinical Study Phase) optional </li> ///<li>1: CSU_C09_STUDY_SCHEDULE (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class CSU_C09_STUDY_PHASE : AbstractGroup { ///<summary> /// Creates a new CSU_C09_STUDY_PHASE Group. ///</summary> public CSU_C09_STUDY_PHASE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(CSP), false, false); this.add(typeof(CSU_C09_STUDY_SCHEDULE), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating CSU_C09_STUDY_PHASE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns CSP (Clinical Study Phase) - creates it if necessary ///</summary> public CSP CSP { get{ CSP ret = null; try { ret = (CSP)this.GetStructure("CSP"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of CSU_C09_STUDY_SCHEDULE (a Group object) - creates it if necessary ///</summary> public CSU_C09_STUDY_SCHEDULE GetSTUDY_SCHEDULE() { CSU_C09_STUDY_SCHEDULE ret = null; try { ret = (CSU_C09_STUDY_SCHEDULE)this.GetStructure("STUDY_SCHEDULE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of CSU_C09_STUDY_SCHEDULE /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public CSU_C09_STUDY_SCHEDULE GetSTUDY_SCHEDULE(int rep) { return (CSU_C09_STUDY_SCHEDULE)this.GetStructure("STUDY_SCHEDULE", rep); } /** * Returns the number of existing repetitions of CSU_C09_STUDY_SCHEDULE */ public int STUDY_SCHEDULERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("STUDY_SCHEDULE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the CSU_C09_STUDY_SCHEDULE results */ public IEnumerable<CSU_C09_STUDY_SCHEDULE> STUDY_SCHEDULEs { get { for (int rep = 0; rep < STUDY_SCHEDULERepetitionsUsed; rep++) { yield return (CSU_C09_STUDY_SCHEDULE)this.GetStructure("STUDY_SCHEDULE", rep); } } } ///<summary> ///Adds a new CSU_C09_STUDY_SCHEDULE ///</summary> public CSU_C09_STUDY_SCHEDULE AddSTUDY_SCHEDULE() { return this.AddStructure("STUDY_SCHEDULE") as CSU_C09_STUDY_SCHEDULE; } ///<summary> ///Removes the given CSU_C09_STUDY_SCHEDULE ///</summary> public void RemoveSTUDY_SCHEDULE(CSU_C09_STUDY_SCHEDULE toRemove) { this.RemoveStructure("STUDY_SCHEDULE", toRemove); } ///<summary> ///Removes the CSU_C09_STUDY_SCHEDULE at the given index ///</summary> public void RemoveSTUDY_SCHEDULEAt(int index) { this.RemoveRepetition("STUDY_SCHEDULE", index); } } }
30.345865
157
0.705897
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V271/Group/CSU_C09_STUDY_PHASE.cs
4,036
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.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit.Abstractions; namespace Microsoft.EntityFrameworkCore.Query { public class OwnedQuerySqlServerTest : OwnedQueryRelationalTestBase<OwnedQuerySqlServerTest.OwnedQuerySqlServerFixture> { public OwnedQuerySqlServerTest(OwnedQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) : base(fixture) { //Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } protected override bool CanExecuteQueryString => true; public override async Task Query_with_owned_entity_equality_operator(bool async) { await base.Query_with_owned_entity_equality_operator(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] CROSS JOIN ( SELECT [o0].[Id] FROM [OwnedPerson] AS [o0] WHERE [o0].[Discriminator] = N'LeafB' ) AS [t] LEFT JOIN ( SELECT [o1].[ClientId], [o1].[Id], [o1].[OrderDate], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id] AS [Id0], [o2].[Detail] FROM [Order] AS [o1] LEFT JOIN [OrderDetail] AS [o2] ON ([o1].[ClientId] = [o2].[OrderClientId]) AND ([o1].[Id] = [o2].[OrderId]) ) AS [t0] ON [o].[Id] = [t0].[ClientId] WHERE 0 = 1 ORDER BY [o].[Id], [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Query_for_base_type_loads_all_owned_navs(bool async) { await base.Query_for_base_type_loads_all_owned_navs(async); // See issue #10067 AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task No_ignored_include_warning_when_implicit_load(bool async) { await base.No_ignored_include_warning_when_implicit_load(async); AssertSql( @"SELECT COUNT(*) FROM [OwnedPerson] AS [o]"); } public override async Task Query_for_branch_type_loads_all_owned_navs(bool async) { await base.Query_for_branch_type_loads_all_owned_navs(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[Discriminator] IN (N'Branch', N'LeafA') ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Query_for_branch_type_loads_all_owned_navs_tracking(bool async) { await base.Query_for_branch_type_loads_all_owned_navs_tracking(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[Discriminator] IN (N'Branch', N'LeafA') ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Query_for_leaf_type_loads_all_owned_navs(bool async) { await base.Query_for_leaf_type_loads_all_owned_navs(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[Discriminator] = N'LeafA' ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Query_when_subquery(bool async) { await base.Query_when_subquery(async); AssertSql( @"@__p_0='5' SELECT [t0].[Id], [t0].[Discriminator], [t0].[Name], [t1].[ClientId], [t1].[Id], [t1].[OrderDate], [t1].[OrderClientId], [t1].[OrderId], [t1].[Id0], [t1].[Detail], [t0].[PersonAddress_AddressLine], [t0].[PersonAddress_PlaceType], [t0].[PersonAddress_ZipCode], [t0].[PersonAddress_Country_Name], [t0].[PersonAddress_Country_PlanetId], [t0].[BranchAddress_BranchName], [t0].[BranchAddress_PlaceType], [t0].[BranchAddress_Country_Name], [t0].[BranchAddress_Country_PlanetId], [t0].[LeafBAddress_LeafBType], [t0].[LeafBAddress_PlaceType], [t0].[LeafBAddress_Country_Name], [t0].[LeafBAddress_Country_PlanetId], [t0].[LeafAAddress_LeafType], [t0].[LeafAAddress_PlaceType], [t0].[LeafAAddress_Country_Name], [t0].[LeafAAddress_Country_PlanetId] FROM ( SELECT TOP(@__p_0) [t].[Id], [t].[Discriminator], [t].[Name], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT DISTINCT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ) AS [t] ORDER BY [t].[Id] ) AS [t0] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t1] ON [t0].[Id] = [t1].[ClientId] ORDER BY [t0].[Id], [t1].[ClientId], [t1].[Id], [t1].[OrderClientId], [t1].[OrderId]"); } public override async Task Navigation_rewrite_on_owned_reference_projecting_scalar(bool async) { await base.Navigation_rewrite_on_owned_reference_projecting_scalar(async); AssertSql( @"SELECT [o].[PersonAddress_Country_Name] FROM [OwnedPerson] AS [o] WHERE [o].[PersonAddress_Country_Name] = N'USA'"); } public override async Task Navigation_rewrite_on_owned_reference_projecting_entity(bool async) { await base.Navigation_rewrite_on_owned_reference_projecting_entity(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[PersonAddress_Country_Name] = N'USA' ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Navigation_rewrite_on_owned_collection(bool async) { await base.Navigation_rewrite_on_owned_collection(async); AssertSql( @"SELECT [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o1].[ClientId], [o1].[Id], [o1].[OrderDate], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id] AS [Id0], [o2].[Detail] FROM [Order] AS [o1] LEFT JOIN [OrderDetail] AS [o2] ON ([o1].[ClientId] = [o2].[OrderClientId]) AND ([o1].[Id] = [o2].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE ( SELECT COUNT(*) FROM [Order] AS [o0] WHERE [o].[Id] = [o0].[ClientId]) > 0 ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Navigation_rewrite_on_owned_collection_with_composition(bool async) { await base.Navigation_rewrite_on_owned_collection_with_composition(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) CASE WHEN [o0].[Id] <> 42 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Order] AS [o0] WHERE [o].[Id] = [o0].[ClientId] ORDER BY [o0].[Id]), CAST(0 AS bit)) FROM [OwnedPerson] AS [o] ORDER BY [o].[Id]"); } public override async Task Navigation_rewrite_on_owned_collection_with_composition_complex(bool async) { await base.Navigation_rewrite_on_owned_collection_with_composition_complex(async); AssertSql( @"SELECT ( SELECT TOP(1) [o1].[PersonAddress_Country_Name] FROM [Order] AS [o0] LEFT JOIN [OwnedPerson] AS [o1] ON [o0].[ClientId] = [o1].[Id] WHERE [o].[Id] = [o0].[ClientId] ORDER BY [o0].[Id]) FROM [OwnedPerson] AS [o]"); } public override async Task SelectMany_on_owned_collection(bool async) { await base.SelectMany_on_owned_collection(async); AssertSql( @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id], [o1].[OrderClientId], [o1].[OrderId]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity(async); AssertSql( @"SELECT [p].[Id], [p].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id]"); } public override async Task Filter_owned_entity_chained_with_regular_entity_followed_by_projecting_owned_collection(bool async) { await base.Filter_owned_entity_chained_with_regular_entity_followed_by_projecting_owned_collection(async); AssertSql( @"SELECT [o].[Id], [p].[Id], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE ([p].[Id] <> 42) OR ([p].[Id] IS NULL) ORDER BY [o].[Id], [p].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Project_multiple_owned_navigations(bool async) { await base.Project_multiple_owned_navigations(async); AssertSql( @"SELECT [o].[Id], [p].[Id], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [p].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] ORDER BY [o].[Id], [p].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Project_multiple_owned_navigations_with_expansion_on_owned_collections(bool async) { await base.Project_multiple_owned_navigations_with_expansion_on_owned_collections(async); AssertSql( @"SELECT ( SELECT COUNT(*) FROM [Order] AS [o0] LEFT JOIN [OwnedPerson] AS [o1] ON [o0].[ClientId] = [o1].[Id] LEFT JOIN [Planet] AS [p0] ON [o1].[PersonAddress_Country_PlanetId] = [p0].[Id] LEFT JOIN [Star] AS [s] ON [p0].[StarId] = [s].[Id] WHERE ([o].[Id] = [o0].[ClientId]) AND (([s].[Id] <> 42) OR ([s].[Id] IS NULL))) AS [Count], [p].[Id], [p].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] ORDER BY [o].[Id]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_filter(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_filter(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [p].[Id], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE ([p].[Id] <> 7) OR ([p].[Id] IS NULL) ORDER BY [o].[Id], [p].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_property(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_property(async); AssertSql( @"SELECT [p].[Id] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection(async); AssertSql( @"SELECT [o].[Id], [p].[Id], [m].[Id], [m].[Diameter], [m].[PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN [Moon] AS [m] ON [p].[Id] = [m].[PlanetId] ORDER BY [o].[Id], [p].[Id]"); } public override async Task SelectMany_on_owned_reference_followed_by_regular_entity_and_collection(bool async) { await base.SelectMany_on_owned_reference_followed_by_regular_entity_and_collection(async); AssertSql( @"SELECT [m].[Id], [m].[Diameter], [m].[PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] INNER JOIN [Moon] AS [m] ON [p].[Id] = [m].[PlanetId]"); } public override async Task SelectMany_on_owned_reference_with_entity_in_between_ending_in_owned_collection(bool async) { await base.SelectMany_on_owned_reference_with_entity_in_between_ending_in_owned_collection(async); AssertSql( @"SELECT [e].[Id], [e].[Name], [e].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN [Star] AS [s] ON [p].[StarId] = [s].[Id] INNER JOIN [Element] AS [e] ON [s].[Id] = [e].[StarId]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference(async); AssertSql( @"SELECT [s].[Id], [s].[Name], [o].[Id], [p].[Id], [e].[Id], [e].[Name], [e].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN [Star] AS [s] ON [p].[StarId] = [s].[Id] LEFT JOIN [Element] AS [e] ON [s].[Id] = [e].[StarId] ORDER BY [o].[Id], [p].[Id], [s].[Id]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar( bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar(async); AssertSql( @"SELECT [s].[Name] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN [Star] AS [s] ON [p].[StarId] = [s].[Id]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection( async); AssertSql( @"SELECT [s].[Id], [s].[Name], [o].[Id], [p].[Id], [e].[Id], [e].[Name], [e].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN [Star] AS [s] ON [p].[StarId] = [s].[Id] LEFT JOIN [Element] AS [e] ON [s].[Id] = [e].[StarId] WHERE [s].[Name] = N'Sol' ORDER BY [o].[Id], [p].[Id], [s].[Id]"); } public override async Task Query_with_OfType_eagerly_loads_correct_owned_navigations(bool async) { await base.Query_with_OfType_eagerly_loads_correct_owned_navigations(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[Discriminator] = N'LeafA' ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Preserve_includes_when_applying_skip_take_after_anonymous_type_select(bool async) { await base.Preserve_includes_when_applying_skip_take_after_anonymous_type_select(async); AssertSql( @"SELECT COUNT(*) FROM [OwnedPerson] AS [o]", // @"@__p_1='0' @__p_2='100' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Unmapped_property_projection_loads_owned_navigations(bool async) { await base.Unmapped_property_projection_loads_owned_navigations(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[Id] = 1 ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Client_method_skip_loads_owned_navigations(bool async) { await base.Client_method_skip_loads_owned_navigations(async); AssertSql( @"@__p_0='1' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] OFFSET @__p_0 ROWS ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Client_method_take_loads_owned_navigations(bool async) { await base.Client_method_take_loads_owned_navigations(async); AssertSql( @"@__p_0='2' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT TOP(@__p_0) [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Client_method_skip_take_loads_owned_navigations(bool async) { await base.Client_method_skip_take_loads_owned_navigations(async); AssertSql( @"@__p_0='1' @__p_1='2' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Client_method_skip_loads_owned_navigations_variation_2(bool async) { await base.Client_method_skip_loads_owned_navigations_variation_2(async); AssertSql( @"@__p_0='1' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] OFFSET @__p_0 ROWS ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Client_method_take_loads_owned_navigations_variation_2(bool async) { await base.Client_method_take_loads_owned_navigations_variation_2(async); AssertSql( @"@__p_0='2' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT TOP(@__p_0) [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Client_method_skip_take_loads_owned_navigations_variation_2(bool async) { await base.Client_method_skip_take_loads_owned_navigations_variation_2(async); AssertSql( @"@__p_0='1' @__p_1='2' SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t0].[ClientId], [t0].[Id], [t0].[OrderDate], [t0].[OrderClientId], [t0].[OrderId], [t0].[Id0], [t0].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id] OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY ) AS [t] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t0] ON [t].[Id] = [t0].[ClientId] ORDER BY [t].[Id], [t0].[ClientId], [t0].[Id], [t0].[OrderClientId], [t0].[OrderId]"); } public override async Task Where_owned_collection_navigation_ToList_Count(bool async) { await base.Where_owned_collection_navigation_ToList_Count(async); AssertSql( @"SELECT [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id], [o2].[Detail] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] LEFT JOIN [OrderDetail] AS [o2] ON ([o0].[ClientId] = [o2].[OrderClientId]) AND ([o0].[Id] = [o2].[OrderId]) WHERE ( SELECT COUNT(*) FROM [OrderDetail] AS [o1] WHERE ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId])) = 0 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId]"); } public override async Task Where_collection_navigation_ToArray_Count(bool async) { await base.Where_collection_navigation_ToArray_Count(async); AssertSql( @"SELECT [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id], [o2].[Detail] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] LEFT JOIN [OrderDetail] AS [o2] ON ([o0].[ClientId] = [o2].[OrderClientId]) AND ([o0].[Id] = [o2].[OrderId]) WHERE ( SELECT COUNT(*) FROM [OrderDetail] AS [o1] WHERE ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId])) = 0 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId]"); } public override async Task Where_collection_navigation_AsEnumerable_Count(bool async) { await base.Where_collection_navigation_AsEnumerable_Count(async); AssertSql( @"SELECT [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id], [o2].[Detail] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] LEFT JOIN [OrderDetail] AS [o2] ON ([o0].[ClientId] = [o2].[OrderClientId]) AND ([o0].[Id] = [o2].[OrderId]) WHERE ( SELECT COUNT(*) FROM [OrderDetail] AS [o1] WHERE ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId])) = 0 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId]"); } public override async Task Where_collection_navigation_ToList_Count_member(bool async) { await base.Where_collection_navigation_ToList_Count_member(async); AssertSql( @"SELECT [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id], [o2].[Detail] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] LEFT JOIN [OrderDetail] AS [o2] ON ([o0].[ClientId] = [o2].[OrderClientId]) AND ([o0].[Id] = [o2].[OrderId]) WHERE ( SELECT COUNT(*) FROM [OrderDetail] AS [o1] WHERE ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId])) = 0 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId]"); } public override async Task Where_collection_navigation_ToArray_Length_member(bool async) { await base.Where_collection_navigation_ToArray_Length_member(async); AssertSql( @"SELECT [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId], [o2].[Id], [o2].[Detail] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] LEFT JOIN [OrderDetail] AS [o2] ON ([o0].[ClientId] = [o2].[OrderClientId]) AND ([o0].[Id] = [o2].[OrderId]) WHERE ( SELECT COUNT(*) FROM [OrderDetail] AS [o1] WHERE ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId])) = 0 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id], [o2].[OrderClientId], [o2].[OrderId]"); } public override async Task Can_query_on_indexer_properties(bool async) { await base.Can_query_on_indexer_properties(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[Name] = N'Mona Cy' ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Can_query_on_owned_indexer_properties(bool async) { await base.Can_query_on_owned_indexer_properties(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] WHERE [o].[PersonAddress_ZipCode] = 38654"); } public override async Task Can_query_on_indexer_property_when_property_name_from_closure(bool async) { await base.Can_query_on_indexer_property_when_property_name_from_closure(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] WHERE [o].[Name] = N'Mona Cy'"); } public override async Task Can_project_indexer_properties(bool async) { await base.Can_project_indexer_properties(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o]"); } public override async Task Can_project_owned_indexer_properties(bool async) { await base.Can_project_owned_indexer_properties(async); AssertSql( @"SELECT [o].[PersonAddress_AddressLine] FROM [OwnedPerson] AS [o]"); } public override async Task Can_project_indexer_properties_converted(bool async) { await base.Can_project_indexer_properties_converted(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o]"); } public override async Task Can_project_owned_indexer_properties_converted(bool async) { await base.Can_project_owned_indexer_properties_converted(async); AssertSql( @"SELECT [o].[PersonAddress_AddressLine] FROM [OwnedPerson] AS [o]"); } public override async Task Can_OrderBy_indexer_properties(bool async) { await base.Can_OrderBy_indexer_properties(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] ORDER BY [o].[Name], [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Can_OrderBy_indexer_properties_converted(bool async) { await base.Can_OrderBy_indexer_properties_converted(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] ORDER BY [o].[Name], [o].[Id]"); } public override async Task Can_OrderBy_owned_indexer_properties(bool async) { await base.Can_OrderBy_owned_indexer_properties(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] ORDER BY [o].[PersonAddress_ZipCode], [o].[Id]"); } public override async Task Can_OrderBy_owened_indexer_properties_converted(bool async) { await base.Can_OrderBy_owened_indexer_properties_converted(async); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] ORDER BY [o].[PersonAddress_ZipCode], [o].[Id]"); } public override async Task Can_group_by_indexer_property(bool isAsync) { await base.Can_group_by_indexer_property(isAsync); AssertSql( @"SELECT COUNT(*) FROM [OwnedPerson] AS [o] GROUP BY [o].[Name]"); } public override async Task Can_group_by_converted_indexer_property(bool isAsync) { await base.Can_group_by_converted_indexer_property(isAsync); AssertSql( @"SELECT COUNT(*) FROM [OwnedPerson] AS [o] GROUP BY [o].[Name]"); } public override async Task Can_group_by_owned_indexer_property(bool isAsync) { await base.Can_group_by_owned_indexer_property(isAsync); AssertSql( @"SELECT COUNT(*) FROM [OwnedPerson] AS [o] GROUP BY [o].[PersonAddress_ZipCode]"); } public override async Task Can_group_by_converted_owned_indexer_property(bool isAsync) { await base.Can_group_by_converted_owned_indexer_property(isAsync); AssertSql( @"SELECT COUNT(*) FROM [OwnedPerson] AS [o] GROUP BY [o].[PersonAddress_ZipCode]"); } public override async Task Can_join_on_indexer_property_on_query(bool isAsync) { await base.Can_join_on_indexer_property_on_query(isAsync); AssertSql( @"SELECT [o].[Id], [o0].[PersonAddress_Country_Name] AS [Name] FROM [OwnedPerson] AS [o] INNER JOIN [OwnedPerson] AS [o0] ON [o].[PersonAddress_ZipCode] = [o0].[PersonAddress_ZipCode]"); } public override async Task Projecting_indexer_property_ignores_include(bool isAsync) { await base.Projecting_indexer_property_ignores_include(isAsync); AssertSql( @"SELECT [o].[PersonAddress_ZipCode] AS [Nation] FROM [OwnedPerson] AS [o]"); } public override async Task Projecting_indexer_property_ignores_include_converted(bool isAsync) { await base.Projecting_indexer_property_ignores_include_converted(isAsync); AssertSql( @"SELECT [o].[PersonAddress_ZipCode] AS [Nation] FROM [OwnedPerson] AS [o]"); } public override async Task Indexer_property_is_pushdown_into_subquery(bool isAsync) { await base.Indexer_property_is_pushdown_into_subquery(isAsync); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] WHERE ( SELECT TOP(1) [o0].[Name] FROM [OwnedPerson] AS [o0] WHERE [o0].[Id] = [o].[Id]) = N'Mona Cy'"); } public override async Task Can_query_indexer_property_on_owned_collection(bool isAsync) { await base.Can_query_indexer_property_on_owned_collection(isAsync); AssertSql( @"SELECT [o].[Name] FROM [OwnedPerson] AS [o] WHERE ( SELECT COUNT(*) FROM [Order] AS [o0] WHERE ([o].[Id] = [o0].[ClientId]) AND (DATEPART(year, [o0].[OrderDate]) = 2018)) = 1"); } public override async Task Query_for_base_type_loads_all_owned_navs_split(bool async) { await base.Query_for_base_type_loads_all_owned_navs_split(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ORDER BY [o].[Id]", // @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]", // @"SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [o].[Id], [o0].[ClientId], [o0].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task Query_for_branch_type_loads_all_owned_navs_split(bool async) { await base.Query_for_branch_type_loads_all_owned_navs_split(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] WHERE [o].[Discriminator] IN (N'Branch', N'LeafA') ORDER BY [o].[Id]", // @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] WHERE [o].[Discriminator] IN (N'Branch', N'LeafA') ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]", // @"SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [o].[Id], [o0].[ClientId], [o0].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) WHERE [o].[Discriminator] IN (N'Branch', N'LeafA') ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task Query_when_subquery_split(bool async) { await base.Query_when_subquery_split(async); AssertSql( @"@__p_0='5' SELECT TOP(@__p_0) [t].[Id], [t].[Discriminator], [t].[Name], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t].[BranchAddress_BranchName], [t].[BranchAddress_PlaceType], [t].[BranchAddress_Country_Name], [t].[BranchAddress_Country_PlanetId], [t].[LeafBAddress_LeafBType], [t].[LeafBAddress_PlaceType], [t].[LeafBAddress_Country_Name], [t].[LeafBAddress_Country_PlanetId], [t].[LeafAAddress_LeafType], [t].[LeafAAddress_PlaceType], [t].[LeafAAddress_Country_Name], [t].[LeafAAddress_Country_PlanetId] FROM ( SELECT DISTINCT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ) AS [t] ORDER BY [t].[Id]", // @"@__p_0='5' SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [t0].[Id] FROM ( SELECT TOP(@__p_0) [t].[Id] FROM ( SELECT DISTINCT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ) AS [t] ORDER BY [t].[Id] ) AS [t0] INNER JOIN [Order] AS [o0] ON [t0].[Id] = [o0].[ClientId] ORDER BY [t0].[Id], [o0].[ClientId], [o0].[Id]", // @"@__p_0='5' SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [t0].[Id], [o0].[ClientId], [o0].[Id] FROM ( SELECT TOP(@__p_0) [t].[Id] FROM ( SELECT DISTINCT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ) AS [t] ORDER BY [t].[Id] ) AS [t0] INNER JOIN [Order] AS [o0] ON [t0].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ORDER BY [t0].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task Project_multiple_owned_navigations_split(bool async) { await base.Project_multiple_owned_navigations_split(async); AssertSql( @"SELECT [o].[Id], [p].[Id], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [p].[StarId] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] ORDER BY [o].[Id], [p].[Id]", // @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id], [p].[Id] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] ORDER BY [o].[Id], [p].[Id], [o0].[ClientId], [o0].[Id]", // @"SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [o].[Id], [p].[Id], [o0].[ClientId], [o0].[Id] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ORDER BY [o].[Id], [p].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection_split(bool async) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_collection_split(async); AssertSql( @"SELECT [o].[Id], [p].[Id] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] ORDER BY [o].[Id], [p].[Id]", // @"SELECT [m].[Id], [m].[Diameter], [m].[PlanetId], [o].[Id], [p].[Id] FROM [OwnedPerson] AS [o] LEFT JOIN [Planet] AS [p] ON [o].[PersonAddress_Country_PlanetId] = [p].[Id] INNER JOIN [Moon] AS [m] ON [p].[Id] = [m].[PlanetId] ORDER BY [o].[Id], [p].[Id]"); } public override async Task Query_with_OfType_eagerly_loads_correct_owned_navigations_split(bool async) { await base.Query_with_OfType_eagerly_loads_correct_owned_navigations_split(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] WHERE [o].[Discriminator] = N'LeafA' ORDER BY [o].[Id]", // @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] WHERE [o].[Discriminator] = N'LeafA' ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]", // @"SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [o].[Id], [o0].[ClientId], [o0].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) WHERE [o].[Discriminator] = N'LeafA' ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task Unmapped_property_projection_loads_owned_navigations_split(bool async) { await base.Unmapped_property_projection_loads_owned_navigations_split(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] WHERE [o].[Id] = 1 ORDER BY [o].[Id]", // @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] WHERE [o].[Id] = 1 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]", // @"SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [o].[Id], [o0].[ClientId], [o0].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) WHERE [o].[Id] = 1 ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task Can_query_on_indexer_properties_split(bool async) { await base.Can_query_on_indexer_properties_split(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] WHERE [o].[Name] = N'Mona Cy' ORDER BY [o].[Id]", // @"SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] WHERE [o].[Name] = N'Mona Cy' ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]", // @"SELECT [o1].[OrderClientId], [o1].[OrderId], [o1].[Id], [o1].[Detail], [o].[Id], [o0].[ClientId], [o0].[Id] FROM [OwnedPerson] AS [o] INNER JOIN [Order] AS [o0] ON [o].[Id] = [o0].[ClientId] INNER JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) WHERE [o].[Name] = N'Mona Cy' ORDER BY [o].[Id], [o0].[ClientId], [o0].[Id]"); } public override async Task GroupBy_with_multiple_aggregates_on_owned_navigation_properties(bool async) { await base.GroupBy_with_multiple_aggregates_on_owned_navigation_properties(async); AssertSql( @"SELECT AVG(CAST([s].[Id] AS float)) AS [p1], COALESCE(SUM([s].[Id]), 0) AS [p2], MAX(CAST(LEN([s].[Name]) AS int)) AS [p3] FROM ( SELECT 1 AS [Key], [o].[PersonAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] ) AS [t] LEFT JOIN [Planet] AS [p] ON [t].[PersonAddress_Country_PlanetId] = [p].[Id] LEFT JOIN [Star] AS [s] ON [p].[StarId] = [s].[Id] GROUP BY [t].[Key]"); } public override async Task Ordering_by_identifying_projection(bool async) { await base.Ordering_by_identifying_projection(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] ORDER BY [o].[PersonAddress_PlaceType], [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Using_from_sql_on_owner_generates_join_with_table_for_owned_shared_dependents(bool async) { await base.Using_from_sql_on_owner_generates_join_with_table_for_owned_shared_dependents(async); AssertSql( @"SELECT [m].[Id], [m].[Discriminator], [m].[Name], [t].[Id], [t].[Id0], [t0].[Id], [t0].[Id0], [t2].[Id], [t2].[Id0], [t4].[Id], [t4].[Id0], [t6].[ClientId], [t6].[Id], [t6].[OrderDate], [t6].[OrderClientId], [t6].[OrderId], [t6].[Id0], [t6].[Detail], [t].[PersonAddress_AddressLine], [t].[PersonAddress_PlaceType], [t].[PersonAddress_ZipCode], [t].[Id1], [t].[PersonAddress_Country_Name], [t].[PersonAddress_Country_PlanetId], [t0].[BranchAddress_BranchName], [t0].[BranchAddress_PlaceType], [t0].[Id1], [t0].[BranchAddress_Country_Name], [t0].[BranchAddress_Country_PlanetId], [t2].[LeafBAddress_LeafBType], [t2].[LeafBAddress_PlaceType], [t2].[Id1], [t2].[LeafBAddress_Country_Name], [t2].[LeafBAddress_Country_PlanetId], [t4].[LeafAAddress_LeafType], [t4].[LeafAAddress_PlaceType], [t4].[Id1], [t4].[LeafAAddress_Country_Name], [t4].[LeafAAddress_Country_PlanetId] FROM ( SELECT * FROM ""OwnedPerson"" ) AS [m] LEFT JOIN ( SELECT [o].[Id], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o0].[Id] AS [Id0], [o].[Id] AS [Id1], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] INNER JOIN [OwnedPerson] AS [o0] ON [o].[Id] = [o0].[Id] WHERE [o].[PersonAddress_ZipCode] IS NOT NULL ) AS [t] ON [m].[Id] = CASE WHEN [t].[PersonAddress_ZipCode] IS NOT NULL THEN [t].[Id] END LEFT JOIN ( SELECT [o1].[Id], [o1].[BranchAddress_BranchName], [o1].[BranchAddress_PlaceType], [t1].[Id] AS [Id0], [o1].[Id] AS [Id1], [o1].[BranchAddress_Country_Name], [o1].[BranchAddress_Country_PlanetId] FROM [OwnedPerson] AS [o1] INNER JOIN ( SELECT [o2].[Id] FROM [OwnedPerson] AS [o2] WHERE [o2].[Discriminator] IN (N'Branch', N'LeafA') ) AS [t1] ON [o1].[Id] = [t1].[Id] WHERE [o1].[BranchAddress_BranchName] IS NOT NULL ) AS [t0] ON [m].[Id] = CASE WHEN [t0].[BranchAddress_BranchName] IS NOT NULL THEN [t0].[Id] END LEFT JOIN ( SELECT [o3].[Id], [o3].[LeafBAddress_LeafBType], [o3].[LeafBAddress_PlaceType], [t3].[Id] AS [Id0], [o3].[Id] AS [Id1], [o3].[LeafBAddress_Country_Name], [o3].[LeafBAddress_Country_PlanetId] FROM [OwnedPerson] AS [o3] INNER JOIN ( SELECT [o4].[Id] FROM [OwnedPerson] AS [o4] WHERE [o4].[Discriminator] = N'LeafB' ) AS [t3] ON [o3].[Id] = [t3].[Id] WHERE [o3].[LeafBAddress_LeafBType] IS NOT NULL ) AS [t2] ON [m].[Id] = CASE WHEN [t2].[LeafBAddress_LeafBType] IS NOT NULL THEN [t2].[Id] END LEFT JOIN ( SELECT [o5].[Id], [o5].[LeafAAddress_LeafType], [o5].[LeafAAddress_PlaceType], [t5].[Id] AS [Id0], [o5].[Id] AS [Id1], [o5].[LeafAAddress_Country_Name], [o5].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o5] INNER JOIN ( SELECT [o6].[Id] FROM [OwnedPerson] AS [o6] WHERE [o6].[Discriminator] = N'LeafA' ) AS [t5] ON [o5].[Id] = [t5].[Id] WHERE [o5].[LeafAAddress_LeafType] IS NOT NULL ) AS [t4] ON [m].[Id] = CASE WHEN [t4].[LeafAAddress_LeafType] IS NOT NULL THEN [t4].[Id] END LEFT JOIN ( SELECT [o7].[ClientId], [o7].[Id], [o7].[OrderDate], [o8].[OrderClientId], [o8].[OrderId], [o8].[Id] AS [Id0], [o8].[Detail] FROM [Order] AS [o7] LEFT JOIN [OrderDetail] AS [o8] ON ([o7].[ClientId] = [o8].[OrderClientId]) AND ([o7].[Id] = [o8].[OrderId]) ) AS [t6] ON [m].[Id] = [t6].[ClientId] ORDER BY [m].[Id], [t].[Id], [t].[Id0], [t0].[Id], [t0].[Id0], [t2].[Id], [t2].[Id0], [t4].[Id], [t4].[Id0], [t6].[ClientId], [t6].[Id], [t6].[OrderClientId], [t6].[OrderId]"); } public override async Task Projecting_collection_correlated_with_keyless_entity_after_navigation_works_using_parent_identifiers(bool async) { await base.Projecting_collection_correlated_with_keyless_entity_after_navigation_works_using_parent_identifiers(async); AssertSql( @"SELECT [b].[Throned_Value], [f].[Id], [b].[Id], [p].[Id], [p].[StarId] FROM [Fink] AS [f] LEFT JOIN [Barton] AS [b] ON [f].[BartonId] = [b].[Id] LEFT JOIN [Planet] AS [p] ON ([b].[Throned_Value] <> [p].[Id]) OR ([b].[Throned_Value] IS NULL) ORDER BY [f].[Id], [b].[Id]"); } public override async Task Filter_on_indexer_using_closure(bool async) { await base.Filter_on_indexer_using_closure(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[PersonAddress_ZipCode] = 38654 ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } public override async Task Filter_on_indexer_using_function_argument(bool async) { await base.Filter_on_indexer_using_function_argument(async); AssertSql( @"SELECT [o].[Id], [o].[Discriminator], [o].[Name], [t].[ClientId], [t].[Id], [t].[OrderDate], [t].[OrderClientId], [t].[OrderId], [t].[Id0], [t].[Detail], [o].[PersonAddress_AddressLine], [o].[PersonAddress_PlaceType], [o].[PersonAddress_ZipCode], [o].[PersonAddress_Country_Name], [o].[PersonAddress_Country_PlanetId], [o].[BranchAddress_BranchName], [o].[BranchAddress_PlaceType], [o].[BranchAddress_Country_Name], [o].[BranchAddress_Country_PlanetId], [o].[LeafBAddress_LeafBType], [o].[LeafBAddress_PlaceType], [o].[LeafBAddress_Country_Name], [o].[LeafBAddress_Country_PlanetId], [o].[LeafAAddress_LeafType], [o].[LeafAAddress_PlaceType], [o].[LeafAAddress_Country_Name], [o].[LeafAAddress_Country_PlanetId] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[ClientId], [o0].[Id], [o0].[OrderDate], [o1].[OrderClientId], [o1].[OrderId], [o1].[Id] AS [Id0], [o1].[Detail] FROM [Order] AS [o0] LEFT JOIN [OrderDetail] AS [o1] ON ([o0].[ClientId] = [o1].[OrderClientId]) AND ([o0].[Id] = [o1].[OrderId]) ) AS [t] ON [o].[Id] = [t].[ClientId] WHERE [o].[PersonAddress_ZipCode] = 38654 ORDER BY [o].[Id], [t].[ClientId], [t].[Id], [t].[OrderClientId], [t].[OrderId]"); } private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); public class OwnedQuerySqlServerFixture : RelationalOwnedQueryFixture { protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; } } }
62.686371
885
0.649348
[ "MIT" ]
SpaceChina/efcore
test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs
76,352
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Data; using BTCPayServer.Events; using BTCPayServer.Logging; using BTCPayServer.Models; using BTCPayServer.Payments; using BTCPayServer.Rating; using BTCPayServer.Security; using BTCPayServer.Services.Apps; using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Rates; using BTCPayServer.Services.Stores; using BTCPayServer.Services.Wallets; using BTCPayServer.Validation; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using NBitcoin; using NBitpayClient; using Newtonsoft.Json; namespace BTCPayServer.Controllers { public partial class InvoiceController : Controller { InvoiceRepository _InvoiceRepository; ContentSecurityPolicies _CSP; RateFetcher _RateProvider; StoreRepository _StoreRepository; UserManager<ApplicationUser> _UserManager; private CurrencyNameTable _CurrencyNameTable; EventAggregator _EventAggregator; BTCPayNetworkProvider _NetworkProvider; private readonly PaymentMethodHandlerDictionary _paymentMethodHandlerDictionary; IServiceProvider _ServiceProvider; public InvoiceController( IServiceProvider serviceProvider, InvoiceRepository invoiceRepository, CurrencyNameTable currencyNameTable, UserManager<ApplicationUser> userManager, RateFetcher rateProvider, StoreRepository storeRepository, EventAggregator eventAggregator, ContentSecurityPolicies csp, BTCPayNetworkProvider networkProvider, PaymentMethodHandlerDictionary paymentMethodHandlerDictionary) { _ServiceProvider = serviceProvider; _CurrencyNameTable = currencyNameTable ?? throw new ArgumentNullException(nameof(currencyNameTable)); _StoreRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository)); _InvoiceRepository = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository)); _RateProvider = rateProvider ?? throw new ArgumentNullException(nameof(rateProvider)); _UserManager = userManager; _EventAggregator = eventAggregator; _NetworkProvider = networkProvider; _paymentMethodHandlerDictionary = paymentMethodHandlerDictionary; _CSP = csp; } internal async Task<DataWrapper<InvoiceResponse>> CreateInvoiceCore(CreateInvoiceRequest invoice, StoreData store, string serverUrl, List<string> additionalTags = null, CancellationToken cancellationToken = default) { if (!store.HasClaim(Policies.CanCreateInvoice.Key)) throw new UnauthorizedAccessException(); InvoiceLogs logs = new InvoiceLogs(); logs.Write("Creation of invoice starting"); var entity = _InvoiceRepository.CreateNewInvoice(); var getAppsTaggingStore = _InvoiceRepository.GetAppsTaggingStore(store.Id); var storeBlob = store.GetStoreBlob(); EmailAddressAttribute emailValidator = new EmailAddressAttribute(); entity.ExpirationTime = entity.InvoiceTime.AddMinutes(storeBlob.InvoiceExpiration); entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration); entity.OrderId = invoice.OrderId; entity.ServerUrl = serverUrl; entity.FullNotifications = invoice.FullNotifications || invoice.ExtendedNotifications; entity.ExtendedNotifications = invoice.ExtendedNotifications; if (invoice.NotificationURL != null && Uri.TryCreate(invoice.NotificationURL, UriKind.Absolute, out var notificationUri) && (notificationUri.Scheme == "http" || notificationUri.Scheme == "https")) { entity.NotificationURL = notificationUri.AbsoluteUri; } entity.NotificationEmail = invoice.NotificationEmail; entity.BuyerInformation = Map<CreateInvoiceRequest, BuyerInformation>(invoice); entity.PaymentTolerance = storeBlob.PaymentTolerance; if (additionalTags != null) entity.InternalTags.AddRange(additionalTags); //Another way of passing buyer info to support FillBuyerInfo(invoice.Buyer, entity.BuyerInformation); if (entity?.BuyerInformation?.BuyerEmail != null) { if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail)) throw new BitpayHttpException(400, "Invalid email"); entity.RefundMail = entity.BuyerInformation.BuyerEmail; } var taxIncluded = invoice.TaxIncluded.HasValue ? invoice.TaxIncluded.Value : 0m; var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(invoice.Currency, false); if (currencyInfo != null) { int divisibility = currencyInfo.CurrencyDecimalDigits; invoice.Price = invoice.Price.RoundToSignificant(ref divisibility); divisibility = currencyInfo.CurrencyDecimalDigits; invoice.TaxIncluded = taxIncluded.RoundToSignificant(ref divisibility); } invoice.Price = Math.Max(0.0m, invoice.Price); invoice.TaxIncluded = Math.Max(0.0m, taxIncluded); invoice.TaxIncluded = Math.Min(taxIncluded, invoice.Price); entity.ProductInformation = Map<CreateInvoiceRequest, ProductInformation>(invoice); entity.RedirectURL = invoice.RedirectURL ?? store.StoreWebsite; if (!Uri.IsWellFormedUriString(entity.RedirectURL, UriKind.Absolute)) entity.RedirectURL = null; entity.RedirectAutomatically = invoice.RedirectAutomatically.GetValueOrDefault(storeBlob.RedirectAutomatically); entity.Status = InvoiceStatus.New; entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy); HashSet<CurrencyPair> currencyPairsToFetch = new HashSet<CurrencyPair>(); var rules = storeBlob.GetRateRules(_NetworkProvider); var excludeFilter = storeBlob.GetExcludedPaymentMethods(); // Here we can compose filters from other origin with PaymentFilter.Any() if (invoice.SupportedTransactionCurrencies != null && invoice.SupportedTransactionCurrencies.Count != 0) { var supportedTransactionCurrencies = invoice.SupportedTransactionCurrencies .Where(c => c.Value.Enabled) .Select(c => PaymentMethodId.TryParse(c.Key, out var p) ? p : null) .ToHashSet(); excludeFilter = PaymentFilter.Or(excludeFilter, PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p))); } foreach (var network in store.GetSupportedPaymentMethods(_NetworkProvider) .Where(s => !excludeFilter.Match(s.PaymentId)) .Select(c => _NetworkProvider.GetNetwork<BTCPayNetworkBase>(c.PaymentId.CryptoCode)) .Where(c => c != null)) { currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, invoice.Currency)); if (storeBlob.LightningMaxValue != null) currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.LightningMaxValue.Currency)); if (storeBlob.OnChainMinValue != null) currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.OnChainMinValue.Currency)); } var rateRules = storeBlob.GetRateRules(_NetworkProvider); var fetchingByCurrencyPair = _RateProvider.FetchRates(currencyPairsToFetch, rateRules, cancellationToken); var fetchingAll = WhenAllFetched(logs, fetchingByCurrencyPair); var supportedPaymentMethods = store.GetSupportedPaymentMethods(_NetworkProvider) .Where(s => !excludeFilter.Match(s.PaymentId)) .Select(c => (Handler: _paymentMethodHandlerDictionary[c.PaymentId], SupportedPaymentMethod: c, Network: _NetworkProvider.GetNetwork<BTCPayNetworkBase>(c.PaymentId.CryptoCode))) .Where(c => c.Network != null) .Select(o => (SupportedPaymentMethod: o.SupportedPaymentMethod, PaymentMethod: CreatePaymentMethodAsync(fetchingByCurrencyPair, o.Handler, o.SupportedPaymentMethod, o.Network, entity, store, logs))) .ToList(); List<ISupportedPaymentMethod> supported = new List<ISupportedPaymentMethod>(); var paymentMethods = new PaymentMethodDictionary(); foreach (var o in supportedPaymentMethods) { var paymentMethod = await o.PaymentMethod; if (paymentMethod == null) continue; supported.Add(o.SupportedPaymentMethod); paymentMethods.Add(paymentMethod); } if (supported.Count == 0) { StringBuilder errors = new StringBuilder(); errors.AppendLine("Warning: No wallet has been linked to your BTCPay Store. See the following link for more information on how to connect your store and wallet. (https://docs.btcpayserver.org/btcpay-basics/gettingstarted#connecting-btcpay-store-to-your-wallet)"); foreach (var error in logs.ToList()) { errors.AppendLine(error.ToString()); } throw new BitpayHttpException(400, errors.ToString()); } entity.SetSupportedPaymentMethods(supported); entity.SetPaymentMethods(paymentMethods); entity.PosData = invoice.PosData; foreach (var app in await getAppsTaggingStore) { entity.InternalTags.Add(AppService.GetAppInternalTag(app.Id)); } using (logs.Measure("Saving invoice")) { entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity); } _ = Task.Run(async () => { try { await fetchingAll; } catch (AggregateException ex) { ex.Handle(e => { logs.Write($"Error while fetching rates {ex}"); return true; }); } await _InvoiceRepository.AddInvoiceLogs(entity.Id, logs); }); _EventAggregator.Publish(new Events.InvoiceEvent(entity, 1001, InvoiceEvent.Created)); var resp = entity.EntityToDTO(); return new DataWrapper<InvoiceResponse>(resp) { Facade = "pos/invoice" }; } private Task WhenAllFetched(InvoiceLogs logs, Dictionary<CurrencyPair, Task<RateResult>> fetchingByCurrencyPair) { return Task.WhenAll(fetchingByCurrencyPair.Select(async pair => { var rateResult = await pair.Value; logs.Write($"{pair.Key}: The rating rule is {rateResult.Rule}"); logs.Write($"{pair.Key}: The evaluated rating rule is {rateResult.EvaluatedRule}"); if (rateResult.Errors.Count != 0) { var allRateRuleErrors = string.Join(", ", rateResult.Errors.ToArray()); logs.Write($"{pair.Key}: Rate rule error ({allRateRuleErrors})"); } foreach (var ex in rateResult.ExchangeExceptions) { logs.Write($"{pair.Key}: Exception reaching exchange {ex.ExchangeName} ({ex.Exception.Message})"); } }).ToArray()); } private async Task<PaymentMethod> CreatePaymentMethodAsync(Dictionary<CurrencyPair, Task<RateResult>> fetchingByCurrencyPair, IPaymentMethodHandler handler, ISupportedPaymentMethod supportedPaymentMethod, BTCPayNetworkBase network, InvoiceEntity entity, StoreData store, InvoiceLogs logs) { try { var logPrefix = $"{supportedPaymentMethod.PaymentId.ToPrettyString()}:"; var storeBlob = store.GetStoreBlob(); var preparePayment = handler.PreparePayment(supportedPaymentMethod, store, network); var rate = await fetchingByCurrencyPair[new CurrencyPair(network.CryptoCode, entity.ProductInformation.Currency)]; if (rate.BidAsk == null) { return null; } PaymentMethod paymentMethod = new PaymentMethod(); paymentMethod.ParentEntity = entity; paymentMethod.Network = network; paymentMethod.SetId(supportedPaymentMethod.PaymentId); paymentMethod.Rate = rate.BidAsk.Bid; paymentMethod.PreferOnion = this.Request.IsOnion(); using (logs.Measure($"{logPrefix} Payment method details creation")) { var paymentDetails = await handler.CreatePaymentMethodDetails(supportedPaymentMethod, paymentMethod, store, network, preparePayment); paymentMethod.SetPaymentMethodDetails(paymentDetails); } var errorMessage = await handler .IsPaymentMethodAllowedBasedOnInvoiceAmount(storeBlob, fetchingByCurrencyPair, paymentMethod.Calculate().Due, supportedPaymentMethod.PaymentId); if (errorMessage != null) { logs.Write($"{logPrefix} {errorMessage}"); return null; } #pragma warning disable CS0618 if (paymentMethod.GetId().IsBTCOnChain) { entity.TxFee = paymentMethod.NextNetworkFee; entity.Rate = paymentMethod.Rate; entity.DepositAddress = paymentMethod.DepositAddress; } #pragma warning restore CS0618 return paymentMethod; } catch (PaymentMethodUnavailableException ex) { logs.Write($"{supportedPaymentMethod.PaymentId.CryptoCode}: Payment method unavailable ({ex.Message})"); } catch (Exception ex) { logs.Write($"{supportedPaymentMethod.PaymentId.CryptoCode}: Unexpected exception ({ex.ToString()})"); } return null; } private SpeedPolicy ParseSpeedPolicy(string transactionSpeed, SpeedPolicy defaultPolicy) { if (transactionSpeed == null) return defaultPolicy; var mappings = new Dictionary<string, SpeedPolicy>(); mappings.Add("low", SpeedPolicy.LowSpeed); mappings.Add("low-medium", SpeedPolicy.LowMediumSpeed); mappings.Add("medium", SpeedPolicy.MediumSpeed); mappings.Add("high", SpeedPolicy.HighSpeed); if (!mappings.TryGetValue(transactionSpeed, out SpeedPolicy policy)) policy = defaultPolicy; return policy; } private void FillBuyerInfo(Buyer buyer, BuyerInformation buyerInformation) { if (buyer == null) return; buyerInformation.BuyerAddress1 = buyerInformation.BuyerAddress1 ?? buyer.Address1; buyerInformation.BuyerAddress2 = buyerInformation.BuyerAddress2 ?? buyer.Address2; buyerInformation.BuyerCity = buyerInformation.BuyerCity ?? buyer.City; buyerInformation.BuyerCountry = buyerInformation.BuyerCountry ?? buyer.country; buyerInformation.BuyerEmail = buyerInformation.BuyerEmail ?? buyer.email; buyerInformation.BuyerName = buyerInformation.BuyerName ?? buyer.Name; buyerInformation.BuyerPhone = buyerInformation.BuyerPhone ?? buyer.phone; buyerInformation.BuyerState = buyerInformation.BuyerState ?? buyer.State; buyerInformation.BuyerZip = buyerInformation.BuyerZip ?? buyer.zip; } private TDest Map<TFrom, TDest>(TFrom data) { return JsonConvert.DeserializeObject<TDest>(JsonConvert.SerializeObject(data)); } } }
51.664671
296
0.615322
[ "MIT" ]
badever/btcpayserver
BTCPayServer/Controllers/InvoiceController.cs
17,258
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.BotService.V20180712.Inputs { /// <summary> /// The parameters to provide for the Enterprise Channel. /// </summary> public sealed class EnterpriseChannelPropertiesArgs : Pulumi.ResourceArgs { [Input("nodes", required: true)] private InputList<Inputs.EnterpriseChannelNodeArgs>? _nodes; /// <summary> /// The nodes associated with the Enterprise Channel. /// </summary> public InputList<Inputs.EnterpriseChannelNodeArgs> Nodes { get => _nodes ?? (_nodes = new InputList<Inputs.EnterpriseChannelNodeArgs>()); set => _nodes = value; } /// <summary> /// The current state of the Enterprise Channel. /// </summary> [Input("state")] public InputUnion<string, Pulumi.AzureNextGen.BotService.V20180712.EnterpriseChannelState>? State { get; set; } public EnterpriseChannelPropertiesArgs() { } } }
31.658537
119
0.651772
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/BotService/V20180712/Inputs/EnterpriseChannelPropertiesArgs.cs
1,298
C#
using Domain.Common; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Domain.Entities { [Table("PRODUTO")] public class Product : AuditableBaseEntity { [Column("Nome")] public string Name { get; set; } [Column("CodigoDeBarras")] public string Barcode { get; set; } [Column("Descricao")] public string Description { get; set; } [Column("Taxa")] public decimal Rate { get; set; } } }
22.84
51
0.602452
[ "MIT" ]
MarcusLoyola/CleanArchitecture.WebApi
Domain/Entities/Product.cs
573
C#
using System.Threading.Tasks; using JetBrains.Annotations; namespace CreativeCoders.Core.Caching { [PublicAPI] public interface ICachedValue<TValue> { Task<TValue> GetValueAsync(); TValue Value { get; } } }
19.076923
41
0.657258
[ "Apache-2.0" ]
CreativeCodersTeam/Core
source/Core/CreativeCoders.Core/Caching/ICachedValue.cs
248
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the marketplace-catalog-2018-09-17.normal.json service model. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Amazon.Runtime; namespace Amazon.MarketplaceCatalog { /// <summary> /// Configuration for accessing Amazon MarketplaceCatalog service /// </summary> public static class AmazonMarketplaceCatalogDefaultConfiguration { /// <summary> /// Collection of all <see cref="DefaultConfiguration"/>s supported by /// MarketplaceCatalog /// </summary> public static ReadOnlyCollection<IDefaultConfiguration> GetAllConfigurations() { return new ReadOnlyCollection<IDefaultConfiguration>(new List<IDefaultConfiguration> { Standard, InRegion, CrossRegion, Mobile, Auto, Legacy }); } /// <summary> /// <p>The STANDARD mode provides the latest recommended default values that should be safe to run in most scenarios</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> public static IDefaultConfiguration Standard {get;} = new DefaultConfiguration { Name = DefaultConfigurationMode.Standard, RetryMode = RequestRetryMode.Standard, StsRegionalEndpoints = StsRegionalEndpointsValue.Regional, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Regional, // 0:00:03.1 ConnectTimeout = TimeSpan.FromMilliseconds(3100L), // 0:00:03.1 TlsNegotiationTimeout = TimeSpan.FromMilliseconds(3100L), TimeToFirstByteTimeout = null, HttpRequestTimeout = null }; /// <summary> /// <p>The IN_REGION mode builds on the standard mode and includes optimization tailored for applications which call AWS services from within the same AWS region</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> public static IDefaultConfiguration InRegion {get;} = new DefaultConfiguration { Name = DefaultConfigurationMode.InRegion, RetryMode = RequestRetryMode.Standard, StsRegionalEndpoints = StsRegionalEndpointsValue.Regional, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Regional, // 0:00:01.1 ConnectTimeout = TimeSpan.FromMilliseconds(1100L), // 0:00:01.1 TlsNegotiationTimeout = TimeSpan.FromMilliseconds(1100L), TimeToFirstByteTimeout = null, HttpRequestTimeout = null }; /// <summary> /// <p>The CROSS_REGION mode builds on the standard mode and includes optimization tailored for applications which call AWS services in a different region</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> public static IDefaultConfiguration CrossRegion {get;} = new DefaultConfiguration { Name = DefaultConfigurationMode.CrossRegion, RetryMode = RequestRetryMode.Standard, StsRegionalEndpoints = StsRegionalEndpointsValue.Regional, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Regional, // 0:00:03.1 ConnectTimeout = TimeSpan.FromMilliseconds(3100L), // 0:00:03.1 TlsNegotiationTimeout = TimeSpan.FromMilliseconds(3100L), TimeToFirstByteTimeout = null, HttpRequestTimeout = null }; /// <summary> /// <p>The MOBILE mode builds on the standard mode and includes optimization tailored for mobile applications</p><p>Note that the default values vended from this mode might change as best practices may evolve. As a result, it is encouraged to perform tests when upgrading the SDK</p> /// </summary> public static IDefaultConfiguration Mobile {get;} = new DefaultConfiguration { Name = DefaultConfigurationMode.Mobile, RetryMode = RequestRetryMode.Standard, StsRegionalEndpoints = StsRegionalEndpointsValue.Regional, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Regional, // 0:00:30 ConnectTimeout = TimeSpan.FromMilliseconds(30000L), // 0:00:30 TlsNegotiationTimeout = TimeSpan.FromMilliseconds(30000L), TimeToFirstByteTimeout = null, HttpRequestTimeout = null }; /// <summary> /// <p>The AUTO mode is an experimental mode that builds on the standard mode. The SDK will attempt to discover the execution environment to determine the appropriate settings automatically.</p><p>Note that the auto detection is heuristics-based and does not guarantee 100% accuracy. STANDARD mode will be used if the execution environment cannot be determined. The auto detection might query <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">EC2 Instance Metadata service</a>, which might introduce latency. Therefore we recommend choosing an explicit defaults_mode instead if startup latency is critical to your application</p> /// </summary> public static IDefaultConfiguration Auto {get;} = new DefaultConfiguration { Name = DefaultConfigurationMode.Auto, RetryMode = RequestRetryMode.Standard, StsRegionalEndpoints = StsRegionalEndpointsValue.Regional, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Regional, // 0:00:01.1 ConnectTimeout = TimeSpan.FromMilliseconds(1100L), // 0:00:01.1 TlsNegotiationTimeout = TimeSpan.FromMilliseconds(1100L), TimeToFirstByteTimeout = null, HttpRequestTimeout = null }; /// <summary> /// <p>The LEGACY mode provides default settings that vary per SDK and were used prior to establishment of defaults_mode</p> /// </summary> public static IDefaultConfiguration Legacy {get;} = new DefaultConfiguration { Name = DefaultConfigurationMode.Legacy, RetryMode = RequestRetryMode.Legacy, StsRegionalEndpoints = StsRegionalEndpointsValue.Legacy, S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Legacy, ConnectTimeout = null, TlsNegotiationTimeout = null, TimeToFirstByteTimeout = null, HttpRequestTimeout = null }; } }
51.952055
676
0.673434
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/MarketplaceCatalog/Generated/AmazonMarketplaceCatalogDefaultConfiguration.cs
7,585
C#
namespace BuilderScenario { [TagAlias("debugLog")] public class LogMessageJob : IBuildJob { public string Message { get; set; } public void Run(IBuildLogger logger) { logger.Log(Message); } } }
20.153846
44
0.553435
[ "MIT" ]
CTAPbIuKODEP/BuilderScenario
src/Jobs/LogMessageJob.cs
262
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 // 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 // 이러한 특성 값을 변경하세요. [assembly: AssemblyTitle("Interface_practice")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Interface_practice")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("e7bf8c6e-df40-4249-9d3c-42e8d5d959f7")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 // 기본값으로 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.810811
56
0.702627
[ "MIT" ]
leeseojune53/BOJ
Cs_learn/Interface_practice/Properties/AssemblyInfo.cs
1,499
C#
using Contact.Entity.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace contact.Business.Abstract { public interface IContactService { string AddContactMessage(MessageModel messageModel); } }
19.933333
60
0.769231
[ "Apache-2.0" ]
burakhalefoglu/ASP.NET-5.0.OcelotGatewayExamplewithSimpleMicroservices
Services/Contact.Service/contact.Business/Abstract/IContactService.cs
301
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Encryption { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos; using Newtonsoft.Json.Linq; internal sealed class EncryptionContainer : Container { private readonly Container container; private readonly AsyncCache<string, EncryptionSettings> encryptionSettingsByContainerName; /// <summary> /// Initializes a new instance of the <see cref="EncryptionContainer"/> class. /// All the operations / requests for exercising client-side encryption functionality need to be made using this EncryptionContainer instance. /// </summary> /// <param name="container">Regular cosmos container.</param> /// <param name="encryptionCosmosClient"> Cosmos Client configured with Encryption.</param> public EncryptionContainer( Container container, EncryptionCosmosClient encryptionCosmosClient) { this.container = container ?? throw new ArgumentNullException(nameof(container)); this.EncryptionCosmosClient = encryptionCosmosClient ?? throw new ArgumentNullException(nameof(container)); this.ResponseFactory = this.Database.Client.ResponseFactory; this.CosmosSerializer = this.Database.Client.ClientOptions.Serializer; this.encryptionSettingsByContainerName = new AsyncCache<string, EncryptionSettings>(); } public CosmosSerializer CosmosSerializer { get; } public CosmosResponseFactory ResponseFactory { get; } public EncryptionCosmosClient EncryptionCosmosClient { get; } public override string Id => this.container.Id; public override Conflicts Conflicts => this.container.Conflicts; public override Scripts.Scripts Scripts => this.container.Scripts; public override Database Database => this.container.Database; public override async Task<ItemResponse<T>> CreateItemAsync<T>( T item, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (partitionKey == null) { throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}."); } ResponseMessage responseMessage; using (Stream itemStream = this.CosmosSerializer.ToStream<T>(item)) { responseMessage = await this.CreateItemHelperAsync( itemStream, partitionKey.Value, requestOptions, cancellationToken); } return this.ResponseFactory.CreateItemResponse<T>(responseMessage); } public override async Task<ResponseMessage> CreateItemStreamAsync( Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (streamPayload == null) { throw new ArgumentNullException(nameof(streamPayload)); } return await this.CreateItemHelperAsync( streamPayload, partitionKey, requestOptions, cancellationToken); } public override Task<ItemResponse<T>> DeleteItemAsync<T>( string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.DeleteItemAsync<T>( id, partitionKey, requestOptions, cancellationToken); } public override Task<ResponseMessage> DeleteItemStreamAsync( string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.DeleteItemStreamAsync( id, partitionKey, requestOptions, cancellationToken); } public override async Task<ItemResponse<T>> ReadItemAsync<T>( string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { ResponseMessage responseMessage = await this.ReadItemHelperAsync( id, partitionKey, requestOptions, cancellationToken); return this.ResponseFactory.CreateItemResponse<T>(responseMessage); } public override async Task<ResponseMessage> ReadItemStreamAsync( string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return await this.ReadItemHelperAsync( id, partitionKey, requestOptions, cancellationToken); } public override async Task<ItemResponse<T>> ReplaceItemAsync<T>( T item, string id, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (item == null) { throw new ArgumentNullException(nameof(item)); } if (partitionKey == null) { throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}."); } ResponseMessage responseMessage; using (Stream itemStream = this.CosmosSerializer.ToStream<T>(item)) { responseMessage = await this.ReplaceItemHelperAsync( itemStream, id, partitionKey.Value, requestOptions, cancellationToken); } return this.ResponseFactory.CreateItemResponse<T>(responseMessage); } public override async Task<ResponseMessage> ReplaceItemStreamAsync( Stream streamPayload, string id, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (streamPayload == null) { throw new ArgumentNullException(nameof(streamPayload)); } return await this.ReplaceItemHelperAsync( streamPayload, id, partitionKey, requestOptions, cancellationToken); } public override async Task<ItemResponse<T>> UpsertItemAsync<T>( T item, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (partitionKey == null) { throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}."); } ResponseMessage responseMessage; using (Stream itemStream = this.CosmosSerializer.ToStream<T>(item)) { responseMessage = await this.UpsertItemHelperAsync( itemStream, partitionKey.Value, requestOptions, cancellationToken); } return this.ResponseFactory.CreateItemResponse<T>(responseMessage); } public override async Task<ResponseMessage> UpsertItemStreamAsync( Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (streamPayload == null) { throw new ArgumentNullException(nameof(streamPayload)); } return await this.UpsertItemHelperAsync( streamPayload, partitionKey, requestOptions, cancellationToken); } public override TransactionalBatch CreateTransactionalBatch( PartitionKey partitionKey) { return new EncryptionTransactionalBatch( this.container.CreateTransactionalBatch(partitionKey), this, this.CosmosSerializer); } public override Task<ContainerResponse> DeleteContainerAsync( ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.DeleteContainerAsync( requestOptions, cancellationToken); } public override Task<ResponseMessage> DeleteContainerStreamAsync( ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.DeleteContainerStreamAsync( requestOptions, cancellationToken); } public override ChangeFeedProcessorBuilder GetChangeFeedEstimatorBuilder( string processorName, ChangesEstimationHandler estimationDelegate, TimeSpan? estimationPeriod = null) { return this.container.GetChangeFeedEstimatorBuilder( processorName, estimationDelegate, estimationPeriod); } public override IOrderedQueryable<T> GetItemLinqQueryable<T>( bool allowSynchronousQueryExecution = false, string continuationToken = null, QueryRequestOptions requestOptions = null, CosmosLinqSerializerOptions linqSerializerOptions = null) { return this.container.GetItemLinqQueryable<T>( allowSynchronousQueryExecution, continuationToken, requestOptions, linqSerializerOptions); } public override FeedIterator<T> GetItemQueryIterator<T>( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new EncryptionFeedIterator<T>( (EncryptionFeedIterator)this.GetItemQueryStreamIterator( queryDefinition, continuationToken, requestOptions), this.ResponseFactory); } public override FeedIterator<T> GetItemQueryIterator<T>( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new EncryptionFeedIterator<T>( (EncryptionFeedIterator)this.GetItemQueryStreamIterator( queryText, continuationToken, requestOptions), this.ResponseFactory); } public override Task<ContainerResponse> ReadContainerAsync( ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.ReadContainerAsync( requestOptions, cancellationToken); } public override Task<ResponseMessage> ReadContainerStreamAsync( ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.ReadContainerStreamAsync( requestOptions, cancellationToken); } public override Task<int?> ReadThroughputAsync( CancellationToken cancellationToken = default) { return this.container.ReadThroughputAsync(cancellationToken); } public override Task<ThroughputResponse> ReadThroughputAsync( RequestOptions requestOptions, CancellationToken cancellationToken = default) { return this.container.ReadThroughputAsync( requestOptions, cancellationToken); } public override Task<ContainerResponse> ReplaceContainerAsync( ContainerProperties containerProperties, ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.ReplaceContainerAsync( containerProperties, requestOptions, cancellationToken); } public override Task<ResponseMessage> ReplaceContainerStreamAsync( ContainerProperties containerProperties, ContainerRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.ReplaceContainerStreamAsync( containerProperties, requestOptions, cancellationToken); } public override Task<ThroughputResponse> ReplaceThroughputAsync( int throughput, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.ReplaceThroughputAsync( throughput, requestOptions, cancellationToken); } public override FeedIterator GetItemQueryStreamIterator( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { QueryRequestOptions clonedRequestOptions = requestOptions != null ? (QueryRequestOptions)requestOptions.ShallowCopy() : new QueryRequestOptions(); return new EncryptionFeedIterator( this.container.GetItemQueryStreamIterator( queryDefinition, continuationToken, clonedRequestOptions), this, clonedRequestOptions); } public override FeedIterator GetItemQueryStreamIterator( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { QueryRequestOptions clonedRequestOptions = requestOptions != null ? (QueryRequestOptions)requestOptions.ShallowCopy() : new QueryRequestOptions(); return new EncryptionFeedIterator( this.container.GetItemQueryStreamIterator( queryText, continuationToken, clonedRequestOptions), this, clonedRequestOptions); } public override Task<ThroughputResponse> ReplaceThroughputAsync( ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.container.ReplaceThroughputAsync( throughputProperties, requestOptions, cancellationToken); } public override Task<IReadOnlyList<FeedRange>> GetFeedRangesAsync( CancellationToken cancellationToken = default) { return this.container.GetFeedRangesAsync(cancellationToken); } public override Task<IEnumerable<string>> GetPartitionKeyRangesAsync( FeedRange feedRange, CancellationToken cancellationToken = default) { return this.container.GetPartitionKeyRangesAsync(feedRange, cancellationToken); } public override FeedIterator GetItemQueryStreamIterator( FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken, QueryRequestOptions requestOptions = null) { QueryRequestOptions clonedRequestOptions = requestOptions != null ? (QueryRequestOptions)requestOptions.ShallowCopy() : new QueryRequestOptions(); return new EncryptionFeedIterator( this.container.GetItemQueryStreamIterator( feedRange, queryDefinition, continuationToken, clonedRequestOptions), this, clonedRequestOptions); } public override FeedIterator<T> GetItemQueryIterator<T>( FeedRange feedRange, QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new EncryptionFeedIterator<T>( (EncryptionFeedIterator)this.GetItemQueryStreamIterator( feedRange, queryDefinition, continuationToken, requestOptions), this.ResponseFactory); } public override ChangeFeedEstimator GetChangeFeedEstimator( string processorName, Container leaseContainer) { return this.container.GetChangeFeedEstimator(processorName, leaseContainer); } public override FeedIterator GetChangeFeedStreamIterator( ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions = null) { ChangeFeedRequestOptions clonedchangeFeedRequestOptions = changeFeedRequestOptions != null ? (ChangeFeedRequestOptions)changeFeedRequestOptions.ShallowCopy() : new ChangeFeedRequestOptions(); return new EncryptionFeedIterator( this.container.GetChangeFeedStreamIterator( changeFeedStartFrom, changeFeedMode, clonedchangeFeedRequestOptions), this, clonedchangeFeedRequestOptions); } public override FeedIterator<T> GetChangeFeedIterator<T>( ChangeFeedStartFrom changeFeedStartFrom, ChangeFeedMode changeFeedMode, ChangeFeedRequestOptions changeFeedRequestOptions = null) { return new EncryptionFeedIterator<T>( (EncryptionFeedIterator)this.GetChangeFeedStreamIterator( changeFeedStartFrom, changeFeedMode, changeFeedRequestOptions), this.ResponseFactory); } public async override Task<ItemResponse<T>> PatchItemAsync<T>( string id, PartitionKey partitionKey, IReadOnlyList<PatchOperation> patchOperations, PatchItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { ResponseMessage responseMessage = await this.PatchItemStreamAsync( id, partitionKey, patchOperations, requestOptions, cancellationToken); return this.ResponseFactory.CreateItemResponse<T>(responseMessage); } public async override Task<ResponseMessage> PatchItemStreamAsync( string id, PartitionKey partitionKey, IReadOnlyList<PatchOperation> patchOperations, PatchItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException(nameof(id)); } if (partitionKey == null) { throw new ArgumentNullException(nameof(partitionKey)); } if (patchOperations == null || !patchOperations.Any()) { throw new ArgumentNullException(nameof(patchOperations)); } ResponseMessage responseMessage = await this.PatchItemHelperAsync( id, partitionKey, patchOperations, requestOptions, cancellationToken); return responseMessage; } public override ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder<T>( string processorName, ChangesHandler<T> onChangesDelegate) { return this.container.GetChangeFeedProcessorBuilder( processorName, async ( IReadOnlyCollection<JObject> documents, CancellationToken cancellationToken) => { List<T> decryptedItems = await this.DecryptChangeFeedDocumentsAsync<T>( documents, cancellationToken); // Call the original passed in delegate await onChangesDelegate(decryptedItems, cancellationToken); }); } public override ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder<T>( string processorName, ChangeFeedHandler<T> onChangesDelegate) { return this.container.GetChangeFeedProcessorBuilder( processorName, async ( ChangeFeedProcessorContext context, IReadOnlyCollection<JObject> documents, CancellationToken cancellationToken) => { List<T> decryptedItems = await this.DecryptChangeFeedDocumentsAsync<T>( documents, cancellationToken); // Call the original passed in delegate await onChangesDelegate(context, decryptedItems, cancellationToken); }); } public override ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint<T>( string processorName, ChangeFeedHandlerWithManualCheckpoint<T> onChangesDelegate) { return this.container.GetChangeFeedProcessorBuilderWithManualCheckpoint( processorName, async ( ChangeFeedProcessorContext context, IReadOnlyCollection<JObject> documents, Func<Task> tryCheckpointAsync, CancellationToken cancellationToken) => { List<T> decryptedItems = await this.DecryptChangeFeedDocumentsAsync<T>( documents, cancellationToken); // Call the original passed in delegate await onChangesDelegate(context, decryptedItems, tryCheckpointAsync, cancellationToken); }); } public override ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilder( string processorName, ChangeFeedStreamHandler onChangesDelegate) { return this.container.GetChangeFeedProcessorBuilder( processorName, async ( ChangeFeedProcessorContext context, Stream changes, CancellationToken cancellationToken) => { EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); Stream decryptedChanges = await EncryptionProcessor.DeserializeAndDecryptResponseAsync( changes, encryptionSettings, operationDiagnostics: null, cancellationToken); // Call the original passed in delegate await onChangesDelegate(context, decryptedChanges, cancellationToken); }); } public override ChangeFeedProcessorBuilder GetChangeFeedProcessorBuilderWithManualCheckpoint( string processorName, ChangeFeedStreamHandlerWithManualCheckpoint onChangesDelegate) { return this.container.GetChangeFeedProcessorBuilderWithManualCheckpoint( processorName, async ( ChangeFeedProcessorContext context, Stream changes, Func<Task> tryCheckpointAsync, CancellationToken cancellationToken) => { EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); Stream decryptedChanges = await EncryptionProcessor.DeserializeAndDecryptResponseAsync( changes, encryptionSettings, operationDiagnostics: null, cancellationToken); // Call the original passed in delegate await onChangesDelegate(context, decryptedChanges, tryCheckpointAsync, cancellationToken); }); } public override Task<ResponseMessage> ReadManyItemsStreamAsync( IReadOnlyList<(string id, PartitionKey partitionKey)> items, ReadManyRequestOptions readManyRequestOptions = null, CancellationToken cancellationToken = default) { return this.ReadManyItemsHelperAsync( items, readManyRequestOptions, cancellationToken); } public override async Task<FeedResponse<T>> ReadManyItemsAsync<T>( IReadOnlyList<(string id, PartitionKey partitionKey)> items, ReadManyRequestOptions readManyRequestOptions = null, CancellationToken cancellationToken = default) { ResponseMessage responseMessage = await this.ReadManyItemsHelperAsync( items, readManyRequestOptions, cancellationToken); return this.ResponseFactory.CreateItemFeedResponse<T>(responseMessage); } public async Task<EncryptionSettings> GetOrUpdateEncryptionSettingsFromCacheAsync( EncryptionSettings obsoleteEncryptionSettings, CancellationToken cancellationToken) { return await this.encryptionSettingsByContainerName.GetAsync( this.Id, obsoleteValue: obsoleteEncryptionSettings, singleValueInitFunc: () => EncryptionSettings.CreateAsync(this, cancellationToken), cancellationToken: cancellationToken); } internal async Task<List<PatchOperation>> EncryptPatchOperationsAsync( IReadOnlyList<PatchOperation> patchOperations, EncryptionSettings encryptionSettings, EncryptionDiagnosticsContext operationDiagnostics, CancellationToken cancellationToken = default) { List<PatchOperation> encryptedPatchOperations = new List<PatchOperation>(patchOperations.Count); operationDiagnostics.Begin(Constants.DiagnosticsEncryptOperation); int propertiesEncryptedCount = 0; foreach (PatchOperation patchOperation in patchOperations) { if (patchOperation.OperationType == PatchOperationType.Remove) { encryptedPatchOperations.Add(patchOperation); continue; } if (string.IsNullOrWhiteSpace(patchOperation.Path) || patchOperation.Path[0] != '/') { throw new ArgumentException($"Invalid path '{patchOperation.Path}'."); } // get the top level path's encryption setting. EncryptionSettingForProperty settingforProperty = encryptionSettings.GetEncryptionSettingForProperty( patchOperation.Path.Split('/')[1]); // non-encrypted path if (settingforProperty == null) { encryptedPatchOperations.Add(patchOperation); continue; } else if (patchOperation.OperationType == PatchOperationType.Increment) { throw new InvalidOperationException($"Increment patch operation is not allowed for encrypted path '{patchOperation.Path}'."); } if (!patchOperation.TrySerializeValueParameter(this.CosmosSerializer, out Stream valueParam)) { throw new ArgumentException($"Cannot serialize value parameter for operation: {patchOperation.OperationType}, path: {patchOperation.Path}."); } Stream encryptedPropertyValue = await EncryptionProcessor.EncryptValueStreamAsync( valueParam, settingforProperty, cancellationToken); propertiesEncryptedCount++; switch (patchOperation.OperationType) { case PatchOperationType.Add: encryptedPatchOperations.Add(PatchOperation.Add(patchOperation.Path, encryptedPropertyValue)); break; case PatchOperationType.Replace: encryptedPatchOperations.Add(PatchOperation.Replace(patchOperation.Path, encryptedPropertyValue)); break; case PatchOperationType.Set: encryptedPatchOperations.Add(PatchOperation.Set(patchOperation.Path, encryptedPropertyValue)); break; default: throw new NotSupportedException(nameof(patchOperation.OperationType)); } } operationDiagnostics?.End(propertiesEncryptedCount); return encryptedPatchOperations; } /// <summary> /// Returns a cloned copy of the passed RequestOptions if passed else creates a new ItemRequestOptions. /// </summary> /// <param name="itemRequestOptions"> Original ItemRequestOptions.</param> /// <returns> ItemRequestOptions.</returns> private static ItemRequestOptions GetClonedItemRequestOptions(ItemRequestOptions itemRequestOptions) { ItemRequestOptions clonedRequestOptions = itemRequestOptions != null ? (ItemRequestOptions)itemRequestOptions.ShallowCopy() : new ItemRequestOptions(); return clonedRequestOptions; } private async Task<ResponseMessage> CreateItemHelperAsync( Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions, CancellationToken cancellationToken, bool isRetry = false) { EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync(obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); if (!encryptionSettings.PropertiesToEncrypt.Any()) { return await this.container.CreateItemStreamAsync( streamPayload, partitionKey, requestOptions, cancellationToken); } EncryptionDiagnosticsContext encryptionDiagnosticsContext = new EncryptionDiagnosticsContext(); streamPayload = await EncryptionProcessor.EncryptAsync( streamPayload, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); ItemRequestOptions clonedRequestOptions = requestOptions; // Clone(once) the request options since we modify it to set AddRequestHeaders to add additional headers. if (!isRetry) { clonedRequestOptions = GetClonedItemRequestOptions(requestOptions); } encryptionSettings.SetRequestHeaders(clonedRequestOptions); ResponseMessage responseMessage = await this.container.CreateItemStreamAsync( streamPayload, partitionKey, clonedRequestOptions, cancellationToken); // This handles the scenario where a container is deleted(say from different Client) and recreated with same Id but with different client encryption policy. // The idea is to have the container Rid cached and sent out as part of RequestOptions with Container Rid set in "x-ms-cosmos-intended-collection-rid" header. // So when the container being referenced here gets recreated we would end up with a stale encryption settings and container Rid and this would result in BadRequest( and a substatus 1024). // This would allow us to refresh the encryption settings and Container Rid, on the premise that the container recreated could possibly be configured with a new encryption policy. if (!isRetry && responseMessage.StatusCode == HttpStatusCode.BadRequest && string.Equals(responseMessage.Headers.Get(Constants.SubStatusHeader), Constants.IncorrectContainerRidSubStatus)) { // Even though the streamPayload position is expected to be 0, // because for MemoryStream we just use the underlying buffer to send over the wire rather than using the Stream APIs // resetting it 0 to be on a safer side. streamPayload.Position = 0; // Now the streamPayload itself is not disposed off(and hence safe to use it in the below call) since the stream that is passed to CreateItemStreamAsync is a MemoryStream and not the original Stream // that the user has passed. The call to EncryptAsync reads out the stream(and processes it) and returns a MemoryStream which is eventually cloned in the // Cosmos SDK and then used. This stream however is to be disposed off as part of ResponseMessage when this gets returned. streamPayload = await this.DecryptStreamPayloadAndUpdateEncryptionSettingsAsync( streamPayload, encryptionSettings, cancellationToken); // we try to recreate the item with the StreamPayload(to be encrypted) now that the encryptionSettings would have been updated with latest values if any. return await this.CreateItemHelperAsync( streamPayload, partitionKey, clonedRequestOptions, cancellationToken, isRetry: true); } responseMessage.Content = await EncryptionProcessor.DecryptAsync( responseMessage.Content, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); encryptionDiagnosticsContext.AddEncryptionDiagnosticsToResponseMessage(responseMessage); return responseMessage; } private async Task<ResponseMessage> ReadItemHelperAsync( string id, PartitionKey partitionKey, ItemRequestOptions requestOptions, CancellationToken cancellationToken, bool isRetry = false) { EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync(obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); if (!encryptionSettings.PropertiesToEncrypt.Any()) { return await this.container.ReadItemStreamAsync( id, partitionKey, requestOptions, cancellationToken); } ItemRequestOptions clonedRequestOptions = requestOptions; // Clone(once) the request options since we modify it to set AddRequestHeaders to add additional headers. if (!isRetry) { clonedRequestOptions = GetClonedItemRequestOptions(requestOptions); } encryptionSettings.SetRequestHeaders(clonedRequestOptions); ResponseMessage responseMessage = await this.container.ReadItemStreamAsync( id, partitionKey, clonedRequestOptions, cancellationToken); if (!isRetry && responseMessage.StatusCode == HttpStatusCode.BadRequest && string.Equals(responseMessage.Headers.Get(Constants.SubStatusHeader), Constants.IncorrectContainerRidSubStatus)) { // get the latest encryption settings. await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: encryptionSettings, cancellationToken: cancellationToken); return await this.ReadItemHelperAsync( id, partitionKey, clonedRequestOptions, cancellationToken, isRetry: true); } EncryptionDiagnosticsContext encryptionDiagnosticsContext = new EncryptionDiagnosticsContext(); responseMessage.Content = await EncryptionProcessor.DecryptAsync( responseMessage.Content, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); encryptionDiagnosticsContext.AddEncryptionDiagnosticsToResponseMessage(responseMessage); return responseMessage; } private async Task<ResponseMessage> ReplaceItemHelperAsync( Stream streamPayload, string id, PartitionKey partitionKey, ItemRequestOptions requestOptions, CancellationToken cancellationToken, bool isRetry = false) { if (partitionKey == null) { throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}."); } EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync(obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); if (!encryptionSettings.PropertiesToEncrypt.Any()) { return await this.container.ReplaceItemStreamAsync( streamPayload, id, partitionKey, requestOptions, cancellationToken); } EncryptionDiagnosticsContext encryptionDiagnosticsContext = new EncryptionDiagnosticsContext(); streamPayload = await EncryptionProcessor.EncryptAsync( streamPayload, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); ItemRequestOptions clonedRequestOptions = requestOptions; // Clone(once) the request options since we modify it to set AddRequestHeaders to add additional headers. if (!isRetry) { clonedRequestOptions = GetClonedItemRequestOptions(requestOptions); } encryptionSettings.SetRequestHeaders(clonedRequestOptions); ResponseMessage responseMessage = await this.container.ReplaceItemStreamAsync( streamPayload, id, partitionKey, clonedRequestOptions, cancellationToken); if (!isRetry && responseMessage.StatusCode == HttpStatusCode.BadRequest && string.Equals(responseMessage.Headers.Get(Constants.SubStatusHeader), Constants.IncorrectContainerRidSubStatus)) { streamPayload.Position = 0; streamPayload = await this.DecryptStreamPayloadAndUpdateEncryptionSettingsAsync( streamPayload, encryptionSettings, cancellationToken); return await this.ReplaceItemHelperAsync( streamPayload, id, partitionKey, clonedRequestOptions, cancellationToken, isRetry: true); } responseMessage.Content = await EncryptionProcessor.DecryptAsync( responseMessage.Content, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); encryptionDiagnosticsContext.AddEncryptionDiagnosticsToResponseMessage(responseMessage); return responseMessage; } private async Task<ResponseMessage> UpsertItemHelperAsync( Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions, CancellationToken cancellationToken, bool isRetry = false) { if (partitionKey == null) { throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}."); } EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync(obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); if (!encryptionSettings.PropertiesToEncrypt.Any()) { return await this.container.UpsertItemStreamAsync( streamPayload, partitionKey, requestOptions, cancellationToken); } EncryptionDiagnosticsContext encryptionDiagnosticsContext = new EncryptionDiagnosticsContext(); streamPayload = await EncryptionProcessor.EncryptAsync( streamPayload, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); ItemRequestOptions clonedRequestOptions = requestOptions; // Clone(once) the request options since we modify it to set AddRequestHeaders to add additional headers. if (!isRetry) { clonedRequestOptions = GetClonedItemRequestOptions(requestOptions); } encryptionSettings.SetRequestHeaders(clonedRequestOptions); ResponseMessage responseMessage = await this.container.UpsertItemStreamAsync( streamPayload, partitionKey, clonedRequestOptions, cancellationToken); if (!isRetry && responseMessage.StatusCode == HttpStatusCode.BadRequest && string.Equals(responseMessage.Headers.Get(Constants.SubStatusHeader), Constants.IncorrectContainerRidSubStatus)) { streamPayload.Position = 0; streamPayload = await this.DecryptStreamPayloadAndUpdateEncryptionSettingsAsync( streamPayload, encryptionSettings, cancellationToken); return await this.UpsertItemHelperAsync( streamPayload, partitionKey, clonedRequestOptions, cancellationToken, isRetry: true); } responseMessage.Content = await EncryptionProcessor.DecryptAsync( responseMessage.Content, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); encryptionDiagnosticsContext.AddEncryptionDiagnosticsToResponseMessage(responseMessage); return responseMessage; } private async Task<ResponseMessage> PatchItemHelperAsync( string id, PartitionKey partitionKey, IReadOnlyList<PatchOperation> patchOperations, PatchItemRequestOptions requestOptions, CancellationToken cancellationToken) { EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); PatchItemRequestOptions clonedRequestOptions; if (requestOptions != null) { clonedRequestOptions = (PatchItemRequestOptions)requestOptions.ShallowCopy(); } else { clonedRequestOptions = new PatchItemRequestOptions(); } encryptionSettings.SetRequestHeaders(clonedRequestOptions); EncryptionDiagnosticsContext encryptionDiagnosticsContext = new EncryptionDiagnosticsContext(); List<PatchOperation> encryptedPatchOperations = await this.EncryptPatchOperationsAsync( patchOperations, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); ResponseMessage responseMessage = await this.container.PatchItemStreamAsync( id, partitionKey, encryptedPatchOperations, clonedRequestOptions, cancellationToken); responseMessage.Content = await EncryptionProcessor.DecryptAsync( responseMessage.Content, encryptionSettings, encryptionDiagnosticsContext, cancellationToken); encryptionDiagnosticsContext.AddEncryptionDiagnosticsToResponseMessage(responseMessage); return responseMessage; } /// <summary> /// This method takes in an encrypted stream payload. /// The streamPayload is decrypted with the same policy which was used to encrypt and then the original plain stream payload is /// returned which can be used to re-encrypt after the latest encryption settings is retrieved. /// The method also updates the cached Encryption Settings with the latest value if any. /// </summary> /// <param name="streamPayload"> Data encrypted with wrong encryption policy. </param> /// <param name="encryptionSettings"> EncryptionSettings which was used to encrypt the payload. </param> /// <param name="cancellationToken"> Cancellation token. </param> /// <returns> Returns the decrypted stream payload and diagnostics content. </returns> private async Task<Stream> DecryptStreamPayloadAndUpdateEncryptionSettingsAsync( Stream streamPayload, EncryptionSettings encryptionSettings, CancellationToken cancellationToken) { streamPayload = await EncryptionProcessor.DecryptAsync( streamPayload, encryptionSettings, operationDiagnostics: null, cancellationToken); // get the latest encryption settings. await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: encryptionSettings, cancellationToken: cancellationToken); return streamPayload; } private async Task<List<T>> DecryptChangeFeedDocumentsAsync<T>( IReadOnlyCollection<JObject> documents, CancellationToken cancellationToken) { List<T> decryptedItems = new List<T>(documents.Count); EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); foreach (JObject document in documents) { (JObject decryptedDocument, _) = await EncryptionProcessor.DecryptAsync( document, encryptionSettings, cancellationToken); decryptedItems.Add(decryptedDocument.ToObject<T>()); } return decryptedItems; } private async Task<ResponseMessage> ReadManyItemsHelperAsync( IReadOnlyList<(string id, PartitionKey partitionKey)> items, ReadManyRequestOptions readManyRequestOptions = null, CancellationToken cancellationToken = default, bool isRetry = false) { EncryptionSettings encryptionSettings = await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: null, cancellationToken: cancellationToken); if (!encryptionSettings.PropertiesToEncrypt.Any()) { return await this.container.ReadManyItemsStreamAsync( items, readManyRequestOptions, cancellationToken); } ReadManyRequestOptions clonedRequestOptions = readManyRequestOptions; // Clone(once) the request options since we modify it to set AddRequestHeaders to add additional headers. if (!isRetry) { clonedRequestOptions = readManyRequestOptions != null ? (ReadManyRequestOptions)readManyRequestOptions.ShallowCopy() : new ReadManyRequestOptions(); } encryptionSettings.SetRequestHeaders(clonedRequestOptions); ResponseMessage responseMessage = await this.container.ReadManyItemsStreamAsync( items, clonedRequestOptions, cancellationToken); if (!isRetry && responseMessage.StatusCode == HttpStatusCode.BadRequest && string.Equals(responseMessage.Headers.Get(Constants.SubStatusHeader), Constants.IncorrectContainerRidSubStatus)) { // get the latest encryption settings. await this.GetOrUpdateEncryptionSettingsFromCacheAsync( obsoleteEncryptionSettings: encryptionSettings, cancellationToken: cancellationToken); return await this.ReadManyItemsHelperAsync( items, clonedRequestOptions, cancellationToken, isRetry: true); } if (responseMessage.IsSuccessStatusCode && responseMessage.Content != null) { EncryptionDiagnosticsContext decryptDiagnostics = new EncryptionDiagnosticsContext(); Stream decryptedContent = await EncryptionProcessor.DeserializeAndDecryptResponseAsync( responseMessage.Content, encryptionSettings, decryptDiagnostics, cancellationToken); decryptDiagnostics.AddEncryptionDiagnosticsToResponseMessage(responseMessage); return new DecryptedResponseMessage(responseMessage, decryptedContent); } return responseMessage; } } }
41.530612
214
0.603686
[ "MIT" ]
Arithmomaniac/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos.Encryption/src/EncryptionContainer.cs
52,912
C#
// The MIT License (MIT) // Copyright 2015 Siney/Pangweiwei siney@yeah.net // // 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. namespace SLua { using System; using System.Collections.Generic; using System.Collections; using System.Text; #if !SLUA_STANDALONE using UnityEngine; #else using System.IO; #endif abstract public class LuaVar : IDisposable { protected LuaState state = null; protected int valueref = 0; public IntPtr L { get { return state.L; } } public int Ref { get { return valueref; } } public LuaVar() { state = null; } public LuaVar(LuaState l, int r) { state = l; valueref = r; } public LuaVar(IntPtr l, int r) { state = LuaState.get(l); valueref = r; } ~LuaVar() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public virtual void Dispose(bool disposeManagedResources) { if (valueref != 0) { LuaState.UnRefAction act = (IntPtr l, int r) => { LuaDLL.lua_unref(l, r); }; state.gcRef(act, valueref); valueref = 0; } } public void push(IntPtr l) { LuaDLL.lua_getref(l, valueref); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { if (obj is LuaVar) { return this == (LuaVar)obj; } return false; } public static bool operator ==(LuaVar x, LuaVar y) { if ((object)x == null || (object)y == null) return (object)x == (object)y; return Equals(x, y) == 1; } public static bool operator !=(LuaVar x, LuaVar y) { if ((object)x == null || (object)y == null) return (object)x != (object)y; return Equals(x, y) != 1; } static int Equals(LuaVar x, LuaVar y) { x.push(x.L); y.push(x.L); int ok = LuaDLL.lua_equal(x.L, -1, -2); LuaDLL.lua_pop(x.L, 2); return ok; } } public class LuaThread : LuaVar { public LuaThread(IntPtr l, int r) : base(l, r) { } } public class LuaDelegate : LuaFunction { public object d; public LuaDelegate(IntPtr l, int r) : base(l, r) { } public override void Dispose(bool disposeManagedResources) { if (valueref != 0) { LuaState.UnRefAction act = (IntPtr l, int r) => { LuaObject.removeDelgate(l, r); LuaDLL.lua_unref(l, r); }; state.gcRef(act, valueref); valueref = 0; } } } public class LuaFunction : LuaVar { public LuaFunction(LuaState l, int r) : base(l, r) { } public LuaFunction(IntPtr l, int r) : base(l, r) { } public bool pcall(int nArgs, int errfunc) { if (!state.isMainThread()) { Logger.LogError("Can't call lua function in bg thread"); return false; } LuaDLL.lua_getref(L, valueref); if (!LuaDLL.lua_isfunction(L, -1)) { LuaDLL.lua_pop(L, 1); throw new Exception("Call invalid function."); } LuaDLL.lua_insert(L, -nArgs - 1); if (LuaDLL.lua_pcall(L, nArgs, -1, errfunc) != 0) { LuaDLL.lua_pop(L, 1); return false; } return true; } bool innerCall(int nArgs, int errfunc) { bool ret = pcall(nArgs, errfunc); LuaDLL.lua_remove(L, errfunc); return ret; } public object call() { int error = LuaObject.pushTry(state.L); if (innerCall(0, error)) { return state.topObjects(error - 1); } return null; } public object call(params object[] args) { int error = LuaObject.pushTry(state.L); for (int n = 0; args != null && n < args.Length; n++) { LuaObject.pushVar(L, args[n]); } if (innerCall(args != null ? args.Length : 0, error)) { return state.topObjects(error - 1); } return null; } public object call(LuaTable self, params object[] args) { int error = LuaObject.pushTry(state.L); LuaObject.pushVar(L, self); for (int n = 0; args != null && n < args.Length; n++) { LuaObject.pushVar(L, args[n]); } if (innerCall((args != null ? args.Length : 0) + 1, error)) { return state.topObjects(error - 1); } return null; } public T cast<T>() where T:class { return LuaObject.delegateCast(this, typeof(T)) as T; } } public class LuaTable : LuaVar, IEnumerable<LuaTable.TablePair> { public struct TablePair { public object key; public object value; } public LuaTable(IntPtr l, int r) : base(l, r) { } public LuaTable(LuaState l, int r) : base(l, r) { } public LuaTable(LuaState state) : base(state, 0) { LuaDLL.lua_newtable(L); valueref = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } public object this[string key] { get { return state.getObject(valueref, key); } set { state.setObject(valueref, key, value); } } public object this[int index] { get { return state.getObject(valueref, index); } set { state.setObject(valueref, index, value); } } public object invoke(string func, params object[] args) { using (LuaFunction f = (LuaFunction)this[func]) { if (f != null) { return f.call(args); } } throw new Exception(string.Format("Can't find {0} function", func)); } public int length() { int n = LuaDLL.lua_gettop(L); push(L); int l = LuaDLL.lua_rawlen(L, -1); LuaDLL.lua_settop(L, n); return l; } public bool IsEmpty { get { int top = LuaDLL.lua_gettop(L); LuaDLL.lua_getref(L, this.Ref); LuaDLL.lua_pushnil(L); bool ret = LuaDLL.lua_next(L, -2) > 0; LuaDLL.lua_settop(L, top); return !ret; } } public class Enumerator : IEnumerator<TablePair>, IDisposable { LuaTable t; int indext = -1; TablePair current = new TablePair(); int iterPhase = 0; public Enumerator(LuaTable table) { t = table; Reset(); } public bool MoveNext() { if (indext < 0) return false; if (iterPhase == 0) { LuaDLL.lua_pushnil(t.L); iterPhase = 1; } else LuaDLL.lua_pop(t.L, 1); //var ty = LuaDLL.lua_type(t.L, -1); bool ret = LuaDLL.lua_next(t.L, indext) > 0; if (!ret) iterPhase = 2; return ret; } public void Reset() { LuaDLL.lua_getref(t.L, t.Ref); indext = LuaDLL.lua_gettop(t.L); } public void Dispose() { if (iterPhase == 1) LuaDLL.lua_pop(t.L, 2); LuaDLL.lua_remove(t.L, indext); } public TablePair Current { get { current.key = LuaObject.checkVar(t.L, -2); current.value = LuaObject.checkVar(t.L, -1); return current; } } object IEnumerator.Current { get { return Current; } } } public IEnumerator<TablePair> GetEnumerator() { return new LuaTable.Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class LuaState : IDisposable { IntPtr l_; int mainThread = 0; internal WeakDictionary<int, LuaDelegate> delgateMap = new WeakDictionary<int, LuaDelegate>(); public int cachedDelegateCount{ get{ return this.delgateMap.AliveCount; } } public IntPtr L { get { if (!isMainThread()) { Logger.LogError("Can't access lua in bg thread"); throw new Exception("Can't access lua in bg thread"); } if (l_ == IntPtr.Zero) { Logger.LogError("LuaState had been destroyed, can't used yet"); throw new Exception("LuaState had been destroyed, can't used yet"); } return l_; } set { l_ = value; } } public IntPtr handle { get { return L; } } public int Top { get { return LuaDLL.lua_gettop(L); } } public delegate byte[] LoaderDelegate(string fn); public delegate void OutputDelegate(string msg); public delegate void PushVarDelegate(IntPtr l, object o); public LoaderDelegate loaderDelegate; public OutputDelegate logDelegate; public OutputDelegate errorDelegate; public OutputDelegate warnDelegate; public delegate void UnRefAction(IntPtr l, int r); struct UnrefPair { public UnRefAction act; public int r; } Queue<UnrefPair> refQueue; public int PCallCSFunctionRef = 0; Dictionary<Type, PushVarDelegate> typePushMap = new Dictionary<Type, PushVarDelegate>(); public static Dictionary<IntPtr, LuaState> statemap = new Dictionary<IntPtr, LuaState>(); static IntPtr oldptr = IntPtr.Zero; static LuaState oldstate = null; static public LuaCSFunction errorFunc = new LuaCSFunction(errorReport); int errorRef = 0; internal LuaFunction newindex_func; internal LuaFunction index_func; const string DelgateTable = "__LuaDelegate"; bool openedSluaLib = false; LuaFunction dumpstack; public bool isMainThread() { return System.Threading.Thread.CurrentThread.ManagedThreadId == mainThread; } #if !SLUA_STANDALONE internal LuaSvrGameObject lgo; #endif static public LuaState get(IntPtr l) { if (l == oldptr) return oldstate; LuaState ls; if (statemap.TryGetValue(l, out ls)) { oldptr = l; oldstate = ls; return ls; } LuaDLL.lua_getglobal(l, "__main_state"); if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); return null; } IntPtr nl = LuaDLL.lua_touserdata(l, -1); LuaDLL.lua_pop(l, 1); if (nl != l) return get(nl); return null; } public void openSluaLib() { LuaArray.init(L); LuaVarObject.init(L); LuaDLL.lua_newtable(L); LuaDLL.lua_setglobal(L, DelgateTable); #if !SLUA_STANDALONE LuaTimer.reg(L); LuaCoroutine.reg(L, lgo); #endif Lua_SLua_ByteArray.reg(L); Helper.reg(L); openedSluaLib = true; } public void openExtLib() { LuaDLL.luaS_openextlibs(L); LuaSocketMini.reg(L); } public void bindUnity() { if (!openedSluaLib) openSluaLib(); LuaSvr.doBind(L); LuaValueType.reg(L); } public IEnumerator bindUnity(Action<int> _tick, Action complete) { if (!openedSluaLib) openSluaLib(); yield return LuaSvr.doBind(L, _tick, complete); LuaValueType.reg(L); } static public LuaState main { get { return LuaSvr.mainState; } } public string Name { get; set; } public LuaState() { if (mainThread == 0) mainThread = System.Threading.Thread.CurrentThread.ManagedThreadId; L = LuaDLL.luaL_newstate(); statemap[L] = this; refQueue = new Queue<UnrefPair>(); ObjectCache.make(L); LuaDLL.lua_atpanic(L, panicCallback); LuaDLL.luaL_openlibs(L); string PCallCSFunction = @" local assert = assert local function check(ok,...) assert(ok, ...) return ... end return function(cs_func) return function(...) return check(cs_func(...)) end end "; LuaDLL.lua_dostring(L, PCallCSFunction); PCallCSFunctionRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); string newindexfun = @" local getmetatable=getmetatable local rawget=rawget local error=error local type=type local function newindex(ud,k,v) local t=getmetatable(ud) repeat local h=rawget(t,k) if h then if h[2] then h[2](ud,v) return else error('property '..k..' is read only') end end t=rawget(t,'__parent') until t==nil error('can not find '..k) end return newindex "; string indexfun = @" local type=type local error=error local rawget=rawget local getmetatable=getmetatable local function index(ud,k) local t=getmetatable(ud) repeat local fun=rawget(t,k) local tp=type(fun) if tp=='function' then return fun elseif tp=='table' then local f=fun[1] if f then return f(ud) else error('property '..k..' is write only') end end t = rawget(t,'__parent') until t==nil error('Can not find '..k) end return index "; newindex_func = (LuaFunction)doString(newindexfun); index_func = (LuaFunction)doString(indexfun); setupPushVar(); pcall(L, init); createGameObject(); } void createGameObject() { #if !SLUA_STANDALONE if (lgo == null #if UNITY_EDITOR && UnityEditor.EditorApplication.isPlaying #endif ) { GameObject go = new GameObject("LuaSvrProxy"); lgo = go.AddComponent<LuaSvrGameObject>(); GameObject.DontDestroyOnLoad(go); lgo.onUpdate = this.tick; lgo.state = this; } #endif } void destroyGameObject() { #if !SLUA_STANDALONE #if UNITY_EDITOR if (UnityEditor.EditorApplication.isPlaying) #endif { if (lgo != null) { GameObject go = lgo.gameObject; GameObject.Destroy(lgo); GameObject.Destroy(go); } } #endif } virtual protected void tick() { checkRef(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int init(IntPtr L) { LuaDLL.lua_pushlightuserdata(L, L); LuaDLL.lua_setglobal(L, "__main_state"); LuaDLL.lua_pushcfunction(L, print); LuaDLL.lua_setglobal(L, "print"); LuaDLL.lua_pushcfunction(L, printerror); LuaDLL.lua_setglobal(L, "printerror"); LuaDLL.lua_pushcfunction(L, warn); LuaDLL.lua_setglobal(L, "warn"); // LuaDLL.lua_pushcfunction(L, pcall); // LuaDLL.lua_setglobal(L, "pcall"); pushcsfunction(L, import); LuaDLL.lua_setglobal(L, "import"); string resumefunc = @" local resume = coroutine.resume local function check(co, ok, err, ...) if not ok then UnityEngine.Debug.LogError(debug.traceback(co,err)) end return ok, err, ... end coroutine.resume=function(co,...) return check(co, resume(co,...)) end "; // overload resume function for report error var state = LuaState.get(L); state.doString(resumefunc); // https://github.com/pkulchenko/MobDebug/blob/master/src/mobdebug.lua#L290 // Dump only 3 stacks, or it will return null (I don't know why) string dumpstackfunc = @" local dumpstack=function() function vars(f) local dump = """" local func = debug.getinfo(f, ""f"").func local i = 1 local locals = {} -- get locals while true do local name, value = debug.getlocal(f, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then dump = dump .. "" "" .. name .. ""="" .. tostring(value) .. ""\n"" end i = i + 1 end -- get varargs (these use negative indices) i = 1 while true do local name, value = debug.getlocal(f, -i) -- `not name` should be enough, but LuaJIT 2.0.0 incorrectly reports `(*temporary)` names here if not name or name ~= ""(*vararg)"" then break end dump = dump .. "" "" .. name .. ""="" .. tostring(value) .. ""\n"" i = i + 1 end -- get upvalues i = 1 while func do -- check for func as it may be nil for tail calls local name, value = debug.getupvalue(func, i) if not name then break end dump = dump .. "" "" .. name .. ""="" .. tostring(value) .. ""\n"" i = i + 1 end return dump end local dump = """" for i = 3, 100 do local source = debug.getinfo(i, ""S"") if not source then break end dump = dump .. ""- stack"" .. tostring(i-2) .. ""\n"" dump = dump .. vars(i+1) if source.what == 'main' then break end end return dump end return dumpstack "; state.dumpstack = state.doString(dumpstackfunc) as LuaFunction; #if UNITY_ANDROID // fix android performance drop with JIT on according to luajit mailist post state.doString("if jit then require('jit.opt').start('sizemcode=256','maxmcode=256') for i=1,1000 do end end"); #endif pushcsfunction(L, dofile); LuaDLL.lua_setglobal(L, "dofile"); pushcsfunction(L, loadfile); LuaDLL.lua_setglobal(L, "loadfile"); pushcsfunction(L, loader); int loaderFunc = LuaDLL.lua_gettop(L); LuaDLL.lua_getglobal(L, "package"); #if LUA_5_3 LuaDLL.lua_getfield(L, -1, "searchers"); #else LuaDLL.lua_getfield(L, -1, "loaders"); #endif int loaderTable = LuaDLL.lua_gettop(L); // Shift table elements right for (int e = LuaDLL.lua_rawlen(L, loaderTable) + 1; e > 2; e--) { LuaDLL.lua_rawgeti(L, loaderTable, e - 1); LuaDLL.lua_rawseti(L, loaderTable, e); } LuaDLL.lua_pushvalue(L, loaderFunc); LuaDLL.lua_rawseti(L, loaderTable, 2); LuaDLL.lua_settop(L, 0); return 0; } void Close() { destroyGameObject(); LuaTimer.DeleteAll(L); if (L != IntPtr.Zero) { Logger.Log("Finalizing Lua State."); // be careful, if you close lua vm, make sure you don't use lua state again, // comment this line as default for avoid unexpected crash. LuaDLL.lua_close(L); ObjectCache.del(L); ObjectCache.clear(); statemap.Remove(L); oldptr = IntPtr.Zero; oldstate = null; L = IntPtr.Zero; } } public void Dispose() { Dispose(true); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } public virtual void Dispose(bool dispose) { if (dispose) { Close(); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int errorReport(IntPtr L) { s.Length = 0; LuaDLL.lua_getglobal(L, "debug"); LuaDLL.lua_getfield(L, -1, "traceback"); LuaDLL.lua_pushvalue(L, 1); LuaDLL.lua_pushnumber(L, 2); LuaDLL.lua_call(L, 2, 1); LuaDLL.lua_remove(L, -2); s.Append(LuaDLL.lua_tostring(L, -1)); LuaDLL.lua_pop(L, 1); LuaState state = LuaState.get(L); state.dumpstack.push(L); LuaDLL.lua_call(L, 0, 1); s.Append("\n"); s.Append(LuaDLL.lua_tostring(L, -1)); LuaDLL.lua_pop(L, 1); string str = s.ToString(); Logger.LogError(str, true); if (state.errorDelegate != null) { state.errorDelegate(str); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int import(IntPtr l) { try { LuaDLL.luaL_checktype(l, 1, LuaTypes.LUA_TSTRING); string str = LuaDLL.lua_tostring(l, 1); string[] ns = str.Split('.'); LuaDLL.lua_pushglobaltable(l); for (int n = 0; n < ns.Length; n++) { LuaDLL.lua_getfield(l, -1, ns[n]); if (!LuaDLL.lua_istable(l, -1)) { return LuaObject.error(l, "expect {0} is type table", ns); } LuaDLL.lua_remove(l, -2); } LuaDLL.lua_pushnil(l); while (LuaDLL.lua_next(l, -2) != 0) { string key = LuaDLL.lua_tostring(l, -2); LuaDLL.lua_getglobal(l, key); if (!LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); return LuaObject.error(l, "{0} had existed, import can't overload it.", key); } LuaDLL.lua_pop(l, 1); LuaDLL.lua_setglobal(l, key); } LuaDLL.lua_pop(l, 1); LuaObject.pushValue(l, true); return 1; } catch (Exception e) { return LuaObject.error(l, e); } } // [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] // internal static int pcall(IntPtr L) // { // int status; // if (LuaDLL.lua_type(L, 1) != LuaTypes.LUA_TFUNCTION) // { // return LuaObject.error(L, "arg 1 expect function"); // } // status = LuaDLL.lua_pcall(L, LuaDLL.lua_gettop(L) - 1, LuaDLL.LUA_MULTRET, 0); // LuaDLL.lua_pushboolean(L, (status == 0)); // LuaDLL.lua_insert(L, 1); // return LuaDLL.lua_gettop(L); /* return status + all results */ // } internal static void pcall(IntPtr l, LuaCSFunction f) { int err = LuaObject.pushTry(l); LuaDLL.lua_pushcfunction(l, f); if (LuaDLL.lua_pcall(l, 0, 0, err) != 0) { LuaDLL.lua_pop(l, 1); } LuaDLL.lua_remove(l, err); } static public bool printTrace = true; private static StringBuilder s = new StringBuilder(); static string stackString(IntPtr L,int n) { s.Length = 0; LuaDLL.lua_getglobal(L, "tostring"); for (int i = 1; i <= n; i++) { if (i > 1) { s.Append(" "); } LuaDLL.lua_pushvalue(L, -1); LuaDLL.lua_pushvalue(L, i); LuaDLL.lua_call(L, 1, 1); s.Append(LuaDLL.lua_tostring(L, -1)); LuaDLL.lua_pop(L, 1); } if (printTrace #if UNITY_EDITOR && SLuaSetting.Instance.PrintTrace #endif ) { LuaDLL.lua_getglobal(L, "debug"); LuaDLL.lua_getfield(L, -1, "traceback"); LuaDLL.lua_call(L, 0, 1); s.Append("\n"); s.Append(LuaDLL.lua_tostring(L, -1)); } return s.ToString(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int print(IntPtr L) { int n = LuaDLL.lua_gettop(L); string str = stackString(L,n); Logger.Log(str, true); LuaState state = LuaState.get(L); if (state.logDelegate != null) { state.logDelegate(s.ToString()); } LuaDLL.lua_settop(L, n); return 0; } // copy from print() [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int printerror(IntPtr L) { int n = LuaDLL.lua_gettop(L); string str = stackString(L,n); Logger.LogError(str, true); LuaState state = LuaState.get(L); if (state.errorDelegate != null) { state.errorDelegate(s.ToString()); } LuaDLL.lua_settop(L, n); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int warn(IntPtr L) { int n = LuaDLL.lua_gettop(L); string str = stackString (L, n); Logger.LogWarning(str); LuaState state = LuaState.get(L); if (state.warnDelegate != null) { state.warnDelegate(s.ToString()); } LuaDLL.lua_settop(L, n); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int loadfile(IntPtr L) { loader(L); if (LuaDLL.lua_isnil(L, -1)) { string fileName = LuaDLL.lua_tostring(L, 1); return LuaObject.error(L, "Can't find {0}", fileName); } return 2; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int dofile(IntPtr L) { int n = LuaDLL.lua_gettop(L); loader(L); if (!LuaDLL.lua_toboolean(L, -2)) { return 2; } else { if (LuaDLL.lua_isnil(L, -1)) { string fileName = LuaDLL.lua_tostring(L, 1); return LuaObject.error(L, "Can't find {0}", fileName); } int k = LuaDLL.lua_gettop(L); LuaDLL.lua_call(L, 0, LuaDLL.LUA_MULTRET); k = LuaDLL.lua_gettop(L); return k - n; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int panicCallback(IntPtr l) { string reason = string.Format("unprotected error in call to Lua API ({0})", LuaDLL.lua_tostring(l, -1)); throw new Exception(reason); } static public void pushcsfunction(IntPtr L, LuaCSFunction function) { LuaDLL.lua_getref(L, get(L).PCallCSFunctionRef); LuaDLL.lua_pushcclosure(L, function, 0); LuaDLL.lua_call(L, 1, 1); } public object doString(string str) { byte[] bytes = Encoding.UTF8.GetBytes(str); object obj; if (doBuffer(bytes, "temp buffer", out obj)) return obj; return null; ; } public object doString(string str, string chunkname) { byte[] bytes = Encoding.UTF8.GetBytes(str); object obj; if (doBuffer(bytes, chunkname, out obj)) return obj; return null; ; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] internal static int loader(IntPtr L) { LuaState state = LuaState.get(L); string fileName = LuaDLL.lua_tostring(L, 1); byte[] bytes = state.loadFile(fileName); if (bytes != null) { if (LuaDLL.luaL_loadbuffer(L, bytes, bytes.Length, "@" + fileName) == 0) { LuaObject.pushValue(L, true); LuaDLL.lua_insert(L, -2); return 2; } else { string errstr = LuaDLL.lua_tostring(L, -1); return LuaObject.error(L, errstr); } } LuaObject.pushValue(L, true); LuaDLL.lua_pushnil(L); return 2; } public object doFile(string file, string function = "") { if (string.IsNullOrEmpty(function)) function = file; byte[] bytes = loadFile(file); if (bytes == null) { Logger.LogError(string.Format("Can't find {0}", file)); return null; } object obj; if (doBuffer(bytes, "@" + function, out obj)) return obj; return null; } /// <summary> /// Ensure remove BOM from bytes /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static byte[] CleanUTF8Bom(byte[] bytes) { if (bytes.Length > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) { var oldBytes = bytes; bytes = new byte[bytes.Length - 3]; Array.Copy(oldBytes, 3, bytes, 0, bytes.Length); } return bytes; } public bool doBuffer(byte[] bytes, string fn, out object ret) { // ensure no utf-8 bom, LuaJIT can read BOM, but Lua cannot! bytes = CleanUTF8Bom(bytes); ret = null; int errfunc = LuaObject.pushTry(L); if (LuaDLL.luaL_loadbuffer(L, bytes, bytes.Length, fn) == 0) { if (LuaDLL.lua_pcall(L, 0, LuaDLL.LUA_MULTRET, errfunc) != 0) { LuaDLL.lua_pop(L, 2); return false; } LuaDLL.lua_remove(L, errfunc); // pop error function ret = topObjects(errfunc - 1); return true; } string err = LuaDLL.lua_tostring(L, -1); LuaDLL.lua_pop(L, 2); throw new Exception(err); } #if UNITY_EDITOR static TextAsset loadAsset(string fn) { TextAsset asset; #if UNITY_5 asset = UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset> (fn); #else asset = (TextAsset)UnityEditor.AssetDatabase.LoadAssetAtPath (fn, typeof(TextAsset)); #endif return asset; } #endif internal byte[] loadFile (string fn) { try { byte[] bytes; if (System.IO.File.Exists(fn)) { bytes = System.IO.File.ReadAllBytes(fn); return bytes; } if (loaderDelegate != null) bytes = loaderDelegate (fn); else { #if !SLUA_STANDALONE fn = fn.Replace (".", "/"); TextAsset asset = null; #if UNITY_EDITOR if (SLuaSetting.Instance.jitType == JITBUILDTYPE.none) { asset = (TextAsset)Resources.Load (fn); } else if (SLuaSetting.Instance.jitType == JITBUILDTYPE.X86) { asset = loadAsset("Assets/Slua/jit/jitx86/" + fn + ".bytes"); } else if (SLuaSetting.Instance.jitType == JITBUILDTYPE.X64) { asset = loadAsset("Assets/Slua/jit/jitx64/" + fn + ".bytes"); } else if (SLuaSetting.Instance.jitType == JITBUILDTYPE.GC64) { asset = loadAsset("Assets/Slua/jit/jitgc64/" + fn + ".bytes"); } #else asset = (TextAsset)Resources.Load<TextAsset>(fn); #endif if (asset == null) return null; bytes = asset.bytes; #else bytes = File.ReadAllBytes(fn); #endif } return bytes; } catch (Exception e) { throw new Exception (e.Message); } } internal object getObject(string key) { LuaDLL.lua_pushglobaltable(L); object o = getObject(key.Split(new char[] { '.' })); LuaDLL.lua_pop(L, 1); return o; } internal void setObject(string key, object v) { LuaDLL.lua_pushglobaltable(L); setObject(key.Split(new char[] { '.' }), v); LuaDLL.lua_pop(L, 1); } internal object getObject(string[] remainingPath) { object returnValue = null; for (int i = 0; i < remainingPath.Length; i++) { LuaDLL.lua_pushstring(L, remainingPath[i]); LuaDLL.lua_gettable(L, -2); returnValue = this.getObject(L, -1); LuaDLL.lua_remove(L, -2); if (returnValue == null) break; } return returnValue; } internal object getObject(int reference, string field) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getref(L, reference); object returnValue = getObject(field.Split(new char[] { '.' })); LuaDLL.lua_settop(L, oldTop); return returnValue; } internal object getObject(int reference, int index) { if (index >= 1) { LuaDLL.lua_getref (L, reference); LuaDLL.lua_rawgeti (L, -1, index); object returnValue = getObject (L, -1); LuaDLL.lua_pop(L, 2); return returnValue; } else { LuaDLL.lua_getref (L, reference); LuaDLL.lua_pushinteger (L, index); LuaDLL.lua_gettable (L, -2); object returnValue = getObject (L, -1); LuaDLL.lua_pop(L, 2); return returnValue; } } internal object getObject(int reference, object field) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getref(L, reference); LuaObject.pushObject(L, field); LuaDLL.lua_gettable(L, -2); object returnValue = getObject(L, -1); LuaDLL.lua_settop(L, oldTop); return returnValue; } internal void setObject(string[] remainingPath, object o) { int top = LuaDLL.lua_gettop(L); for (int i = 0; i < remainingPath.Length - 1; i++) { LuaDLL.lua_pushstring(L, remainingPath[i]); LuaDLL.lua_gettable(L, -2); } LuaDLL.lua_pushstring(L, remainingPath[remainingPath.Length - 1]); LuaObject.pushVar(L, o); LuaDLL.lua_settable(L, -3); LuaDLL.lua_settop(L, top); } internal void setObject(int reference, string field, object o) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getref(L, reference); setObject(field.Split(new char[] { '.' }), o); LuaDLL.lua_settop(L, oldTop); } internal void setObject(int reference, int index, object o) { if (index >= 1) { LuaDLL.lua_getref (L, reference); LuaObject.pushVar (L, o); LuaDLL.lua_rawseti (L, -2, index); LuaDLL.lua_pop (L, 1); } else { LuaDLL.lua_getref (L, reference); LuaDLL.lua_pushinteger (L, index); LuaObject.pushVar (L, o); LuaDLL.lua_settable (L, -3); LuaDLL.lua_pop (L, 1); } } internal void setObject(int reference, object field, object o) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getref(L, reference); LuaObject.pushObject(L, field); LuaObject.pushObject(L, o); LuaDLL.lua_settable(L, -3); LuaDLL.lua_settop(L, oldTop); } internal object topObjects(int from) { int top = LuaDLL.lua_gettop(L); int nArgs = top - from; if (nArgs == 0) return null; else if (nArgs == 1) { object o = LuaObject.checkVar(L, top); LuaDLL.lua_pop(L, 1); return o; } else { object[] o = new object[nArgs]; for (int n = 1; n <= nArgs; n++) { o[n - 1] = LuaObject.checkVar(L, from + n); } LuaDLL.lua_settop(L, from); return o; } } object getObject(IntPtr l, int p) { p = LuaDLL.lua_absindex(l, p); return LuaObject.checkVar(l, p); } public LuaFunction getFunction(string key) { return (LuaFunction)this[key]; } public LuaTable getTable(string key) { return (LuaTable)this[key]; } public object this[string path] { get { return this.getObject(path); } set { this.setObject(path, value); } } public void gcRef(UnRefAction act, int r) { UnrefPair u = new UnrefPair(); u.act = act; u.r = r; lock (refQueue) { refQueue.Enqueue(u); } } public void checkRef() { int cnt = 0; // fix il2cpp lock issue on iOS lock (refQueue) { cnt = refQueue.Count; } var l = L; for (int n = 0; n < cnt; n++) { UnrefPair u; lock (refQueue) { u = refQueue.Dequeue(); } u.act(l, u.r); } } public void regPushVar(Type t, PushVarDelegate d) { typePushMap[t] = d; } public bool tryGetTypePusher(Type t, out PushVarDelegate d) { return typePushMap.TryGetValue(t, out d); } void setupPushVar() { typePushMap[typeof(float)] = (IntPtr L, object o) => { LuaDLL.lua_pushnumber(L, (float)o); }; typePushMap[typeof(double)] = (IntPtr L, object o) => { LuaDLL.lua_pushnumber(L, (double)o); }; typePushMap[typeof(int)] = (IntPtr L, object o) => { LuaDLL.lua_pushinteger(L, (int)o); }; typePushMap[typeof(uint)] = (IntPtr L, object o) => { LuaDLL.lua_pushnumber(L, Convert.ToUInt32(o)); }; typePushMap[typeof(short)] = (IntPtr L, object o) => { LuaDLL.lua_pushinteger(L, (short)o); }; typePushMap[typeof(ushort)] = (IntPtr L, object o) => { LuaDLL.lua_pushinteger(L, (ushort)o); }; typePushMap[typeof(sbyte)] = (IntPtr L, object o) => { LuaDLL.lua_pushinteger(L, (sbyte)o); }; typePushMap[typeof(byte)] = (IntPtr L, object o) => { LuaDLL.lua_pushinteger(L, (byte)o); }; typePushMap[typeof(Int64)] = typePushMap[typeof(UInt64)] = (IntPtr L, object o) => { #if LUA_5_3 LuaDLL.lua_pushinteger(L, (long)o); #else LuaDLL.lua_pushnumber(L, System.Convert.ToDouble(o)); #endif }; typePushMap[typeof(string)] = (IntPtr L, object o) => { LuaDLL.lua_pushstring(L, (string)o); }; typePushMap[typeof(bool)] = (IntPtr L, object o) => { LuaDLL.lua_pushboolean(L, (bool)o); }; typePushMap[typeof(LuaTable)] = typePushMap[typeof(LuaFunction)] = typePushMap[typeof(LuaThread)] = (IntPtr L, object o) => { ((LuaVar)o).push(L); }; typePushMap[typeof(LuaCSFunction)] = (IntPtr L, object o) => { LuaObject.pushValue(L, (LuaCSFunction)o); }; regPushVar(typeof(UnityEngine.Vector2), (IntPtr L, object o) => { LuaObject.pushValue(L, (UnityEngine.Vector2)o); }); regPushVar(typeof(UnityEngine.Vector3), (IntPtr L, object o) => { LuaObject.pushValue(L, (UnityEngine.Vector3)o); }); regPushVar(typeof(UnityEngine.Vector4), (IntPtr L, object o) => { LuaObject.pushValue(L, (UnityEngine.Vector4)o); }); regPushVar(typeof(UnityEngine.Quaternion), (IntPtr L, object o) => { LuaObject.pushValue(L, (UnityEngine.Quaternion)o); }); regPushVar(typeof(UnityEngine.Color), (IntPtr L, object o) => { LuaObject.pushValue(L, (UnityEngine.Color)o); }); } public int pushTry(IntPtr L) { if (errorRef == 0) { LuaDLL.lua_pushcfunction(L, LuaState.errorFunc); LuaDLL.lua_pushvalue(L, -1); errorRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } else { LuaDLL.lua_getref(L, errorRef); } return LuaDLL.lua_gettop(L); } public object run(string entry) { using (LuaFunction func = getFunction(entry)) { if (func != null) return func.call(); } return null; } } }
25.716626
135
0.516387
[ "Apache-2.0" ]
365082218/meteor_original_ios
Assets/Plugins/Slua_Managed/LuaState.cs
42,383
C#
using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; using IdentityServer.Admin.Core.Constants; using IdentityServer.Admin.Core.Entities.Clients; using IdentityServer.Admin.Infrastructure.Mappers; using IdentityServer.Admin.Models.Client; using IdentityServer.Admin.Services.Client; using IdentityServer.Admin.Services.Localization; namespace IdentityServer.Admin.Controllers { public class ClientClaimController : BaseController { private readonly IClientClaimService _clientClaimService; private readonly ILocalizationService _localizationService; public ClientClaimController(IClientClaimService clientClaimService,ILocalizationService localizationService) { _clientClaimService = clientClaimService; _localizationService = localizationService; } public async Task<IActionResult> Index(int id, int? page) { if (id == 0) { return RedirectToAction("Index", "Client"); } var pagedClientClaims = await _clientClaimService.GetPagedAsync(id, page ?? 1); ViewBag.PagedClientClaims = pagedClientClaims; return View(new ClientClaimModel { ClientId = pagedClientClaims.ClientId }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(ClientClaimModel model) { if (!ModelState.IsValid) { return RedirectToAction(nameof(Index), new { id = model.Id }); } await _clientClaimService.InsertClientClaim(ClientMappers.Mapper.Map<ClientClaim>(model)); SuccessNotification(await _localizationService.GetResourceAsync("Clients.ClientClaims.Added")); return RedirectToAction(nameof(Index), new { Id = model.ClientId }); } [HttpGet] public async Task<IActionResult> Delete(int id) { var clientSecret = await _clientClaimService.GetClientClaimById(id); if (clientSecret == null) { return RedirectToAction("Index", "Client"); } var model = ClientMappers.Mapper.Map<ClientClaimModel>(clientSecret); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Delete(ClientClaimModel model) { var result = await _clientClaimService.DeleteClientClaim(ClientMappers.Mapper.Map<ClientClaim>(model)); if (result) { SuccessNotification(await _localizationService.GetResourceAsync("Clients.ClientClaims.Deleted")); } return RedirectToAction(nameof(Index), new { Id = model.ClientId }); } [HttpGet] public IActionResult SearchClaims(string claim, int limit = 0) { var claims = ClientConstant.GetStandardClaims(); if (!string.IsNullOrEmpty(claim)) { claims = claims.Where(x => x.Contains(claim)).ToList(); } if (limit > 0) { claims = claims.Take(limit).ToList(); } return Ok(claims); } } }
31.923077
117
0.619578
[ "MIT" ]
Olek-HZQ/IdentityServerManagement
src/IdentityServer.Admin/Controllers/ClientClaimController.cs
3,322
C#
using UnityEngine; public class Shadow : MonoBehaviour { }
10.166667
35
0.754098
[ "Apache-2.0" ]
BoringStudio/BurningBear
Assets/Scripts/Utils/Shadow.cs
63
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using log4net; using log4net.Repository.Hierarchy; namespace Mechavian.NodeService.UI.ViewModels { internal class NodeServiceViewModel : INotifyPropertyChanged, IDisposable { private static readonly Dictionary<ServiceStatus, Color> StatusIcon = new Dictionary<ServiceStatus, Color> { {ServiceStatus.Running, Colors.Green}, {ServiceStatus.Starting, Colors.LightGreen}, {ServiceStatus.Stopped, Colors.Blue}, {ServiceStatus.Stopping, Colors.LightBlue} }; private readonly string[] _args; private readonly ObservableCollection<LoggingEventViewModel> _loggingEvents = new ObservableCollection<LoggingEventViewModel>(); private readonly NodeServiceBase _service; private readonly Dispatcher _serviceDispatcher; private readonly DelegateCommand _startCommand; private readonly DelegateCommand _stopCommand; private readonly Dispatcher _uiDispatcher; private string _displayName; private Color _statusColor = Colors.DarkGray; private string _statusText = "UNKNOWN"; public NodeServiceViewModel( NodeServiceBase service, string[] args) { if (service == null) throw new ArgumentNullException("service"); _service = service; _args = args; DisplayName = _service.ServiceName; _startCommand = new DelegateCommand(o => Start(), o => CanStart()); _stopCommand = new DelegateCommand(o => Stop(), o => CanStop()); _service.StatusChanged += (o, s) => _uiDispatcher.Invoke(UpdateStatusProperties); _serviceDispatcher = CreateDispatcher(); _uiDispatcher = Dispatcher.CurrentDispatcher; UpdateStatusProperties(); AttachAppender(service.Log); Start(); } public NodeServiceViewModel() { } public string DisplayName { get { return _displayName; } set { if (value == _displayName) return; _displayName = value; OnPropertyChanged(); } } public Color StatusColor { get { return _statusColor; } set { if (value == _statusColor) return; _statusColor = value; OnPropertyChanged(); } } public string StatusText { get { return _statusText; } set { if (value == _statusText) return; _statusText = value; OnPropertyChanged(); } } public ObservableCollection<LoggingEventViewModel> LoggingEvents { get { return _loggingEvents; } } public ICommand StartCommand { get { return _startCommand; } } public ICommand StopCommand { get { return _stopCommand; } } public void Dispose() { if (_serviceDispatcher != null) { _serviceDispatcher.InvokeShutdown(); } } public event PropertyChangedEventHandler PropertyChanged; private void AttachAppender(ILog log) { var logger = log.Logger as Logger; if (logger != null) { var appender = new NodeServiceLogAppender(); appender.LogAppended += (o, e) => _uiDispatcher.BeginInvoke(new Action(() => LoggingEvents.Add(new LoggingEventViewModel(e)))); logger.AddAppender(appender); } } private Dispatcher CreateDispatcher() { Dispatcher dispatcher = null; var dispatcherReadyEvent = new ManualResetEvent(false); new Thread(() => { dispatcher = Dispatcher.CurrentDispatcher; dispatcherReadyEvent.Set(); Dispatcher.Run(); }).Start(); dispatcherReadyEvent.WaitOne(); return dispatcher; } private void UpdateStatusProperties() { StatusColor = StatusIcon[_service.Status]; StatusText = _service.Status.ToString("G"); _startCommand.RaiseCanExecuteChanged(); _stopCommand.RaiseCanExecuteChanged(); } public Task Start() { if (CanStart()) { var tcs = new TaskCompletionSource<int>(); _serviceDispatcher.BeginInvoke(new Action(() => { _service.StartImpl(_args); tcs.SetResult(0); })); return tcs.Task; } return Task.FromResult(0); } public bool CanStart() { return _service.Status == ServiceStatus.Stopped; } public Task Stop() { var tcs = new TaskCompletionSource<int>(); _serviceDispatcher.BeginInvoke(new Action(() => { _service.StopImpl(); tcs.SetResult(0); })); return tcs.Task; } public bool CanStop() { return _service.Status == ServiceStatus.Running; } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
29.372549
143
0.561582
[ "MIT" ]
Mechavian/node-service
src/NodeService.UI/ViewModels/NodeServiceViewModel.cs
5,994
C#
/* * Copyright (C) 2004 Bruno Fernandez-Ruiz <brunofr@olympum.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. */ namespace Caffeine.Caffeinator { using System; using System.Collections; using System.Text; using System.Reflection; public class Class { Class declaringClass; string internalName; // java/util/Map$Entry string name; // Entry string fqn; // java.util.Map.Entry string ns; // java.util AccessFlag accessFlags; ArrayList baseTypes; ArrayList fields; ArrayList methods; ArrayList innerClasses; public Class() { baseTypes = new ArrayList(); fields = new ArrayList(); methods = new ArrayList(); innerClasses = new ArrayList(); } public Class(string internalName, string fqn, AccessFlag accessFlags) : this() { this.internalName = internalName; this.fqn = fqn; this.accessFlags = accessFlags; } public AccessFlag AccessFlags { set { accessFlags = value; } get { return accessFlags; } } public string InternalName { get { return internalName; } set { internalName = value; } } public string FullyQualifiedName { get { if (fqn == null) { // java.lang.Object fqn = internalName.Replace('/', '.').Replace('$', '+'); } return fqn; } set { fqn = value; } } public string Name { get { if (name == null) { // java/util/Map$Entry -> Entry string dottified = FullyQualifiedName; int index = dottified.LastIndexOf('+'); if (index < 0) { return dottified; } name = dottified.Substring(index + 1); } return name; } set { name = value; } } public string NameSpace { get { if (ns == null) { // java/util/Map$Entry -> java.util int index = internalName.LastIndexOf('/'); if (index < 0) { return String.Empty; } ns = internalName.Substring(0, index).Replace('/', '.'); } return ns; } set { ns = value; } } public ICollection BaseTypes { get { return baseTypes; } } public ICollection Fields { get { return fields; } } public ICollection Methods { get { return methods; } } public ICollection InnerTypes { get { return innerClasses; } } public Class DeclaringClass { set { declaringClass = value; } get { return declaringClass; } } public void AddBaseType(Class typeName) { if (typeName == null) { return; } if (baseTypes.Contains(typeName)) { throw new ApplicationException("Duplicate BaseType: " + typeName); } baseTypes.Add(typeName); } public void AddInnerClass(Class c) { if (innerClasses.Contains(c)) { // this can happen while processing things like: // javax/swing/text/html/HTMLDocument$HTMLReader$TitleAction return; } innerClasses.Add(c); c.DeclaringClass = this; } public void AddField(Field f) { if (fields.Contains(f)){ throw new ApplicationException("Duplicate Field: " + f); } fields.Add(f); } public void AddMethod(Method m) { if (methods.Contains(m)){ throw new ApplicationException("Duplicate Method: " + m); } methods.Add(m); } public bool IsPublic { get { return (accessFlags & AccessFlag.ACC_PUBLIC) != 0; } } public bool IsFinal { get { return (accessFlags & AccessFlag.ACC_FINAL) != 0; } } public bool IsInterface { get { return (accessFlags & AccessFlag.ACC_INTERFACE) != 0; } } public bool IsAbstract { get { return (accessFlags & AccessFlag.ACC_ABSTRACT) != 0; } } public TypeAttributes TypeAttributes { get { TypeAttributes r; if (IsPublic) { r = TypeAttributes.Public; } else { r = TypeAttributes.NotPublic; } if (IsInterface) { r |= TypeAttributes.Interface; } else { r |= TypeAttributes.Class; } if (IsFinal) { r |= TypeAttributes.Sealed; } if (IsAbstract) { r |= TypeAttributes.Abstract; } if (DeclaringClass != null) { if (IsPublic) { r |= TypeAttributes.NestedPublic; } else { r |= TypeAttributes.NestedFamily; } } // TODO serializable // r |= TypeAttributes.Serializable; return r; } } public enum AccessFlag { ACC_PUBLIC = 0x0001, ACC_FINAL = 0x0010, ACC_INTERFACE = 0x0200, ACC_ABSTRACT = 0x0400 } public override string ToString() { return Name; } } }
20.663004
80
0.621876
[ "MIT" ]
olympum/caffeine
src/Caffeine.Caffeinator/Class.cs
5,641
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThanOrEqual.Complete.NullableInt32.NullableInt64{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Int32>; using T_DATA2 =System.Nullable<System.Int64>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__02__VN public static class TestSet_504__param__02__VN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ <= /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ <= /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__02__VN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThanOrEqual.Complete.NullableInt32.NullableInt64
28.116667
150
0.537937
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/LessThanOrEqual/Complete/NullableInt32/NullableInt64/TestSet_504__param__02__VN.cs
3,376
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OOPPrinciples Part1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OOPPrinciples Part1")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8ad2d31f-4f5e-4e3b-a076-f19226f0acb0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.135135
84
0.746279
[ "MIT" ]
PowerfullChild/CSharp-OOP
OOPPrinciples Part1/OOPPrinciples Part1/Properties/AssemblyInfo.cs
1,414
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace HelloWorld.SOLID.WebApi.Areas.HelpPage.ModelDescriptions { public class EnumTypeModelDescription : ModelDescription { public EnumTypeModelDescription() { Values = new Collection<EnumValueDescription>(); } public Collection<EnumValueDescription> Values { get; private set; } } }
27.8
76
0.71223
[ "MIT" ]
jcrowegitHu8/HellowWorld.SOLID.Example
HelloWorld.SOLID.WebApi/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs
417
C#
#region Using directives using Cureos.Measures; using Cureos.Measures.Quantities; using Sharp3D.Math.Core; using treeDiM.StackBuilder.Basics; #endregion namespace treeDiM.Basics { public partial class UnitsManagerEx { public static Vector2D ConvertLengthFrom(Vector2D value, UnitsManager.UnitSystem unitSystem) { if (unitSystem == UnitsManager.CurrentUnitSystem) return value; else { StandardMeasure<Length> measureX = new StandardMeasure<Length>(value.X, UnitsManager.LengthUnitFromUnitSystem(unitSystem)); StandardMeasure<Length> measureY = new StandardMeasure<Length>(value.Y, UnitsManager.LengthUnitFromUnitSystem(unitSystem)); return new Vector2D( measureX.GetAmount(UnitsManager.LengthUnitFromUnitSystem(UnitsManager.CurrentUnitSystem)) , measureY.GetAmount(UnitsManager.LengthUnitFromUnitSystem(UnitsManager.CurrentUnitSystem)) ); } } public static Vector3D ConvertLengthFrom(Vector3D value, UnitsManager.UnitSystem unitSystem) { if (unitSystem == UnitsManager.CurrentUnitSystem) return value; else { StandardMeasure<Length> measureX = new StandardMeasure<Length>(value.X, UnitsManager.LengthUnitFromUnitSystem(unitSystem)); StandardMeasure<Length> measureY = new StandardMeasure<Length>(value.Y, UnitsManager.LengthUnitFromUnitSystem(unitSystem)); StandardMeasure<Length> measureZ = new StandardMeasure<Length>(value.Z, UnitsManager.LengthUnitFromUnitSystem(unitSystem)); return new Vector3D( measureX.GetAmount(UnitsManager.LengthUnitFromUnitSystem(UnitsManager.CurrentUnitSystem)) , measureY.GetAmount(UnitsManager.LengthUnitFromUnitSystem(UnitsManager.CurrentUnitSystem)) , measureZ.GetAmount(UnitsManager.LengthUnitFromUnitSystem(UnitsManager.CurrentUnitSystem)) ); } } public static BoxPosition ConvertLengthFrom(BoxPosition value, UnitsManager.UnitSystem unitSystem) { if (unitSystem == UnitsManager.CurrentUnitSystem) return value; else return new BoxPosition( ConvertLengthFrom(value.Position, unitSystem), value.DirectionLength, value.DirectionWidth); } } }
45.963636
139
0.660601
[ "MIT" ]
metc/StackBuilder
Sources/TreeDim.StackBuilder.Basics/UnitsManager.cs
2,530
C#
using System; using System.Net; namespace BuildsAppReborn.Contracts.Models { public class DataResponse<T> { public T Data { get; set; } public Boolean IsSuccessStatusCode { get { if (StatusCode >= HttpStatusCode.OK) { return StatusCode <= (HttpStatusCode) 299; } return false; } } public HttpStatusCode StatusCode { get; set; } public void ThrowIfUnsuccessful() { if (!IsSuccessStatusCode) { throw new DataResponseUnsuccessfulException(StatusCode); } } } }
21.515152
72
0.491549
[ "MIT" ]
lgrabarevic/BuildsAppReborn
BuildsAppReborn.Contracts/Models/DataResponse.cs
712
C#
using GovUk.Education.ExploreEducationStatistics.Common.Extensions; using Newtonsoft.Json; namespace GovUk.Education.ExploreEducationStatistics.Data.Model { public class LocalAuthority : IObservationalUnit { public string Code { get; set; } [JsonIgnore] public string OldCode { get; set; } public string Name { get; set; } public LocalAuthority() { } public LocalAuthority(string code, string oldCode, string name) { Code = code; OldCode = oldCode; Name = name; } public static LocalAuthority Empty() { return new LocalAuthority(null, null, null); } public string GetCodeOrOldCodeIfEmpty() { return Code.IsNullOrEmpty() ? OldCode : Code; } protected bool Equals(LocalAuthority other) { return string.Equals(Code, other.Code); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((LocalAuthority) obj); } public override int GetHashCode() { return (Code != null ? Code.GetHashCode() : 0); } } }
27.137255
71
0.570809
[ "MIT" ]
benoutram/explore-education-statistics
src/GovUk.Education.ExploreEducationStatistics.Data.Model/LocalAuthority.cs
1,384
C#
using System; using System.IO; using System.Linq; namespace AoC { class Program { static void Main(string[] args) { var useTestData = args.Contains("--test"); var app = Bootstrap(useTestData); app.Solver.FindCorners ( app.TileReader.GetTiles(app.InputPath) ); } private static (string InputPath, TileReader TileReader, Solver Solver) Bootstrap(bool useTestData) { var filename = useTestData ? "Test-Input.txt" : "Input.txt"; return ( Path.Join(Directory.GetCurrentDirectory(), filename), new TileReader(), new Solver() ); } } }
22.305556
108
0.49066
[ "MIT" ]
David-Rushton/AdventOfCode-Solutions
2020/Day20/Program.cs
805
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class Brick : MonoBehaviour { public BrickData Data; protected ItemDropController itemDrop; protected PointController pointController; protected ParticleSpawner particleSpawner; [SerializeField] protected List<ParticleSystem> particles = default; private MeshRenderer meshRenderer; private Collider col; [SerializeField] private SoundPlayer soundPlayer = default; private void Awake() { particleSpawner = new ParticleSpawner(particles); itemDrop = FindObjectOfType<ItemDropController>(); pointController = FindObjectOfType<PointController>(); meshRenderer = GetComponent<MeshRenderer>(); col = GetComponent<BoxCollider>(); } private void OnCollisionEnter(Collision collision) { soundPlayer.Play(); var ball = collision.collider.GetComponent<BallController>(); var projectile = collision.collider.GetComponent<Projectile>(); if (ball) { TakeDamage(ball.Force); } else if(projectile) { TakeDamage(projectile.Damage); } } public void TakeDamage(float force) { StartCoroutine(GiveDamage(force)); } private IEnumerator GiveDamage(float force) { DealDamage(force); if (Data.HP <= 0f) { meshRenderer.enabled = false; col.enabled = false; } VisualizeDamage(); particleSpawner.Launch(); yield return new WaitForSeconds(0.25f); DeactivateBrick(); } private void DealDamage(float force) { Data.HP -= force; } public abstract void VisualizeDamage(); public abstract void DeactivateBrick(); }
25.472222
71
0.643948
[ "MIT" ]
kamitul/Breakout
Assets/Scripts/Bricks/Brick.cs
1,836
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using EventFinder.Models.Repositories; using EventFinder.Models.Entity; namespace EventFinder.Controllers { [Authorize()] public class Setting : Controller { public IRepositoryBase<User> UserRepository {get;} public Setting(IRepositoryBase<User> userRepository) { this.UserRepository = userRepository; } public IActionResult Settings(int? id) { if(id == null){ return BadRequest(); } else{ Models.Entity.User user = UserRepository.Find((int)id); return View(user); } } } }
23.580645
71
0.589603
[ "Apache-2.0" ]
NoskovEugene/EventFinder
Controllers/Setting.cs
731
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TO8CHTX_GraceNote { class TSSEntry { public uint[] Entry; public String StringJPN; public String StringENG; private int StringJPNIndex; private int StringENGIndex; public TSSEntry(uint[] Entry, String StringJPN, String StringENG, int StringJPNIndex, int StringENGIndex) { this.Entry = Entry; this.StringJPN = StringJPN; this.StringENG = StringENG; this.StringJPNIndex = StringJPNIndex; this.StringENGIndex = StringENGIndex; } private void SetPointer(int index, uint Pointer) { Entry[index] = Pointer; } public void SetJPNPointer(uint Pointer) { SetPointer(StringJPNIndex, Pointer); } public void SetENGPointer(uint Pointer) { SetPointer(StringENGIndex, Pointer); } public byte[] SerializeScript() { List<byte> bytes = new List<byte>(Entry.Length); foreach (uint e in Entry) { bytes.AddRange(System.BitConverter.GetBytes(Util.SwapEndian(e))); } return bytes.ToArray(); } } }
25.901961
113
0.576079
[ "MIT" ]
AdmiralCurtiss/ToVPatcher
Scripts/tools/Scenario_GraceNote_Mark360/TO8CHTX_GraceNote/TSSEntry.cs
1,323
C#
namespace System { /// <summary> /// Contains event data of a specified type <typeparamref name="T"/>. /// </summary> public class EventArgs<T> : EventArgs { /// <summary> /// Exposes the constructor as a delegate. /// </summary> public static readonly Func<T, EventArgs<T>> Create = value => new EventArgs<T>(value); /// <summary> /// Exposes the wrapped value for the specified event data type. /// </summary> public T Value { get; private set; } private EventArgs(T value) { Value = value; } } }
28.478261
96
0.519084
[ "MIT" ]
TylerKendrick/Sugar.Core
Sugar/EventArgs.cs
657
C#
using System; using System.Collections.Generic; using System.Text; using System.Numerics; using Slipe.MtaDefinitions; using Slipe.Shared.Utilities; namespace Slipe.Shared.Vehicles { /// <summary> /// Represents the set of all sirens on a vehicle /// </summary> public class SharedSirens { protected SharedVehicle vehicle; #region Properties protected SirenType type; /// <summary> /// Get the type of this siren set /// </summary> public SirenType Type { get { return type; } } protected bool visibleFromAllDirection; /// <summary> /// Visible from all directions (applies to single type only) /// </summary> public bool VisibleFromAllDirections { get { return visibleFromAllDirection; } } protected bool checkLOS; /// <summary> /// Check line of sight between camera and light so it won't draw if blocked /// </summary> public bool CheckLineOfSight { get { return checkLOS; } } protected bool useRandomiser; /// <summary> /// Randomise the light order, false for sequential /// </summary> public bool UseRandomiser { get { return useRandomiser; } } protected bool silent; /// <summary> /// If the silent is silent (no audio) or not /// </summary> public bool Silent { get { return silent; } } /// <summary> /// Get and set if the sirens are on /// </summary> public bool On { get { return MtaShared.GetVehicleSirensOn(vehicle.MTAElement); } set { // This is due to an MTA bug not turning on silent sirens that are off MtaShared.SetVehicleSirensOn(vehicle.MTAElement, false); MtaShared.SetVehicleSirensOn(vehicle.MTAElement, value); } } /// <summary> /// Get all the attached individual sirens /// </summary> public Siren[] All { get { dynamic[] ar = MtaShared.GetArrayFromTable(MtaShared.GetVehicleSirens(vehicle.MTAElement), "dynamic"); Siren[] result = new Siren[ar.Length]; for (int i = 0; i < ar.Length; i++) { Dictionary<string, float> d = (Dictionary<string, float>)MtaShared.GetDictionaryFromTable(ar[i], "System.String", "System.Single"); result[i] = new Siren(vehicle, i + 1, new Vector3(d["x"], d["y"], d["z"]), new Color((byte)d["Red"], (byte)d["Green"], (byte)d["Blue"], (byte)d["Alpha"]), d["Min_Alpha"], false); } return result; } } #endregion /// <summary> /// Create a sirens set attached to a vehicle /// </summary> public SharedSirens(SharedVehicle vehicle) { this.vehicle = vehicle; UpdateParams(); } protected void UpdateParams() { Dictionary<string, dynamic> d = MtaShared.GetDictionaryFromTable(MtaShared.GetVehicleSirenParams(vehicle.MTAElement), "System.String", "dynamic"); type = (SirenType)d["SirenType"]; Dictionary<string, bool> flags = MtaShared.GetDictionaryFromTable(d["Flags"], "System.String", "System.Boolean"); visibleFromAllDirection = flags["360"]; checkLOS = flags["DoLOSCheck"]; useRandomiser = flags["UseRandomiser"]; silent = flags["Silent"]; } } }
29.496296
198
0.509292
[ "Apache-2.0" ]
Citizen01/Slipe-Core
Slipe/Core/Source/SlipeShared/Vehicles/SharedSirens.cs
3,984
C#
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Sitecore.Demo.Init.Extensions; using Sitecore.Demo.Init.Jobs; using Sitecore.Demo.Init.Model; namespace Sitecore.Demo.Init.Services { public sealed class JobManagementManagementService : BackgroundService, IJobManagementService { private readonly ILogger<JobManagementManagementService> logger; private readonly InitContext initContext; private readonly IStateService stateService; public JobManagementManagementService(ILoggerFactory logFactory, ILogger<JobManagementManagementService> logger, InitContext initContext, IStateService stateService) { ApplicationLogging.LoggerFactory = logFactory; this.logger = logger; this.initContext = initContext; this.stateService = stateService; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { logger.LogInformation($"{DateTime.UtcNow} Init started."); await stateService.SetState(InstanceState.Initializing); await new WaitForContextDatabase(initContext).Run(); await new WaitForSitecoreToStart(initContext).Run(); await new PopulateManagedSchema(initContext).Run(); await stateService.SetState(InstanceState.WarmingUp); await new UpdateDamUri(initContext).Run(); await new PushSerialized(initContext).Run(); await new ClearAllCaches(initContext).Run(); await new WarmupCM(initContext).Run(); await stateService.SetState(InstanceState.Preparing); await new DeployToVercel(initContext).Run(); await stateService.SetState(InstanceState.Ready); } catch (Exception ex) { logger.LogError(ex, "An error has occurred when running JobManagementManagementService"); } } } }
42
121
0.646062
[ "MIT" ]
MadhavJ/Sitecore.Demo.Edge
docker/build/init/Services/JobManagementManagementService.cs
2,135
C#
/* This file is licensed to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Xml; using Org.XmlUnit.Transform; namespace Org.XmlUnit.Input { /// <summary> /// ISource implementation that is obtained from a different /// source by stripping all comments. /// </summary> /// <remarks> /// <para> /// As of XMLUnit.NET 2.5.0 it is possible to select the XSLT /// version to use for the stylesheet. The default now is 2.0, /// it used to be 1.0 and you may need to change the value if /// your transformer doesn't support XSLT 2.0. /// </para> /// </remarks> public sealed class CommentLessSource : ISource { private bool disposed; private readonly XmlReader reader; private string systemId; private const string DEFAULT_VERSION = "2.0"; private const string STYLE_TEMPLATE = "<stylesheet xmlns=\"http://www.w3.org/1999/XSL/Transform\" version=\"{0}\">" + "<template match=\"node()[not(self::comment())]|@*\"><copy>" + "<apply-templates select=\"node()[not(self::comment())]|@*\"/>" + "</copy></template>" + "</stylesheet>"; private static readonly string STYLE = GetStylesheetContent(DEFAULT_VERSION); /// <summary> /// Creates a new Source with the same content as another /// source removing all comments using an XSLT stylesheet of /// version 2.0. /// </summary> /// <param name="originalSource">source with the original content</param> public CommentLessSource(ISource originalSource) : this(originalSource, DEFAULT_VERSION) { } /// <summary> /// Creates a new Source with the same content as another /// source removing all comments. /// </summary> /// <remarks> /// <para> /// since XMLUnit 2.5.0 /// </para> /// </remarks> /// <param name="originalSource">source with the original content</param> /// <param name="xsltVersion">use this version for the stylesheet</param> public CommentLessSource(ISource originalSource, string xsltVersion) { if (originalSource == null) { throw new ArgumentNullException(); } if (xsltVersion == null) { throw new ArgumentNullException(); } systemId = originalSource.SystemId; Transformation t = new Transformation(originalSource); t.Stylesheet = GetStylesheet(xsltVersion); reader = new XmlNodeReader(t.TransformToDocument()); } /// <inheritdoc/> public XmlReader Reader { get { return reader; } } /// <inheritdoc/> public string SystemId { get { return systemId; } set { systemId = value; } } public void Dispose() { if (!disposed) { reader.Close(); disposed = true; } } private static ISource GetStylesheet(string xsltVersion) { return new StreamSource(new System.IO.StringReader(GetStylesheetContentCached(xsltVersion))); } private static string GetStylesheetContentCached(string xsltVersion) { return DEFAULT_VERSION == xsltVersion ? STYLE : GetStylesheetContent(xsltVersion); } private static string GetStylesheetContent(string xsltVersion) { return string.Format(STYLE_TEMPLATE, xsltVersion); } } }
33.991935
105
0.588612
[ "Apache-2.0" ]
bodewig/xmlunit.net
src/main/net-core/Input/CommentLessSource.cs
4,215
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using Microsoft.Azure.Management.SiteRecovery.Models; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Test; using System.Net; using Xunit; using System.Collections.Generic; using System; namespace SiteRecovery.Tests { public class SiteTests : SiteRecoveryTestsBase { string siteName = "site3"; public void CreateSite() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); FabricCreationInput siteInput = new FabricCreationInput(); siteInput.Properties = new FabricCreationInputProperties(); siteInput.Properties.FabricType = ""; var site = client.Fabrics.Create(siteName, siteInput, RequestHeaders); var response = client.Fabrics.Get(siteName, RequestHeaders); Assert.True(response.Fabric.Name == siteName, "Site Name can not be different"); } } public void DeleteSite() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var site = client.Fabrics.Delete(siteName, new FabricDeletionInput(), RequestHeaders); Assert.True(site.StatusCode == HttpStatusCode.NoContent, "Site Name should have been deleted"); } } } }
34.403226
111
0.654477
[ "Apache-2.0" ]
ailn/azure-sdk-for-net
src/ResourceManagement/SiteRecovery/SiteRecovery.Tests/ScenarioTests/SiteTests.cs
2,135
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Allowedfileextensionbulkdeletefailures. /// </summary> public static partial class AllowedfileextensionbulkdeletefailuresExtensions { /// <summary> /// Get adoxio_allowedfileextension_BulkDeleteFailures from /// adoxio_allowedfileextensions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioAllowedfileextensionid'> /// key: adoxio_allowedfileextensionid of adoxio_allowedfileextension /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbulkdeletefailureCollection Get(this IAllowedfileextensionbulkdeletefailures operations, string adoxioAllowedfileextensionid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(adoxioAllowedfileextensionid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get adoxio_allowedfileextension_BulkDeleteFailures from /// adoxio_allowedfileextensions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioAllowedfileextensionid'> /// key: adoxio_allowedfileextensionid of adoxio_allowedfileextension /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbulkdeletefailureCollection> GetAsync(this IAllowedfileextensionbulkdeletefailures operations, string adoxioAllowedfileextensionid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(adoxioAllowedfileextensionid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get adoxio_allowedfileextension_BulkDeleteFailures from /// adoxio_allowedfileextensions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioAllowedfileextensionid'> /// key: adoxio_allowedfileextensionid of adoxio_allowedfileextension /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMbulkdeletefailureCollection> GetWithHttpMessages(this IAllowedfileextensionbulkdeletefailures operations, string adoxioAllowedfileextensionid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.GetWithHttpMessagesAsync(adoxioAllowedfileextensionid, top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get adoxio_allowedfileextension_BulkDeleteFailures from /// adoxio_allowedfileextensions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioAllowedfileextensionid'> /// key: adoxio_allowedfileextensionid of adoxio_allowedfileextension /// </param> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbulkdeletefailure BulkDeleteFailuresByKey(this IAllowedfileextensionbulkdeletefailures operations, string adoxioAllowedfileextensionid, string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.BulkDeleteFailuresByKeyAsync(adoxioAllowedfileextensionid, bulkdeletefailureid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get adoxio_allowedfileextension_BulkDeleteFailures from /// adoxio_allowedfileextensions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioAllowedfileextensionid'> /// key: adoxio_allowedfileextensionid of adoxio_allowedfileextension /// </param> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbulkdeletefailure> BulkDeleteFailuresByKeyAsync(this IAllowedfileextensionbulkdeletefailures operations, string adoxioAllowedfileextensionid, string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BulkDeleteFailuresByKeyWithHttpMessagesAsync(adoxioAllowedfileextensionid, bulkdeletefailureid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get adoxio_allowedfileextension_BulkDeleteFailures from /// adoxio_allowedfileextensions /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioAllowedfileextensionid'> /// key: adoxio_allowedfileextensionid of adoxio_allowedfileextension /// </param> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<MicrosoftDynamicsCRMbulkdeletefailure> BulkDeleteFailuresByKeyWithHttpMessages(this IAllowedfileextensionbulkdeletefailures operations, string adoxioAllowedfileextensionid, string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null) { return operations.BulkDeleteFailuresByKeyWithHttpMessagesAsync(adoxioAllowedfileextensionid, bulkdeletefailureid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
51.390698
556
0.590823
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/AllowedfileextensionbulkdeletefailuresExtensions.cs
11,049
C#
using System.Text.Json.Serialization; namespace Topdev.Bittrex { public class NewTransfer { [JsonPropertyName("toSubaccountId")] public string ToSubaccountId { get; set; } [JsonPropertyName("requestId")] public string RequestId { get; set; } [JsonPropertyName("currencySymbol")] public string CurrencySymbol { get; set; } [JsonPropertyName("amount")] [JsonConverter(typeof(DoubleConverterWithStringSupport))] public double Amount { get; set; } [JsonPropertyName("toMasterAccount")] public bool ToMasterAccount { get; set; } } }
25.36
65
0.648265
[ "MIT" ]
tomaspavlic/bittrex-api-clien
src/Entities/NewTransfer.cs
634
C#
using CsvHelper.Configuration; namespace CsvHelperDemo { public class PersonMapByIndex : ClassMap<PersonV1> { public PersonMapByIndex() { Map(p => p.FirstName).Index(0); Map(p => p.LastName).Index(1); Map(p => p.Age).Index(2); Map(p => p.IsActive).Index(4); } } }
21.875
54
0.531429
[ "MIT" ]
duongntbk/CsvHelperDemo
CsvHelperDemo/PersonMapByIndex.cs
352
C#
using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using NUnit.Framework; public class Perf12 { //GetByTypeAndDamageRange [TestCase] public void GetByTypeAndDamageRangeOrderedByDamageThenById() { IArena ar = new RoyaleArena(); List<Battlecard> cds = new List<Battlecard>(); Random rand = new Random(); for (int i = 0; i < 100000; i++) { int amount = rand.Next(0, 1000); Battlecard cd = new Battlecard(i, CardType.BUILDING, "sender", amount, 15); ar.Add(cd); if (amount > 200 && amount <= 600) cds.Add(cd); } cds = cds.OrderByDescending(x => x.Damage).ThenBy(x => x.Id).ToList(); int count = ar.Count; Assert.AreEqual(100000, count); Stopwatch watch = new Stopwatch(); watch.Start(); IEnumerable<Battlecard> all = ar.GetByTypeAndDamageRangeOrderedByDamageThenById( CardType.BUILDING, 200, 600); int c = 0; foreach (Battlecard cd in all) { Assert.AreSame(cd, cds[c]); c++; } watch.Stop(); long l1 = watch.ElapsedMilliseconds; Assert.Less(l1, 150); Assert.AreEqual(cds.Count, c); } }
27.291667
88
0.570229
[ "Apache-2.0" ]
KostadinovK/Data-Structures
12-Exam-Prep/Exam-20.05.2018/02-RoyalArena/RoyaleArena.Tests/Performance/Perf12.cs
1,312
C#
using FailTracker.Web.Domain; using Microsoft.AspNet.Identity.EntityFramework; namespace FailTracker.Web.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
21.555556
71
0.685567
[ "MIT" ]
mcarcini/FailTracker
FailTracker.Web/Data/ApplicationDbContext.cs
390
C#
using Haley.Abstractions; using Haley.Enums; using Haley.Events; using Haley.Models; using Haley.MVVM; using Haley.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace NotificationDemo { public class DialogVM : ChangeNotifier, IHaleyVM { public event EventHandler<FrameClosingEventArgs> ViewModelClosed; public ICommand closeCommand => new DelegateCommand(_close); private void _close() { // ViewModelClosed.Invoke(this, null); } public void OnViewLoaded(object sender) { } private bool isManager; public bool IsManager { get { return isManager; } set { SetProp(ref isManager, value); } } private bool _isEmployee; public bool IsEmployee { get { return _isEmployee; } set { SetProp(ref _isEmployee, value); } } private bool _isPresident; public bool IsPresident { get { return _isPresident; } set { SetProp(ref _isPresident, value); } } public DialogVM() { } } }
21.525424
73
0.594488
[ "MIT" ]
TheHaleyProject/HaleyMVVM
_TESTING/NotificationDemo/DialogVM.cs
1,272
C#
namespace Tailwind.Traders.ImageClassifier.Api.Mlnet { public struct TensorFlowModelSettings { // input tensor name public const string inputTensorName = "Placeholder"; // output tensor name public const string outputTensorName = "loss"; } }
24
60
0.670139
[ "MIT" ]
4villains/TailwindTraders-Backend-1
Source/Services/Tailwind.Traders.ImageClassifier.Api/Mlnet/TensorFlowModelSettings.cs
290
C#
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org. // IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Xml.Serialization; using BuildingSmart.IFC.IfcKernel; using BuildingSmart.IFC.IfcMeasureResource; using BuildingSmart.IFC.IfcUtilityResource; namespace BuildingSmart.IFC.IfcProductExtension { public partial class IfcRelContainedInSpatialStructure : IfcRelConnects { [DataMember(Order = 0)] [Description("Set of products, which are contained within this level of the spatial structure hierarchy. <blockquote class=\"change-ifc2x\">IFC2x CHANGE&nbsp; The data type has been changed from <em>IfcElement</em> to <em>IfcProduct</em> with upward compatibility</blockquote> ")] [Required()] [MinLength(1)] public ISet<IfcProduct> RelatedElements { get; protected set; } [DataMember(Order = 1)] [XmlIgnore] [Description("Spatial structure element, within which the element is contained. Any element can only be contained within one element of the project spatial structure. <blockquote class=\"change-ifc2x4\">IFC4 CHANGE&nbsp; The attribute <em>RelatingStructure</em> as been promoted to the new supertype <em>IfcSpatialElement</em> with upward compatibility for file based exchange.</blockquote>")] [Required()] public IfcSpatialElement RelatingStructure { get; set; } public IfcRelContainedInSpatialStructure(IfcGloballyUniqueId __GlobalId, IfcOwnerHistory __OwnerHistory, IfcLabel? __Name, IfcText? __Description, IfcProduct[] __RelatedElements, IfcSpatialElement __RelatingStructure) : base(__GlobalId, __OwnerHistory, __Name, __Description) { this.RelatedElements = new HashSet<IfcProduct>(__RelatedElements); this.RelatingStructure = __RelatingStructure; } } }
45.6
396
0.795322
[ "Unlicense", "MIT" ]
BuildingSMART/IfcDoc
IfcKit/schemas/IfcProductExtension/IfcRelContainedInSpatialStructure.cs
2,052
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Maui.Trading.Model { public class TimeRange : ClosedInterval<DateTime> { public static readonly TimeRange All = new TimeRange( DateTime.MinValue, DateTime.MaxValue ); public TimeRange( DateTime min, DateTime max ) : base( min, max ) { } } }
22.944444
102
0.62954
[ "BSD-3-Clause" ]
bg0jr/Maui
src/Trading/Maui.Trading/Model/TimeRange.cs
415
C#
using dnsl48.SGF.Model; using dnsl48.SGF.Model.Property.Info; using dnsl48.SGF.Types; using Xunit; namespace dnsl48.SGF.Tests.Model.Property { public class BlackPlayerNameSuite { [Fact] public void TestColour() { Assert.Equal(Colour.Black, new BlackPlayerName(new SimpleText("Lee Sedol")).GetColour()); } [Fact] public void TestName() { Assert.Equal("Lee Sedol", new BlackPlayerName(new SimpleText("Lee Sedol")).GetValue().source); } [Fact] public void TestValue() { Assert.Equal("PB[Lee Sedol]", new BlackPlayerName(new SimpleText("Lee Sedol")).StringValue()); } } }
24.655172
106
0.598601
[ "Apache-2.0", "MIT" ]
dnsl48/sharp-sgf-tools
SGF.Test/src/Model/Property/BlackPlayerNameSuite.cs
715
C#
// ***************************************************************************** // // © Component Factory Pty Ltd 2017. 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 licence terms. // // Version 4.5.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Text; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections.Generic; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Implementation for the fixed mdi child pendant buttons. /// </summary> public abstract class ButtonSpecMdiChildFixed : ButtonSpec { #region Instance Fields private Form _mdiChild; #endregion #region Identity /// <summary> /// Initialize a new instance of the ButtonSpecMdiChildFixed class. /// </summary> /// <param name="fixedStyle">Fixed style to use.</param> public ButtonSpecMdiChildFixed(PaletteButtonSpecStyle fixedStyle) { // Fix the type ProtectedType = fixedStyle; } #endregion #region AllowComponent /// <summary> /// Gets a value indicating if the component is allowed to be selected at design time. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public override bool AllowComponent { get { return false; } } #endregion #region MdiChild /// <summary> /// Gets access to the owning krypton form. /// </summary> public Form MdiChild { get { return _mdiChild; } set { _mdiChild = value; } } #endregion #region ButtonSpecStype /// <summary> /// Gets and sets the actual type of the button. /// </summary> public PaletteButtonSpecStyle ButtonSpecType { get { return ProtectedType; } set { ProtectedType = value; } } #endregion #region IButtonSpecValues /// <summary> /// Gets the button style. /// </summary> /// <param name="palette">Palette to use for inheriting values.</param> /// <returns>Button style.</returns> public override ButtonStyle GetStyle(IPalette palette) { return ButtonStyle.ButtonSpec; } #endregion } }
30.728261
94
0.575875
[ "BSD-3-Clause" ]
ALMMa/Krypton
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/ButtonSpec/ButtonSpecMdiChildFixed.cs
2,830
C#
using NExpect.Interfaces; // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable MemberCanBePrivate.Global namespace NExpect.Implementations { internal class StringPropertyAnd : ExpectationContext<string>, IStringPropertyContinuation { public string Actual { get; } public IStringPropertyNot Not => ContinuationFactory.Create<string, StringPropertyNot>(Actual, this); public IStringPropertyContinuation And => ContinuationFactory.Create<string, StringPropertyAnd>(Actual, this); public IEqualityContinuation<string> Equal => ContinuationFactory.Create<string, EqualityContinuation<string>>(Actual, this); public IStringPropertyStartingContinuation Starting => ContinuationFactory.Create<string, StringPropertyContinuation>(Actual, this); public IStringPropertyEndingContinuation Ending => ContinuationFactory.Create<string, StringPropertyContinuation>(Actual, this); public StringPropertyAnd(string actual) { Actual = actual; } } }
34.272727
94
0.70557
[ "BSD-3-Clause" ]
tammylotter/NExpect
src/NExpect/Implementations/StringPropertyAnd.cs
1,131
C#
namespace TSST.NetworkNode.View { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); } } }
16.8
45
0.547619
[ "MIT" ]
atlasner/IPMPLSNetworkEmulator
TSST/TSST.NetworkNode/View/MainWindow.xaml.cs
254
C#
using System.Web; using System.Web.Mvc; namespace SecurityClaimsIntro { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
19.428571
80
0.665441
[ "MIT" ]
jespirit/bti420winter2017
Week_07/SecurityClaimsIntro/SecurityClaimsIntro/App_Start/FilterConfig.cs
274
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Telegram.Bot.Args; using Telegram.Bot.Requests.Abstractions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InlineQueryResults; using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.Payments; using Telegram.Bot.Types.ReplyMarkups; using File = Telegram.Bot.Types.File; namespace Telegram.Bot { /// <summary> /// A client interface to use the Telegram Bot API /// </summary> public interface ITelegramBotClient { /// <summary> /// Unique identifier for the bot from bot token. For example, for the bot token /// "1234567:4TT8bAc8GHUspu3ERYn-KGcvsvGB9u_n4ddy", the bot id is "1234567". /// Token format is not public API so this property is optional and may stop working /// in the future if Telegram changes it's token format. /// </summary> long? BotId { get; } #region Config Properties /// <summary> /// Timeout for requests /// </summary> TimeSpan Timeout { get; set; } /// <summary> /// Indicates if receiving updates /// </summary> [Obsolete("This property will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] bool IsReceiving { get; } /// <summary> /// The current message offset /// </summary> [Obsolete("This property will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] int MessageOffset { get; set; } #endregion Config Properties #region Events /// <summary> /// Occurs before sending a request to API /// </summary> event AsyncEventHandler<ApiRequestEventArgs> OnMakingApiRequest; /// <summary> /// Occurs after receiving the response to an API request /// </summary> event AsyncEventHandler<ApiResponseEventArgs> OnApiResponseReceived; /// <summary> /// Occurs when an <see cref="Update"/> is received. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<UpdateEventArgs> OnUpdate; /// <summary> /// Occurs when a <see cref="Message"/> is received. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<MessageEventArgs> OnMessage; /// <summary> /// Occurs when <see cref="Message"/> was edited. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<MessageEventArgs> OnMessageEdited; /// <summary> /// Occurs when an <see cref="InlineQuery"/> is received. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<InlineQueryEventArgs> OnInlineQuery; /// <summary> /// Occurs when a <see cref="ChosenInlineResult"/> is received. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<ChosenInlineResultEventArgs> OnInlineResultChosen; /// <summary> /// Occurs when an <see cref="CallbackQuery"/> is received /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<CallbackQueryEventArgs> OnCallbackQuery; /// <summary> /// Occurs when an error occurs during the background update pooling. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<ReceiveErrorEventArgs> OnReceiveError; /// <summary> /// Occurs when an error occurs during the background update pooling. /// </summary> [Obsolete("This event will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] event EventHandler<ReceiveGeneralErrorEventArgs> OnReceiveGeneralError; #endregion Events #region Helpers /// <summary> /// Send a request to Bot API /// </summary> /// <typeparam name="TResponse">Type of expected result in the response object</typeparam> /// <param name="request">API request object</param> /// <param name="cancellationToken"></param> /// <returns>Result of the API request</returns> Task<TResponse> MakeRequestAsync<TResponse>( IRequest<TResponse> request, CancellationToken cancellationToken = default); /// <summary> /// Test the API token /// </summary> /// <param name="cancellationToken"></param> /// <returns><c>true</c> if token is valid</returns> Task<bool> TestApiAsync(CancellationToken cancellationToken = default); /// <summary> /// Start update receiving /// </summary> /// <param name="allowedUpdates">List the types of updates you want your bot to receive.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="Exceptions.ApiRequestException"> Thrown if token is invalid</exception> [Obsolete("This method will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] void StartReceiving(UpdateType[] allowedUpdates = null, CancellationToken cancellationToken = default); /// <summary> /// Stop update receiving /// </summary> [Obsolete("This method will be removed in the next major version. "+ "Please consider using Telegram.Bot.Extensions.Polling instead.")] void StopReceiving(); #endregion Helpers #region Getting updates /// <summary> /// Use this method to receive incoming updates using long polling (wiki). /// </summary> /// <param name="offset"> /// Identifier of the first <see cref="Update"/> to be returned. /// Must be greater by one than the highest among the identifiers of previously received updates. /// By default, updates starting with the earliest unconfirmed update are returned. An update is considered /// confirmed as soon as <see cref="GetUpdatesAsync"/> is called with an offset higher than its <see cref="Update.Id"/>. /// The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten. /// </param> /// <param name="limit"> /// Limits the number of updates to be retrieved. Values between 1-100 are accepted. /// </param> /// <param name="timeout"> /// Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. /// </param> /// <param name="allowedUpdates"> /// List the <see cref="UpdateType"/> of updates you want your bot to receive. See <see cref="UpdateType"/> for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). /// If not specified, the previous setting will be used. /// /// Please note that this parameter doesn't affect updates created before the call to the <see cref="GetUpdatesAsync"/>, so unwanted updates may be received for a short period of time. /// </param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <remarks> /// 1. This method will not work if an outgoing webhook is set up.<para/> /// 2. In order to avoid getting duplicate updates, recalculate offset after each server response. /// <para/> /// Telegram Docs <see href="https://core.telegram.org/bots/api#getupdates"/> /// </remarks> /// <returns>An Array of <see cref="Update"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#getupdates"/> Task<Update[]> GetUpdatesAsync( int offset = default, int limit = default, int timeout = default, IEnumerable<UpdateType> allowedUpdates = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to specify a url and receive incoming updates via an outgoing webhook.<para/> /// Whenever there is an <see cref="Update"/> for the bot, we will send an HTTPS POST request to the specified url, /// containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable /// amount of attempts. /// <para/> /// If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path /// in the URL, e.g. https://www.example.com/&lt;token&gt;. Since nobody else knows your bot's token, you can be /// pretty sure it's us. /// </summary> /// <param name="url">HTTPS url to send updates to. Use an empty string to remove webhook integration</param> /// <param name="certificate"> /// Upload your public key certificate so that the root certificate in use can be checked. /// See the <see href="https://core.telegram.org/bots/self-signed">self-signed guide</see> for details. /// </param> /// <param name="ipAddress">The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS</param> /// <param name="maxConnections">Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.</param> /// <param name="allowedUpdates"> /// List the <see cref="UpdateType"/> of updates you want your bot to receive. See <see cref="UpdateType"/> for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). /// If not specified, the previous setting will be used. /// /// Please note that this parameter doesn't affect updates created before the call to the <see cref="GetUpdatesAsync"/>, so unwanted updates may be received for a short period of time. /// </param> /// <param name="dropPendingUpdates">Pass True to drop all pending updates</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c></returns> /// <remarks> /// 1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.<para/> /// 2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.<para/> /// 3. Ports currently supported for Webhooks: 443, 80, 88, 8443.<para/> /// If you're having any trouble setting up webhooks, please check out this <see href="https://core.telegram.org/bots/webhooks">amazing guide to Webhooks</see>. /// </remarks> /// <see href="https://core.telegram.org/bots/api#setwebhook"/> Task SetWebhookAsync( string url, InputFileStream certificate = default, string ipAddress = default, int maxConnections = default, IEnumerable<UpdateType> allowedUpdates = default, bool dropPendingUpdates = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to remove webhook integration if you decide to switch back to getUpdates. /// </summary> /// <param name="dropPendingUpdates">Pass True to drop all pending updates</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success</returns> /// <see href="https://core.telegram.org/bots/api#deletewebhook"/> Task DeleteWebhookAsync( bool dropPendingUpdates = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to get current webhook status. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, returns <see cref="WebhookInfo"/>.</returns> /// <see href="https://core.telegram.org/bots/api#getwebhookinfo"/> Task<WebhookInfo> GetWebhookInfoAsync(CancellationToken cancellationToken = default); #endregion Getting updates #region Available methods /// <summary> /// A simple method for testing your bot's auth token. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns basic information about the bot in form of <see cref="User"/> object</returns> /// <see href="https://core.telegram.org/bots/api#getme"/> Task<User> GetMeAsync(CancellationToken cancellationToken = default); /// <summary> /// Use this method to log out from the cloud Bot API server before launching the bot locally. /// You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. /// After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> Task LogOutAsync(CancellationToken cancellationToken = default); /// <summary> /// Use this method to close the bot instance before moving it from one local server to another. /// You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. /// The method will return error 429 in the first 10 minutes after the bot is launched /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success</returns> Task CloseAsync(CancellationToken cancellationToken = default); /// <summary> /// Use this method to send text messages. On success, the sent Description is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="text">Text of the message to be sent</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.</param> /// <param name="entities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="disableWebPagePreview">Disables link previews for links in this message</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply">Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendmessage"/> Task<Message> SendTextMessageAsync( ChatId chatId, string text, ParseMode parseMode = default, IEnumerable<MessageEntity> entities = default, bool disableWebPagePreview = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to forward messages of any kind. On success, the sent Description is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="fromChatId"><see cref="ChatId"/> for the chat where the original message was sent</param> /// <param name="messageId">Unique message identifier</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#forwardmessage"/> Task<Message> ForwardMessageAsync( ChatId chatId, ChatId fromChatId, int messageId, bool disableNotification = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to copy messages of any kind. The method is analogous to the method forwardMessages, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="fromChatId"><see cref="ChatId"/> for the chat where the original message was sent</param> /// <param name="messageId">Unique message identifier</param> /// <param name="caption">New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline</param> /// <param name="captionEntities">List of special entities that appear in the new caption, which can be specified instead of parse_mode</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns the MessageId of the sent message on success.</returns> /// <see href="https://core.telegram.org/bots/api#copymessage"/> Task<MessageId> CopyMessageAsync( ChatId chatId, ChatId fromChatId, int messageId, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, int replyToMessageId = default, bool disableNotification = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send photos. On success, the sent Description is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="photo">Photo to send.</param> /// <param name="caption">Photo caption (may also be used when resending photos by file_id).</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendphoto"/> Task<Message> SendPhotoAsync( ChatId chatId, InputOnlineFile photo, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your /// audio must be in the .mp3 format. On success, the sent Description is returned. Bots can currently send /// audio files of up to 50 MB in size, this limit may be changed in the future. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="audio">Audio file to send.</param> /// <param name="caption">Audio caption, 0-1024 characters</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline /// URLs in your bot's message.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="duration">Duration of the audio in seconds</param> /// <param name="performer">Performer</param> /// <param name="title">Track name</param> /// <param name="thumb">Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB /// in size. A thumbnail's width and height should not exceed 90. Thumbnails can't be reused and can be only /// uploaded as a new file.</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive /// notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendaudio"/> Task<Message> SendAudioAsync( ChatId chatId, InputOnlineFile audio, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, int duration = default, string performer = default, string title = default, InputMedia thumb = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send general files. On success, the sent Description is returned. Bots can send files of /// any type of up to 50 MB in size. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="document">File to send.</param> /// <param name="thumb">Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB /// in size. A thumbnail's width and height should not exceed 90. Thumbnails can't be reused and can be only /// uploaded as a new file.</param> /// <param name="caption">Document caption</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline /// URLs in your bot's message.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="disableContentTypeDetection">Disables automatic server-side content type detection for files uploaded using multipart/form-data</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive /// notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#senddocument"/> Task<Message> SendDocumentAsync( ChatId chatId, InputOnlineFile document, InputMedia thumb = default, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, bool disableContentTypeDetection = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send .webp stickers. On success, the sent Description is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="sticker">Sticker to send.</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendsticker"/> Task<Message> SendStickerAsync( ChatId chatId, InputOnlineFile sticker, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as /// Document). On success, the sent Description is returned. Bots can send video files of up to 50 MB in size. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="video">Video to send.</param> /// <param name="duration">Duration of sent video in seconds</param> /// <param name="width">Video width</param> /// <param name="height">Video height</param> /// <param name="thumb">Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB /// in size. A thumbnail's width and height should not exceed 90. Thumbnails can't be reused and can be only /// uploaded as a new file.</param> /// <param name="caption">Video caption</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline /// URLs in your bot's message.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="supportsStreaming">Pass True, if the uploaded video is suitable for streaming</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive /// notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendvideo"/> Task<Message> SendVideoAsync( ChatId chatId, InputOnlineFile video, int duration = default, int width = default, int height = default, InputMedia thumb = default, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, bool supportsStreaming = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent /// Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be /// changed in the future. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="animation">Animation to send</param> /// <param name="duration">Duration of sent animation in seconds</param> /// <param name="width">Animation width</param> /// <param name="height">Animation height</param> /// <param name="thumb">Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB /// in size. A thumbnail's width and height should not exceed 90. Thumbnails can't be reused and can be only /// uploaded as a new file.</param> /// <param name="caption">Animation caption</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline /// URLs in your bot's message.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive /// notice of cancellation.</param> /// <returns>On success, the sent Message is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendanimation"/> Task<Message> SendAnimationAsync( ChatId chatId, InputOnlineFile animation, int duration = default, int width = default, int height = default, InputMedia thumb = default, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Description is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="voice">Audio file to send.</param> /// <param name="caption">Voice message caption, 0-1024 characters</param> /// <param name="parseMode">Change, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="duration">Duration of sent audio in seconds</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendvoice"/> Task<Message> SendVoiceAsync( ChatId chatId, InputOnlineFile voice, string caption = default, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, int duration = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// As of <see href="https://telegram.org/blog/video-messages-and-telescope">v.4.0</see>, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to /// send video messages. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="videoNote">Video note to send.</param> /// <param name="duration">Duration of sent video in seconds</param> /// <param name="length">Video width and height</param> /// <param name="thumb">Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB /// in size. A thumbnail's width and height should not exceed 90. Thumbnails can't be reused and can be only /// uploaded as a new file.</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive /// notice of cancellation.</param> /// <returns>On success, the sent <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendvideonote"/> Task<Message> SendVideoNoteAsync( ChatId chatId, InputTelegramFile videoNote, int duration = default, int length = default, InputMedia thumb = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="media">A JSON-serialized array describing messages to be sent, must include 2-10 items</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, an array of the sent <see cref="Message"/>s is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendmediagroup"/> Task<Message[]> SendMediaGroupAsync( ChatId chatId, IEnumerable<IAlbumInputMedia> media, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send point on the map. On success, the sent Description is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="latitude">Latitude of location</param> /// <param name="longitude">Longitude of location</param> /// <param name="livePeriod">Period in seconds for which the location will be updated. Should be between 60 and 86400.</param> /// <param name="heading">For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.</param> /// <param name="proximityAlertRadius">For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendlocation"/> Task<Message> SendLocationAsync( ChatId chatId, float latitude, float longitude, int livePeriod = default, int heading = default, int proximityAlertRadius = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send information about a venue. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="latitude">Latitude of the venue</param> /// <param name="longitude">Longitude of the venue</param> /// <param name="title">Name of the venue</param> /// <param name="address">Address of the venue</param> /// <param name="foursquareId">Foursquare identifier of the venue</param> /// <param name="foursquareType">Foursquare type of the venue, if known. (For example, /// "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) </param> /// <param name="googlePlaceId">Google Places identifier of the venue</param> /// <param name="googlePlaceType">Google Places type of the venue /// <see href="https://developers.google.com/places/web-service/supported_types"/> /// </param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply /// keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive /// notice of cancellation.</param> /// <returns>On success, the sent <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendvenue"/> Task<Message> SendVenueAsync( ChatId chatId, float latitude, float longitude, string title, string address, string foursquareId = default, string foursquareType = default, string googlePlaceId = default, string googlePlaceType = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send phone contacts. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="phoneNumber">Contact's phone number</param> /// <param name="firstName">Contact's first name</param> /// <param name="lastName">Contact's last name</param> /// <param name="vCard">Additional data about the contact in the form of a vCard, 0-2048 bytes</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendcontact"/> Task<Message> SendContactAsync( ChatId chatId, string phoneNumber, string firstName, string lastName = default, string vCard = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent <see cref="Message"/> is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="question">Poll question, 1-300 characters</param> /// <param name="options">List of answer options, 2-10 strings 1-100 characters each</param> /// <param name="isAnonymous">True, if the poll needs to be anonymous, defaults to True</param> /// <param name="type">Poll type, “quiz” or “regular”, defaults to “regular”</param> /// <param name="allowsMultipleAnswers">True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False</param> /// <param name="correctOptionId">0-based identifier of the correct answer option, required for polls in quiz mode</param> /// <param name="explanation">Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll</param> /// <param name="explanationParseMode">Mode for parsing entities in the explanation</param> /// <param name="explanationEntities">List of special entities that appear in the poll explanation, which can be specified instead of parse_mode</param> /// <param name="openPeriod">Amount of time in seconds the poll will be active after creation</param> /// <param name="closeDate">Point in time when the poll will be automatically closed</param> /// <param name="isClosed">Pass True, if the poll needs to be immediately closed</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendpoll"/> Task<Message> SendPollAsync( ChatId chatId, string question, IEnumerable<string> options, bool? isAnonymous = default, PollType? type = default, bool? allowsMultipleAnswers = default, int? correctOptionId = default, string explanation = default, ParseMode explanationParseMode = default, IEnumerable<MessageEntity> explanationEntities = default, int? openPeriod = default, DateTime? closeDate = default, bool? isClosed = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this request to send a dice, which will have a random value from 1 to 6. On success, the sent <see cref="Message"/> is returned /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="emoji">Emoji on which the dice throw animation is based</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#senddice"/> Task<Message> SendDiceAsync( ChatId chatId, Emoji? emoji = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, IReplyMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="chatAction">Type of action to broadcast. Choose one, depending on what the user is about to receive.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <remarks>We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.</remarks> /// <see href="https://core.telegram.org/bots/api#sendchataction"/> Task SendChatActionAsync( ChatId chatId, ChatAction chatAction, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. /// </summary> /// <param name="userId">Unique identifier of the target user</param> /// <param name="offset">Sequential number of the first photo to be returned. By default, all photos are returned.</param> /// <param name="limit">Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns a <see cref="UserProfilePhotos"/> object</returns> /// <see href="https://core.telegram.org/bots/api#getuserprofilephotos"/> Task<UserProfilePhotos> GetUserProfilePhotosAsync( long userId, int offset = default, int limit = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get information about a file. For the moment, bots can download files of up to 20MB in size. /// </summary> /// <param name="fileId">File identifier</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The File object</returns> /// <see href="https://core.telegram.org/bots/api#getfile"/> Task<File> GetFileAsync( string fileId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to download a file. Get <paramref name="filePath"/> by calling <see cref="GetFileAsync"/> /// </summary> /// <param name="filePath">Path to file on server</param> /// <param name="destination">Destination stream to write file to</param> /// <param name="cancellationToken">The cancellation token to cancel operation</param> /// <exception cref="ArgumentException">filePath is <c>null</c>, empty or too short</exception> /// <exception cref="ArgumentNullException"><paramref name="destination"/> is <c>null</c></exception> Task DownloadFileAsync( string filePath, Stream destination, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get basic info about a file and download it. /// </summary> /// <param name="fileId">File identifier to get info about</param> /// <param name="destination">Destination stream to write file to</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>File info</returns> Task<File> GetInfoAndDownloadFileAsync( string fileId, Stream destination, CancellationToken cancellationToken = default); /// <summary> /// Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the group for this to work. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target group</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="untilDate"><see cref="DateTime"/> when the user will be unbanned. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever</param> /// <param name="revokeMessages">Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#kickchatmember"/> Task KickChatMemberAsync( ChatId chatId, long userId, DateTime untilDate = default, bool? revokeMessages = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method for your bot to leave a group, supergroup or channel. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns a Chat object on success.</returns> /// <see href="https://core.telegram.org/bots/api#leavechat"/> Task LeaveChatAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target group</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="onlyIfBanned">Do nothing if the user is not banned</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#unbanchatmember"/> Task UnbanChatMemberAsync( ChatId chatId, long userId, bool onlyIfBanned = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns a Chat object on success.</returns> /// <see href="https://core.telegram.org/bots/api#getchat"/> Task<Chat> GetChatAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get a list of administrators in a chat. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, returns an Array of <see cref="ChatMember"/> objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.</returns> /// <see href="https://core.telegram.org/bots/api#getchatadministrators"/> Task<ChatMember[]> GetChatAdministratorsAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get the number of members in a chat. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns Int on success.</returns> /// <see href="https://core.telegram.org/bots/api#getchatmemberscount"/> Task<int> GetChatMembersCountAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get information about a member of a chat. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns a ChatMember object on success.</returns> /// <see href="https://core.telegram.org/bots/api#getchatmember"/> Task<ChatMember> GetChatMemberAsync( ChatId chatId, long userId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. /// </summary> /// <param name="callbackQueryId">Unique identifier for the query to be answered</param> /// <param name="text">Text of the notification. If not specified, nothing will be shown to the user</param> /// <param name="showAlert">If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.</param> /// <param name="url"> /// URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game — note that this will only work if the query comes from a callback_game button. /// Otherwise, you may use links like telegram.me/your_bot? start = XXXX that open your bot with a parameter. /// </param> /// <param name="cacheTime">The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, <c>true</c> is returned.</returns> /// <remarks> /// Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via BotFather and accept the terms. /// Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter. /// </remarks> /// <see href="https://core.telegram.org/bots/api#answercallbackquery"/> Task AnswerCallbackQueryAsync( string callbackQueryId, string text = default, bool showAlert = default, string url = default, int cacheTime = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="permissions">New user permissions</param> /// <param name="untilDate"><see cref="DateTime"/> when restrictions will be lifted for the user. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, <c>true</c> is returned</returns> /// <remarks>Pass True for all boolean parameters to lift restrictions from a user.</remarks> /// <see href="https://core.telegram.org/bots/api#restrictchatmember"/> Task RestrictChatMemberAsync( ChatId chatId, long userId, ChatPermissions permissions, DateTime untilDate = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="isAnonymous">Pass True, if the administrator's presence in the chat is hidden</param> /// <param name="canManageChat">Pass True, if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege</param> /// <param name="canChangeInfo">Pass True, if the administrator can change chat title, photo and other settings</param> /// <param name="canPostMessages">Pass True, if the administrator can create channel posts, channels only</param> /// <param name="canEditMessages">Pass True, if the administrator can edit messages of other users, channels only</param> /// <param name="canDeleteMessages">Pass True, if the administrator can delete messages of other users</param> /// <param name="canManageVoiceChats">Pass True, if the administrator can manage voice chats, supergroups only</param> /// <param name="canInviteUsers">Pass True, if the administrator can invite new users to the chat</param> /// <param name="canRestrictMembers">Pass True, if the administrator can restrict, ban or unban chat members</param> /// <param name="canPinMessages">Pass True, if the administrator can pin messages, supergroups only</param> /// <param name="canPromoteMembers">Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> /// <remarks>Pass False for all boolean parameters to demote a user.</remarks> /// <see href="https://core.telegram.org/bots/api#promotechatmember"/> Task PromoteChatMemberAsync( ChatId chatId, long userId, bool? isAnonymous = default, bool? canManageChat = default, bool? canChangeInfo = default, bool? canPostMessages = default, bool? canEditMessages = default, bool? canDeleteMessages = default, bool? canManageVoiceChats = default, bool? canInviteUsers = default, bool? canRestrictMembers = default, bool? canPinMessages = default, bool? canPromoteMembers = default, CancellationToken cancellationToken = default ); /// <summary> /// <inheritdoc cref="Telegram.Bot.Requests.SetChatAdministratorCustomTitleRequest"/> /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="customTitle">New custom title for the administrator; 0-16 characters, emoji are not allowed</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> /// <see href="https://core.telegram.org/bots/api#setchatadministratorcustomtitle"/> Task SetChatAdministratorCustomTitleAsync( ChatId chatId, long userId, string customTitle, CancellationToken cancellationToken = default); /// <summary> /// Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights. Returns True on success. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="permissions">New default permissions</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> Task SetChatPermissionsAsync( ChatId chatId, ChatPermissions permissions, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get the current list of the bot's commands /// </summary> /// <param name="cancellationToken"></param> /// <returns>Array of <see cref="BotCommand"/> on success.</returns> /// <see href="https://core.telegram.org/bots/api#getmycommands"/> Task<BotCommand[]> GetMyCommandsAsync(CancellationToken cancellationToken = default); /// <summary> /// Use this method to change the list of the bot's commands. Returns True on success. /// </summary> /// <param name="commands">A list of bot commands to be set</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#setmycommands"/> Task SetMyCommandsAsync( IEnumerable<BotCommand> commands, CancellationToken cancellationToken = default); #endregion Available methods #region Updating messages /// <summary> /// Use this method to edit text messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Unique identifier of the sent message</param> /// <param name="text">New text of the message</param> /// <param name="parseMode">Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.</param> /// <param name="entities">List of special entities that appear in message text, which can be specified instead of parseMode</param> /// <param name="disableWebPagePreview">Disables link previews for links in this message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the edited Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagetext"/> Task<Message> EditMessageTextAsync( ChatId chatId, int messageId, string text, ParseMode parseMode = default, IEnumerable<MessageEntity> entities = default, bool disableWebPagePreview = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to edit text messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="inlineMessageId">Identifier of the inline message</param> /// <param name="text">New text of the message</param> /// <param name="parseMode">Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.</param> /// <param name="entities">List of special entities that appear in message text, which can be specified instead of parseMode</param> /// <param name="disableWebPagePreview">Disables link previews for links in this message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagetext"/> Task EditMessageTextAsync( string inlineMessageId, string text, ParseMode parseMode = default, IEnumerable<MessageEntity> entities = default, bool disableWebPagePreview = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to stop updating a live location message sent by the bot before live_period expires. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Unique identifier of the sent message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success the sent <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#stopmessagelivelocation"/> Task<Message> StopMessageLiveLocationAsync( ChatId chatId, int messageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to stop updating a live location message sent via the bot (for inline bots) before live_period expires. /// </summary> /// <param name="inlineMessageId">Identifier of the inline message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#stopmessagelivelocation"/> Task StopMessageLiveLocationAsync( string inlineMessageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Unique identifier of the sent message</param> /// <param name="caption">New caption of the message</param> /// <param name="parseMode">Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the edited Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagecaption"/> Task<Message> EditMessageCaptionAsync( ChatId chatId, int messageId, string caption, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="inlineMessageId">Unique identifier of the sent message</param> /// <param name="caption">New caption of the message</param> /// <param name="parseMode">Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.</param> /// <param name="captionEntities">List of special entities that appear in the caption, which can be specified instead of parse_mode</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the edited Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagecaption"/> Task EditMessageCaptionAsync( string inlineMessageId, string caption, ParseMode parseMode = default, IEnumerable<MessageEntity> captionEntities = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to edit audio, document, photo, or video messages. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Unique identifier of the sent message</param> /// <param name="media">A JSON-serialized object for a new media content of the message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success the edited <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagemedia"/> Task<Message> EditMessageMediaAsync( ChatId chatId, int messageId, InputMediaBase media, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to edit audio, document, photo, or video inline messages. /// </summary> /// <param name="inlineMessageId">Unique identifier of the sent message</param> /// <param name="media">A JSON-serialized object for a new media content of the message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagemedia"/> Task EditMessageMediaAsync( string inlineMessageId, InputMediaBase media, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Unique identifier of the sent message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the edited Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagereplymarkup"/> Task<Message> EditMessageReplyMarkupAsync( ChatId chatId, int messageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="inlineMessageId">Unique identifier of the sent message</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagereplymarkup"/> Task EditMessageReplyMarkupAsync( string inlineMessageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to edit live location messages sent by the bot. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Unique identifier of the sent message</param> /// <param name="latitude">Latitude of location</param> /// <param name="longitude">Longitude of location</param> /// <param name="horizontalAccuracy">The radius of uncertainty for the location, measured in meters; 0-1500</param> /// <param name="heading">Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.</param> /// <param name="proximityAlertRadius">Maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success the edited <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagelivelocation"/> Task<Message> EditMessageLiveLocationAsync( ChatId chatId, int messageId, float latitude, float longitude, float horizontalAccuracy = default, int heading = default, int proximityAlertRadius = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to edit live location messages sent via the bot (for inline bots). /// </summary> /// <param name="inlineMessageId">Unique identifier of the sent message</param> /// <param name="latitude">Latitude of location</param> /// <param name="longitude">Longitude of location</param> /// <param name="horizontalAccuracy">The radius of uncertainty for the location, measured in meters; 0-1500</param> /// <param name="heading">Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.</param> /// <param name="proximityAlertRadius">Maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#editmessagelivelocation"/> Task EditMessageLiveLocationAsync( string inlineMessageId, float latitude, float longitude, float horizontalAccuracy = default, int heading = default, int proximityAlertRadius = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent <see cref="Message"/> is returned. /// </summary> /// <param name="chatId"><see cref="ChatId"/> for the target chat</param> /// <param name="messageId">Identifier of the original message with the poll</param> /// <param name="replyMarkup">A JSON-serialized object for a new message inline keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the stopped <see cref="Poll"/> with the final results is returned.</returns> /// <see href="https://core.telegram.org/bots/api#stoppoll"/> Task<Poll> StopPollAsync( ChatId chatId, int messageId, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such recently sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator in a supergroup, it can delete messages from any other user and service messages about people joining or leaving the group (other types of service messages may only be removed by the group creator). In channels, bots can only remove their own messages. /// </summary> /// <param name="chatId"><see cref="ChatId"/> Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="messageId">Unique identifier of the message to delete</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns><c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#deletemessage"/> Task DeleteMessageAsync( ChatId chatId, int messageId, CancellationToken cancellationToken = default); #endregion Updating messages #region Inline mode /// <summary> /// Use this method to send answers to an inline query. /// </summary> /// <param name="inlineQueryId">Unique identifier for answered query</param> /// <param name="results">A array of results for the inline query</param> /// <param name="cacheTime">The maximum amount of time in seconds the result of the inline query may be cached on the server</param> /// <param name="isPersonal">Pass <c>true</c>, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query</param> /// <param name="nextOffset">Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes.</param> /// <param name="switchPmText">If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter</param> /// <param name="switchPmParameter">Parameter for the start message sent to the bot when user presses the switch button</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, <c>true</c> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#answerinlinequery"/> Task AnswerInlineQueryAsync( string inlineQueryId, IEnumerable<InlineQueryResultBase> results, int? cacheTime = default, bool isPersonal = default, string nextOffset = default, string switchPmText = default, string switchPmParameter = default, CancellationToken cancellationToken = default); #endregion Inline mode #region Payments /// <summary> /// Use this method to send invoices. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="title">Product name, 1-32 characters</param> /// <param name="description">Product description, 1-255 characters</param> /// <param name="payload">Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.</param> /// <param name="providerToken">Payments provider token, obtained via BotFather</param> /// <param name="currency">Three-letter ISO 4217 currency code, see <see href="https://core.telegram.org/bots/payments#supported-currencies">more on currencies</see></param> /// <param name="prices">Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)</param> /// <param name="maxTipAmount">The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass maxTipAmount = 145. See the exp parameter in <see href="https://core.telegram.org/bots/payments/currencies.json">currencies.json</see>, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0</param> /// <param name="suggestedTipAmounts">Array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed maxTipAmount.</param> /// <param name="startParameter">Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter</param> /// <param name="providerData">A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider</param> /// <param name="photoUrl">URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for</param> /// <param name="photoSize">Photo size</param> /// <param name="photoWidth">Photo width</param> /// <param name="photoHeight">Photo height</param> /// <param name="needName">Pass True, if you require the user's full name to complete the order</param> /// <param name="needPhoneNumber">Pass True, if you require the user's phone number to complete the order</param> /// <param name="needEmail">Pass True, if you require the user's email to complete the order</param> /// <param name="needShippingAddress">Pass True, if you require the user's shipping address to complete the order</param> /// <param name="sendPhoneNumberToProvider">Pass True, if user's phone number should be sent to provider</param> /// <param name="sendEmailToProvider">Pass True, if user's email address should be sent to provider</param> /// <param name="isFlexible">Pass True, if the final price depends on the shipping method</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply">Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent <see cref="Message"/> is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendinvoice"/> Task<Message> SendInvoiceAsync( long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable<LabeledPrice> prices, int maxTipAmount = default, int[] suggestedTipAmounts = default, string startParameter = default, string providerData = default, string photoUrl = default, int photoSize = default, int photoWidth = default, int photoHeight = default, bool needName = default, bool needPhoneNumber = default, bool needEmail = default, bool needShippingAddress = default, bool sendPhoneNumberToProvider = default, bool sendEmailToProvider = default, bool isFlexible = default, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to reply to shipping queries with success and shipping options. If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. /// </summary> /// <param name="shippingQueryId">Unique identifier for the query to be answered</param> /// <param name="shippingOptions">Required if OK is True.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, True is returned.</returns> /// <see href="https://core.telegram.org/bots/api#answershippingquery"/> Task AnswerShippingQueryAsync( string shippingQueryId, IEnumerable<ShippingOption> shippingOptions, CancellationToken cancellationToken = default); /// <summary> /// Use this method to reply to shipping queries with failure and error message. If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. /// </summary> /// <param name="shippingQueryId">Unique identifier for the query to be answered</param> /// <param name="errorMessage">Required if OK is False. Error message in human readable form that explains why it is impossible to complete the order </param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, True is returned.</returns> /// <see href="https://core.telegram.org/bots/api#answershippingquery"/> Task AnswerShippingQueryAsync( string shippingQueryId, string errorMessage, CancellationToken cancellationToken = default); /// <summary> /// Respond to a pre-checkout query with success /// </summary> /// <param name="preCheckoutQueryId">Unique identifier for the query to be answered</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, True is returned.</returns> /// <remarks>Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.</remarks> /// <see href="https://core.telegram.org/bots/api#answerprecheckoutquery"/> Task AnswerPreCheckoutQueryAsync( string preCheckoutQueryId, CancellationToken cancellationToken = default); /// <summary> /// Respond to a pre-checkout query with failure and error message /// </summary> /// <param name="preCheckoutQueryId">Unique identifier for the query to be answered</param> /// <param name="errorMessage">Required if OK is False. Error message in human readable form that explains the reason for failure to proceed with the checkout</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, True is returned.</returns> /// <remarks>Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.</remarks> /// <see href="https://core.telegram.org/bots/api#answerprecheckoutquery"/> Task AnswerPreCheckoutQueryAsync( string preCheckoutQueryId, string errorMessage, CancellationToken cancellationToken = default); #endregion Payments #region Games /// <summary> /// Use this method to send a game. /// </summary> /// <param name="chatId">Unique identifier of the target chat</param> /// <param name="gameShortName">Short name of the game, serves as the unique identifier for the game.</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message</param> /// <param name="allowSendingWithoutReply"> Pass True, if the message should be sent even if the specified replied-to message is not found</param> /// <param name="replyMarkup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, the sent Description is returned.</returns> /// <see href="https://core.telegram.org/bots/api#sendgame"/> Task<Message> SendGameAsync( long chatId, string gameShortName, bool disableNotification = default, int replyToMessageId = default, bool allowSendingWithoutReply = default, InlineKeyboardMarkup replyMarkup = default, CancellationToken cancellationToken = default ); /// <summary> /// Use this method to set the score of the specified user in a game. /// </summary> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="score">The score.</param> /// <param name="chatId">Unique identifier of the target chat.</param> /// <param name="messageId">Unique identifier of the sent message.</param> /// <param name="force">Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters</param> /// <param name="disableEditMessage">Pass True, if the game message should not be automatically edited to include the current scoreboard</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, if the message was sent by the bot, returns the edited <see cref="Message"/></returns> /// <see href="https://core.telegram.org/bots/api#setgamescore"/> Task<Message> SetGameScoreAsync( long userId, int score, long chatId, int messageId, bool force = default, bool disableEditMessage = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to set the score of the specified user in a game. /// </summary> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="score">The score.</param> /// <param name="inlineMessageId">Identifier of the inline message.</param> /// <param name="force">Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters</param> /// <param name="disableEditMessage">Pass True, if the game message should not be automatically edited to include the current scoreboard</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success returns True</returns> /// <see href="https://core.telegram.org/bots/api#setgamescore"/> Task SetGameScoreAsync( long userId, int score, string inlineMessageId, bool force = default, bool disableEditMessage = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get data for high score tables. /// </summary> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="chatId">Unique identifier of the target chat.</param> /// <param name="messageId">Unique identifier of the sent message.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, returns an Array of <see cref="GameHighScore"/> objects</returns> /// <remarks> /// This method will currently return scores for the target user, plus two of his closest neighbors on each side. /// Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. /// </remarks> /// <see href="https://core.telegram.org/bots/api#getgamehighscores"/> Task<GameHighScore[]> GetGameHighScoresAsync( long userId, long chatId, int messageId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to get data for high score tables. /// </summary> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="inlineMessageId">Unique identifier of the inline message.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, returns an Array of <see cref="GameHighScore"/> objects</returns> /// <remarks> /// This method will currently return scores for the target user, plus two of his closest neighbors on each side. /// Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. /// </remarks> /// <see href="https://core.telegram.org/bots/api#getgamehighscores"/> Task<GameHighScore[]> GetGameHighScoresAsync( long userId, string inlineMessageId, CancellationToken cancellationToken = default); #endregion Games #region Stickers /// <summary> /// Use this method to get a sticker set. /// </summary> /// <param name="name">Short name of the sticker set that is used in t.me/addstickers/ URLs (e.g., animals)</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>On success, a StickerSet object is returned.</returns> /// <see href="https://core.telegram.org/bots/api#getstickerset"/> Task<StickerSet> GetStickerSetAsync( string name, CancellationToken cancellationToken = default); /// <summary> /// Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). /// </summary> /// <param name="userId">User identifier of sticker file owner</param> /// <param name="pngSticker">Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns the uploaded File on success.</returns> /// <see href="https://core.telegram.org/bots/api#uploadstickerfile"/> Task<File> UploadStickerFileAsync( long userId, InputFileStream pngSticker, CancellationToken cancellationToken = default); /// <summary> /// Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. /// </summary> /// <param name="userId">User identifier of created sticker set owner</param> /// <param name="name">Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_&lt;bot_username&gt;”. &lt;bot_username&gt; is case insensitive. 1-64 characters.</param> /// <param name="title">Sticker set title, 1-64 characters</param> /// <param name="pngSticker">Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.</param> /// <param name="emojis">One or more emoji corresponding to the sticker</param> /// <param name="isMasks">Pass True, if a set of mask stickers should be created</param> /// <param name="maskPosition">Position where the mask should be placed on faces</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> /// <see href="https://core.telegram.org/bots/api#createnewstickerset"/> Task CreateNewStickerSetAsync( long userId, string name, string title, InputOnlineFile pngSticker, string emojis, bool isMasks = default, MaskPosition maskPosition = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to add a new sticker to a set created by the bot. /// </summary> /// <param name="userId">User identifier of sticker set owner</param> /// <param name="name">Sticker set name</param> /// <param name="pngSticker">Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.</param> /// <param name="emojis">One or more emoji corresponding to the sticker</param> /// <param name="maskPosition">Position where the mask should be placed on faces</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>True on success</returns> /// <see href="https://core.telegram.org/bots/api#addstickertoset"/> Task AddStickerToSetAsync( long userId, string name, InputOnlineFile pngSticker, string emojis, MaskPosition maskPosition = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. /// </summary> /// <param name="userId">User identifier of created sticker set owner</param> /// <param name="name">Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_&lt;bot_username&gt;”. &lt;bot_username&gt; is case insensitive. 1-64 characters.</param> /// <param name="title">Sticker set title, 1-64 characters</param> /// <param name="tgsSticker">Tgs animation with the sticker</param> /// <param name="emojis">One or more emoji corresponding to the sticker</param> /// <param name="isMasks">Pass True, if a set of mask stickers should be created</param> /// <param name="maskPosition">Position where the mask should be placed on faces</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> /// <see href="https://core.telegram.org/bots/api#createnewstickerset"/> Task CreateNewAnimatedStickerSetAsync( long userId, string name, string title, InputFileStream tgsSticker, string emojis, bool isMasks = default, MaskPosition maskPosition = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to add a new sticker to a set created by the bot. /// </summary> /// <param name="userId">User identifier of sticker set owner</param> /// <param name="name">Sticker set name</param> /// <param name="tgsSticker">Tgs animation with the sticker</param> /// <param name="emojis">One or more emoji corresponding to the sticker</param> /// <param name="maskPosition">Position where the mask should be placed on faces</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>True on success</returns> /// <see href="https://core.telegram.org/bots/api#addstickertoset"/> Task AddAnimatedStickerToSetAsync( long userId, string name, InputFileStream tgsSticker, string emojis, MaskPosition maskPosition = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to move a sticker in a set created by the bot to a specific position. /// </summary> /// <param name="sticker">File identifier of the sticker</param> /// <param name="position">New sticker position in the set, zero-based</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>True on success</returns> /// <see href="https://core.telegram.org/bots/api#setstickerpositioninset"/> Task SetStickerPositionInSetAsync( string sticker, int position, CancellationToken cancellationToken = default); /// <summary> /// Use this method to delete a sticker from a set created by the bot. /// </summary> /// <param name="sticker">File identifier of the sticker</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> /// <see href="https://core.telegram.org/bots/api#deletestickerfromset"/> Task DeleteStickerFromSetAsync( string sticker, CancellationToken cancellationToken = default); /// <summary> /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// </summary> /// <param name="name">Sticker set name</param> /// <param name="userId">User identifier of the sticker set owner</param> /// <param name="thumb">A PNG image or a TGS animation with the thumbnail</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success.</returns> /// <see href="https://core.telegram.org/bots/api#setstickersetthumb"/> Task SetStickerSetThumbAsync( string name, long userId, InputOnlineFile thumb = default, CancellationToken cancellationToken = default); #endregion #region Group and channel management /// <summary> /// Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns exported invite link as String on success.</returns> /// <see href="https://core.telegram.org/bots/api#exportchatinvitelink"/> Task<string> ExportChatInviteLinkAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="photo">The new profile picture for the chat.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns <c>true</c> on success.</returns> /// <see href="https://core.telegram.org/bots/api#setchatphoto"/> Task SetChatPhotoAsync( ChatId chatId, InputFileStream photo, CancellationToken cancellationToken = default); /// <summary> /// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success.</returns> /// <see href="https://core.telegram.org/bots/api#deletechatphoto"/> Task DeleteChatPhotoAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="title">New chat title, 1-255 characters</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success.</returns> /// <see href="https://core.telegram.org/bots/api#setchattitle"/> Task SetChatTitleAsync( ChatId chatId, string title, CancellationToken cancellationToken = default); /// <summary> /// Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel</param> /// <param name="description">New chat description, 0-255 characters. Defaults to an empty string, which would clear the description.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success.</returns> /// <see href="https://core.telegram.org/bots/api#setchatdescription"/> Task SetChatDescriptionAsync( ChatId chatId, string description = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup</param> /// <param name="messageId">Identifier of a message to pin</param> /// <param name="disableNotification">Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success.</returns> /// <see href="https://core.telegram.org/bots/api#pinchatmessage"/> Task PinChatMessageAsync( ChatId chatId, int messageId, bool disableNotification = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin right in a channel. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup</param> /// <param name="messageId">Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success</returns> /// <see href="https://core.telegram.org/bots/api#unpinchatmessage"/> Task UnpinChatMessageAsync(ChatId chatId, int messageId = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin right in a channel. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns True on success</returns> /// <see href="https://core.telegram.org/bots/api#unpinallchatmessages"/> Task UnpinAllChatMessages(ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to set a new group sticker set for a supergroup. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)</param> /// <param name="stickerSetName">Name of the sticker set to be set as the group sticker set</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success</returns> /// <see href="https://core.telegram.org/bots/api#setchatstickerset"/> Task SetChatStickerSetAsync( ChatId chatId, string stickerSetName, CancellationToken cancellationToken = default); /// <summary> /// Use this method to delete a group sticker set from a supergroup. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true on success</returns> /// <see href="https://core.telegram.org/bots/api#deletechatstickerset"/> Task DeleteChatStickerSetAsync( ChatId chatId, CancellationToken cancellationToken = default); /// <summary> /// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method <see cref="RevokeChatInviteLinkAsync"/>. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="expireDate">DateTime when the link will expire</param> /// <param name="memberLimit">Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation</param> /// <returns>Returns the new invite link as <see cref="ChatInviteLink"/> object</returns> Task<ChatInviteLink> CreateChatInviteLinkAsync( ChatId chatId, DateTime? expireDate = default, int? memberLimit = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="inviteLink">The invite link to edit</param> /// <param name="expireDate">DateTime when the link will expire</param> /// <param name="memberLimit">Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation</param> /// <returns>Returns the edited invite link as <see cref="ChatInviteLink"/> object</returns> Task<ChatInviteLink> EditChatInviteLinkAsync( ChatId chatId, string inviteLink, DateTime? expireDate = default, int? memberLimit = default, CancellationToken cancellationToken = default); /// <summary> /// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights /// </summary> /// <param name="chatId">Unique identifier of the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="inviteLink">The invite link to revoke</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation</param> /// <returns>Returns the revoked invite link as <see cref="ChatInviteLink"/> object</returns> Task<ChatInviteLink> RevokeChatInviteLinkAsync( ChatId chatId, string inviteLink, CancellationToken cancellationToken = default); #endregion } }
67.497684
546
0.663769
[ "MIT" ]
NA-002/NT7TelegramBot
src/Telegram.Bot/ITelegramBotClient.cs
131,170
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; using Abp.Authorization.Users; using Abp.AutoMapper; using ImproveX.Authorization.Users; namespace ImproveX.Users.Dto { [AutoMapTo(typeof(User))] public class CreateUserDto { [Required] [StringLength(AbpUserBase.MaxUserNameLength)] public string UserName { get; set; } [Required] [StringLength(AbpUserBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxSurnameLength)] public string Surname { get; set; } [Required] [EmailAddress] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string EmailAddress { get; set; } public bool IsActive { get; set; } public string[] RoleNames { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } } }
26.315789
58
0.65
[ "MIT" ]
zchhaenngg/IWI
src/ImproveX.Application/Users/Dto/CreateUserDto.cs
1,002
C#
using Abp.Domain.Entities; using System; using System.Collections.Generic; using System.Text; namespace ABPsinglePageProj1.Entities { public class Department:Entity<Guid> { public string Name { get; set; } public string Description { get; set; } public string EstablishDate { get; set; } public virtual ICollection<Employee> Employees { get; set; } } }
24.875
68
0.683417
[ "MIT" ]
Heba-Ahmed-Magdy/ABPSPProj1
aspnet-core/src/ABPsinglePageProj1.Core/Entities/Department.cs
400
C#
using System; using System.Threading.Tasks; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Serilog; namespace AppInsightsTest { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "AppInsightsTest", Version = "v1" }); }); services.AddMemoryCache(); services.AddSingleton<IRandomNumberProvider, RandomNumberProvider>(); services.AddHealthChecks() .AddCheck<DependencyAvailableHealthCheck>( "DependencyHealthCheck", HealthStatus.Unhealthy, new [] {"liveness"}); services.Configure<HealthCheckPublisherOptions>(opts => { opts.Delay = TimeSpan.FromSeconds(10); opts.Predicate = check => check.Tags.Contains("liveness"); opts.Period = TimeSpan.FromSeconds(30); }); // TODO: Step 2 - Call AddApplicationInsightsTelemetry() extension method to register the // appropriate middleware so that hooks will all be in place to enable application monitoring. services.AddApplicationInsightsTelemetry(opts => { // None of these options are necessary; the defaults are very reasonable. opts.EnableAdaptiveSampling = true; // enabled by default opts.EnableHeartbeat = true; // default is not documented opts.DeveloperMode = GetAppInsightsDeveloperMode(); // useful to stream logs/events instead of batch opts.EnablePerformanceCounterCollectionModule = true; // enabled by default on Windows opts.EnableEventCounterCollectionModule = true; // enabled by default for NetStandard 2+ }); // TODO: Step 3 - Add ApplicationInsights section to your application settings (appsettings.json) // because we didn't specify an instrumentation key or connection string when enabling the // telemetry as specified above. // TODO: Step 4 - We can track a dependency that's not already tracked by manually using the // telemetry client and adding a custom metric. I prefer a decorator approach for this. // We would typically have something like the following: // // services.AddSingleton<IRandomNumberProvider, RandomNumberProvider>(); // // Instead, we will register a decorated version whose primary responsibility is to track the // calls made to the dependency: services.AddSingleton<IRandomNumberProvider>(provider => new DependencyTrackingRandomNumberProvider( new RandomNumberProvider(provider.GetRequiredService<TelemetryClient>()), provider.GetRequiredService<TelemetryClient>() )); // TODO: Step 6 - Enable a telemetry initializer so we can customize what is being sent as telemetry services.AddSingleton<ITelemetryInitializer, ThreadDetailsRequestMessageTelemetryInitializer>(); // TODO: Step 7 - Publish the health check results to Application Insights as availability metrics services.AddSingleton<IHealthCheckPublisher, AppInsightsHealthCheckResultsPublisher>(); // TODO: Step 9 - Enable the Application Insights Profiler. This will result in the stack sampler // kicking in based on the profiler configuration settings. services.AddServiceProfiler(cfg => { cfg.IsDisabled = false; cfg.CPUTriggerThreshold = 70; cfg.Duration = TimeSpan.FromSeconds(30); }); // TODO: Step 11 - Enable the Snapshot Debugger so that we have information about exceptions that // are thrown within the application. No options are required if the defaults are agreeable. // TODO: Step 12 - Add "Application Insights Snapshot Debugger" Role to user(s) that will need // to access the Debug Snapshots within Application Insights. services.AddSnapshotCollector(cfg => { cfg.IsEnabled = true; cfg.IsEnabledWhenProfiling = true; cfg.IsEnabledInDeveloperMode = true; cfg.SnapshotsPerTenMinutesLimit = 10; }); // TODO: Step 14 - Secure Live Metrics control plane by using authenticated API calls // by: // 1. Creating a new API key in the Azure Portal for Application Insights. // 2. Configuring the QuickPulseTelemetryModule (live metrics view) to use an API key services.ConfigureTelemetryModule<QuickPulseTelemetryModule>((module, opts) => { module.AuthenticationApiKey = "pybmwdbwoic4ontzobzfd1knsb0hsy0nukg0bpik"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AppInsightsTest v1")); } app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandler = OnException }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/healthz"); }); } private Task OnException(HttpContext context) { var errorContext = context.Features.Get<IExceptionHandlerPathFeature>(); Log.Logger.Error( errorContext.Error, "An unhandled exception occurred at {path}: {errorMessage}", errorContext.Path, errorContext.Error.Message); return Task.CompletedTask; } private static bool? GetAppInsightsDeveloperMode() { #if DEBUG return true; #else return false; #endif } } }
45.736196
120
0.617572
[ "Apache-2.0" ]
kalebpederson/AppInsightsTest
AppInsightsTest/Startup.cs
7,455
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Aspose.Cells.Charts; namespace Aspose.Cells.Examples.CSharp.Articles { public class FindDataPointsInPieBar { public static void Run() { // ExStart:FindDataPointsInPieBar // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Load source excel file containing Bar of Pie chart Workbook wb = new Workbook(dataDir + "PieBars.xlsx"); // Access first worksheet Worksheet ws = wb.Worksheets[0]; // Access first chart which is Bar of Pie chart and calculate it Chart ch = ws.Charts[0]; ch.Calculate(); // Access the chart series Series srs = ch.NSeries[0]; /* * Print the data points of the chart series and * check its IsInSecondaryPlot property to determine * if data point is inside the bar or pie */ for (int i = 0; i < srs.Points.Count; i++) { //Access chart point ChartPoint cp = srs.Points[i]; //Skip null values if (cp.YValue == null) continue; /* * Print the chart point value and see if it is inside bar or pie. * If the IsInSecondaryPlot is true, then the data point is inside bar * otherwise it is inside the pie. */ Console.WriteLine("Value: " + cp.YValue); Console.WriteLine("IsInSecondaryPlot: " + cp.IsInSecondaryPlot); Console.WriteLine(); } // ExEnd:FindDataPointsInPieBar } } }
33.210526
115
0.547808
[ "MIT" ]
Aspose/Aspose.Cells-for-.NET
Examples/CSharp/Articles/FindDataPointsInPieBar.cs
1,895
C#
using Codeable.Foundation.Common; using Codeable.Foundation.Common.Aspect; using Codeable.Foundation.Common.Daemons; using Codeable.Foundation.Core.Caching; using Codeable.Foundation.Core.Unity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Stencil.Common.Configuration; using Stencil.Common; using Stencil.Domain; namespace Stencil.Primary.Health.Daemons { public class HealthReportDaemon : ChokeableClass, IDaemonTask { public HealthReportDaemon(IFoundation iFoundation) : base(iFoundation) { } #region IDaemonTask Members public const string DAEMON_NAME = "HealthReportDaemon"; protected static bool _executing; public string DaemonName { get { return DAEMON_NAME; } protected set { } } public void Execute(Codeable.Foundation.Common.IFoundation iFoundation) { base.ExecuteMethod("Execute", delegate() { if (_executing) { return; } // safety try { _executing = true; this.PersistHealth(); } finally { _executing = false; } }); } public DaemonSynchronizationPolicy SynchronizationPolicy { get { return DaemonSynchronizationPolicy.SingleAppDomain; } } #endregion protected void PersistHealth() { base.ExecuteMethod("PersistHealth", delegate() { base.IFoundation.LogWarning("Sending Health Reports"); string hostName = Dns.GetHostName(); Dictionary<string, decimal> metrics = null; List<string> logs = null; HealthReporter.Current.ResetMetrics(out metrics, out logs); string suffix = DateTime.UtcNow.ToUnixSecondsUTC().ToString(); foreach (var item in metrics) { logs.Add(string.Format("{0}.{1} {2} {3}", hostName, item.Key, (int)item.Value, suffix)); } ISettingsResolver settingsResolver = this.IFoundation.Resolve<ISettingsResolver>(); if (!settingsResolver.IsLocalHost()) { string apiKey = this.ApiKey; if(!string.IsNullOrEmpty(apiKey)) { HostedGraphiteTcpClient client = new HostedGraphiteTcpClient(apiKey); client.SendMany(logs); } } }); } protected virtual string ApiKey { get { ISettingsResolver settings = this.IFoundation.Resolve<ISettingsResolver>(); return settings.GetSetting(CommonAssumptions.APP_KEY_HEALTH_APIKEY); } } } }
28.743119
108
0.5391
[ "MIT" ]
DanMasterson1/stencil
Source/Stencil.Server/Stencil.Primary/Health/Daemons/HealthReportDaemon.cs
3,135
C#
 #region using statements using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; #endregion namespace DataJuggler.UltimateHelper.Core { #region class DateHelper /// <summary> /// This class has methods to help parse date safely. /// </summary> public class DateHelper { #region Methods #region GetFileNameWithTimestamp(string filename) /// <summary> /// This method Get File Name With Timestamp /// </summary> public static string GetFileNameWithTimestamp(string filename) { // initial value string fileNameWithTimeStamp = ""; // If the filename string exists if (TextHelper.Exists(filename)) { // Get the timestamp string timestamp = GetTimestamp(DateTime.Now); // Create a fileInfo object FileInfo fileInfo = new FileInfo(filename); // Get the name of the file string fileNameWithoutExtension = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf(".")); // set the return value fileNameWithTimeStamp = fileNameWithoutExtension + " - " + timestamp + fileInfo.Extension; // Add the folder back fileNameWithTimeStamp = Path.Combine(fileInfo.DirectoryName, fileNameWithTimeStamp); } // return value return fileNameWithTimeStamp; } #endregion #region GetMinutesThisMillennium() /// <summary> /// This method returns the number of minutes since January 1, 2000 /// </summary> /// <returns></returns> public static int GetMinutesThisMillennium() { // initial value int minutes = 0; // create a date for New Year's Day 2000 DateTime y2k = new DateTime(2000, 1, 1); // set the return value minutes = (int) DateTime.Now.Subtract(y2k).TotalMinutes; // return value return minutes; } #endregion #region GetMinutesThisMillennium(DateTime time) /// <summary> /// This method returns the number of minutes since January 1, 2000 /// </summary> /// <returns></returns> public static int GetMinutesThisMillennium(DateTime time) { // initial value int minutes = 0; // create a date for New Year's Day 2000 DateTime y2k = new DateTime(2000, 1, 1); // set the return value minutes = (int) time.Subtract(DateTime.Now).TotalMinutes; // return value return minutes; } #endregion #region GetMonthEnd(int year = 0, int month = 0) /// <summary> /// This method returns date at the end of the month. /// <param name="year">The year used to return the start date and end date</param> /// <param name="month">The month to return the start date and end date</param> /// </summary> public static DateTime GetMonthEnd(int year = 0, int month = 0) { // initial value DateTime monthEnd; // locals int day = 0; int hour = 23; int min = 59; int sec = 59; // update the params for Year and Month if not supplied if (year == 0) { // Set the value for year year = DateTime.Now.Year; } // Set the value for month if (month == 0) { // Set the value for month month = DateTime.Now.Month; } // set the value for day day = DateTime.DaysInMonth(year, month); // now create the monthEnd date monthEnd = new DateTime(year, month, day, hour, min, sec); // return value return monthEnd; } #endregion #region GetMonthStart(int year = 0, int month = 0) /// <summary> /// This method returns the Month Start /// </summary> public static DateTime GetMonthStart(int year = 0, int month = 0) { // initial value DateTime monthStart; // locals int day = 1; int hour = 0; int min = 0; int sec = 0; // update the params for Year and Month if not supplied if (year == 0) { // Set the value for year year = DateTime.Now.Year; } // Set the value for month if (month == 0) { // Set the value for month month = DateTime.Now.Month; } // now create the monthStart date monthStart = new DateTime(year, month, day, hour, min, sec); // return value return monthStart; } #endregion #region GetShortDateTime(DateTime date) /// <summary> /// This method returns the Time and Date of the string given. /// </summary> public static string GetShortDateTime(DateTime date) { // initial value string time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); // return value return time; } #endregion #region GetTimestamp(DateTime date) /// <summary> /// This method returns the date plus the time /// </summary> public static string GetTimestamp(DateTime date) { // initial value string timestamp = ""; // Get the month string month = GetTwoDigitMonth(date); string hour = GetTwoDigitHour(date); string day = GetTwoDigitDay(date); string minute = GetTwoDigitMinute(date); // Create a string builder StringBuilder sb = new StringBuilder(); // Add each section of the timestamp sb.Append(month); sb.Append(day); sb.Append(date.Year); sb.Append(hour); sb.Append(minute); // Setup the Timestamp timestamp = sb.ToString(); // return value return timestamp; } #endregion #region GetTwoDigitDay(DateTime date) /// <summary> /// This method returns a two digit day for the date given. /// </summary> /// <param name="date"></param> /// <returns></returns> public static string GetTwoDigitDay(DateTime date) { // initial value string twoDigitDay = ""; // set the twoDigitDay twoDigitDay = date.Day.ToString(); // if the Length is less than two if (twoDigitDay.Length < 2) { // prepend a zero to the Day twoDigitDay = "0" + date.Day.ToString(); } // return value return twoDigitDay; } #endregion #region GetTwoDigitHour(DateTime date) /// <summary> /// This method returns a two digit hour for the date given. /// </summary> /// <param name="date"></param> /// <returns></returns> public static string GetTwoDigitHour(DateTime date) { // initial value string twoDigitHour = ""; // set the twoDigitHour twoDigitHour = date.Hour.ToString(); // if the Length is less than two if (twoDigitHour.Length < 2) { // prepend a zero to the Hour twoDigitHour = "0" + date.Hour.ToString(); } // return value return twoDigitHour; } #endregion #region GetTwoDigitMinute(DateTime date) /// <summary> /// This method returns a two digit minute for the date given. /// </summary> /// <param name="date"></param> /// <returns></returns> public static string GetTwoDigitMinute(DateTime date) { // initial value string twoDigitMinute = ""; // set the twoDigitMinute twoDigitMinute = date.Minute.ToString(); // if the Length is less than two if (twoDigitMinute.Length < 2) { // prepend a zero to the Minute twoDigitMinute = "0" + date.Minute.ToString(); } // return value return twoDigitMinute; } #endregion #region GetTwoDigitMonth(DateTime date) /// <summary> /// This method returns the month for the date given. /// </summary> /// <param name="date"></param> /// <returns></returns> public static string GetTwoDigitMonth(DateTime date) { // initial value string twoDigitMonth = ""; // set the twoDigitMonth twoDigitMonth = date.Month.ToString(); // if the Length is less than two if (twoDigitMonth.Length < 2) { // prepend a zero to the month twoDigitMonth = "0" + date.Month.ToString(); } // return value return twoDigitMonth; } #endregion #region IsAfter(DateTime sourceDate, DateTime targetDate, bool includeTime = true) /// <summary> /// This method returns true if the targetDate comes AFTER the sourceDate. /// </summary> public static bool IsAfter(DateTime sourceDate, DateTime targetDate, bool includeTime = true) { // initial value bool isAfter = false; // if time should be Not be included in the comparison if (!includeTime) { // recreate the sourceDate without the time sourceDate = new DateTime(sourceDate.Year, sourceDate.Month, sourceDate.Day); // recreate the targetDate without the time targetDate = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day); } // compare just the dates isAfter = (targetDate > sourceDate); // return value return isAfter; } #endregion #region IsBefore(DateTime sourceDate, DateTime targetDate, bool includeTime = true) /// <summary> /// This method returns true if the targetDate comes Before the sourceDate. /// </summary> public static bool IsBefore(DateTime sourceDate, DateTime targetDate, bool includeTime = true) { // initial value bool isAfter = false; // if time should be Not be included in the comparison if (!includeTime) { // recreate the sourceDate without the time sourceDate = new DateTime(sourceDate.Year, sourceDate.Month, sourceDate.Day); // recreate the targetDate without the time targetDate = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day); } // compare the dates isAfter = (targetDate < sourceDate); // return value return isAfter; } #endregion #region IsDate(string date) /// <summary> /// This method returns true if the string can be parsed into a date. /// </summary> /// <param name="date"></param> /// <returns></returns> public static bool IsDate(string date) { // initial value bool isDate = false; // If the date string exists if (TextHelper.Exists(date)) { try { // local DateTime actualDate = new DateTime(1900, 1, 1); // try and parse the date isDate = DateTime.TryParse(date, out actualDate); // if the value for isDate is true if (isDate) { // if the date did not parse to a valid range if ((actualDate.Year < 1900) || (actualDate.Year > DateTime.Now.Year)) { // not a valid date isDate = false; } } } catch (Exception error) { // for debugging only string err = error.ToString(); } } // return value return isDate; } #endregion #region IsDateInRange(DateTime sourceDate, int allowedDays) /// <summary> /// This method returns true if the sourceDate is not any older than the allowedDays /// </summary> public static bool IsDateInRange(DateTime sourceDate, int allowedDays) { // initial value bool isDateInRange = false; try { // subtract the number of days TimeSpan ts = DateTime.Now.Subtract(sourceDate); // set the return value isDateInRange = (ts.TotalDays <= allowedDays); } catch (Exception error) { // for debugging only string err = error.ToString(); } // return value return isDateInRange; } #endregion #region IsSameDay(DateTime sourceDate, DateTime targetDate) /// <summary> /// This method returns true if the targetDate is the same date as the sourceDate. /// With this override Time is automatically removed so Time is NOT A FACTOR. /// </summary> public static bool IsSameDay(DateTime sourceDate, DateTime targetDate) { // initial value bool isSameDay = false; // remove time values in case they are included sourceDate = new DateTime(sourceDate.Year, sourceDate.Month, sourceDate.Day); targetDate = new DateTime(targetDate.Year, targetDate.Month, targetDate.Day); // set the return value isSameDay = (sourceDate == targetDate); // return value return isSameDay; } #endregion #region ParseDate(string sourceString, DateTime defaultValue, DateTime errorValue) /// <summary> /// This method is used to safely parse a string /// </summary> public static DateTime ParseDate(string sourceString, DateTime defaultValue, DateTime errorValue) { // initial value DateTime returnValue = defaultValue; try { // if the sourceString exists if (!String.IsNullOrEmpty(sourceString)) { // perform the parse returnValue = Convert.ToDateTime(sourceString); } } catch (Exception error) { // for debugging only string err = error.ToString(); // set the value to the errorValue returnValue = errorValue; } // return value return returnValue; } #endregion #endregion } #endregion }
35.029014
114
0.449034
[ "MIT" ]
DataJuggler/DataJuggler.UltimateHelper.Core
DateHelper.cs
18,112
C#
using System; using System.Xml.Serialization; namespace NPOI.OpenXmlFormats.Wordprocessing { [Serializable] [XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IncludeInSchema = false)] public enum ItemsChoiceType27 { [XmlEnum("http://schemas.openxmlformats.org/officeDocument/2006/math:oMath")] oMath, [XmlEnum("http://schemas.openxmlformats.org/officeDocument/2006/math:oMathPara")] oMathPara, bookmarkEnd, bookmarkStart, commentRangeEnd, commentRangeStart, customXml, customXmlDelRangeEnd, customXmlDelRangeStart, customXmlInsRangeEnd, customXmlInsRangeStart, customXmlMoveFromRangeEnd, customXmlMoveFromRangeStart, customXmlMoveToRangeEnd, customXmlMoveToRangeStart, del, ins, moveFrom, moveFromRangeEnd, moveFromRangeStart, moveTo, moveToRangeEnd, moveToRangeStart, permEnd, permStart, proofErr, sdt, tc } }
21.714286
111
0.778509
[ "MIT" ]
iNeverSleeeeep/NPOI-For-Unity
NPOI.OpenXmlFormats.Wordprocessing/ItemsChoiceType27.cs
912
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("StudentManger")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StudentManger")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("21a183a5-ba2a-4601-b0a4-168b91d79e84")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.594595
56
0.715945
[ "Apache-2.0" ]
soojade/StudentManger
StudentManger/Properties/AssemblyInfo.cs
1,288
C#
using LolApp.Models; using LolApp.Services; using Prism.Commands; using Prism.Navigation; using Prism.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Windows.Input; using Xamarin.Essentials; namespace LolApp.ViewModels { public class SummonerDetailViewModel : BaseViewModel, IInitialize { public Summoner Summoner { get; set; } public List<SummonerLeagueDetail> SummonerDetailList { get; set; } public MatchList SummonerMatches { get; set; } public ObservableCollection<Match> SummonerDetailedMatches { get; set; } private ISummonerLeagueApiService _summonerLeagueApiServie; private IMatchApiService _matchApiService; private INavigationService _navigation; public ICommand Refresh { get; } public ObservableCollection<Participant> ParticipationsOfCurrentSummoner { get; set; } public ICommand OnOpenGameCommand { get; } private List<int> participantIdByMatch; public SummonerDetailViewModel(IPageDialogService pageDialogService, ISummonerLeagueApiService summonerLeagueApiService, IMatchApiService matchApiService, INavigationService navigation) : base(pageDialogService) { OnOpenGameCommand = new DelegateCommand<Participant>(GetMatchDetails); Refresh = new DelegateCommand(GetSummonerMatches); _summonerLeagueApiServie = summonerLeagueApiService; _matchApiService = matchApiService; _navigation = navigation; } public void GetMatchDetails(Participant participant) { _navigation.NavigateAsync($"{NavigationConstant.MatchTabbedPage}", new NavigationParameters() { {NavigationConstant.MatchParam, SummonerDetailedMatches.First(element => element.GameId == participant.GameId) }, {NavigationConstant.SummonerParam, Summoner } }); } public void Initialize(INavigationParameters parameters) { if(parameters.TryGetValue(NavigationConstant.SummonerParam, out Summoner _summoner)) { Summoner = _summoner; } GetSummonerLeague(); GetSummonerMatches(); } private async void GetSummonerLeague() { if (Connectivity.NetworkAccess == NetworkAccess.Internet) { var summonerDetail = await _summonerLeagueApiServie.GetSummonerLeagueAsync(Summoner.Id); SummonerDetailList = summonerDetail; } else { await AlertService.DisplayAlertAsync(AlertConstant.NoInternetConnectionTitle, AlertConstant.NoInternetConnectionDescription, AlertConstant.NoInternetConnectionConfirm); } } private async void GetSummonerMatches() { if (Connectivity.NetworkAccess == NetworkAccess.Internet) { var summonerMatches = await _matchApiService.GetMatchesByAccountIdAsync(Summoner.AccountId); SummonerMatches = summonerMatches; SummonerDetailedMatches = new ObservableCollection<Match>(); participantIdByMatch = new List<int>(); foreach (MatchElement element in SummonerMatches.Matches) { Match matchWholeElement = await _matchApiService.GetMatchByIdAsync(element.GameId.ToString()); SummonerDetailedMatches.Add(matchWholeElement); foreach (ParticipantIdentity participantId in matchWholeElement.ParticipantIdentities) { if(participantId.Player.SummonerId == Summoner.Id) { participantIdByMatch.Add(participantId.ParticipantId); } } } ParticipationsOfCurrentSummoner = new ObservableCollection<Participant>(); int counter = 0; foreach (Match match in SummonerDetailedMatches) { ParticipationsOfCurrentSummoner.Add(match.Participants.First(element => element.ParticipantId == participantIdByMatch[counter])); ParticipationsOfCurrentSummoner[counter].GameId = match.GameId; counter++; } // var participantId = SummonerDetailedMatches.First((p)=> p.ParticipantIdentities.Pla == "") } else { await AlertService.DisplayAlertAsync(AlertConstant.NoInternetConnectionTitle, AlertConstant.NoInternetConnectionDescription, AlertConstant.NoInternetConnectionConfirm); } } } }
35.543478
219
0.636086
[ "MIT" ]
DemetrioQ/LolApp
LolApp/LolApp/ViewModels/SummonerDetailViewModel.cs
4,907
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using lm.Comol.Modules.Standard.Glossary.Domain; namespace lm.Comol.Modules.Standard.Glossary.Model { public class EditGroup { public GlossaryGroup Group { get; set; } public Boolean CanShowDetailedList { get; set; } public Boolean CanShowNotPaged { get; set; } } }
21.105263
56
0.690773
[ "MIT" ]
EdutechSRL/Adevico
3-Business/3-Modules/lm.Comol.Modules.Standard/Glossary/Model/EditGroup.cs
403
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { internal partial class PeerExpressRouteCircuitConnectionsRestOperations { private readonly string _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of PeerExpressRouteCircuitConnectionsRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public PeerExpressRouteCircuitConnectionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2021-02-01"; _userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId); } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string circuitName, string peeringName, string connectionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/expressRouteCircuits/", false); uri.AppendPath(circuitName, true); uri.AppendPath("/peerings/", false); uri.AppendPath(peeringName, true); uri.AppendPath("/peerConnections/", false); uri.AppendPath(connectionName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Gets the specified Peer Express Route Circuit Connection from the specified express route circuit. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="connectionName"> The name of the peer express route circuit connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/>, <paramref name="peeringName"/> or <paramref name="connectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/>, <paramref name="peeringName"/> or <paramref name="connectionName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<PeerExpressRouteCircuitConnectionData>> GetAsync(string subscriptionId, string resourceGroupName, string circuitName, string peeringName, string connectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(circuitName, nameof(circuitName)); Argument.AssertNotNullOrEmpty(peeringName, nameof(peeringName)); Argument.AssertNotNullOrEmpty(connectionName, nameof(connectionName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, circuitName, peeringName, connectionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { PeerExpressRouteCircuitConnectionData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = PeerExpressRouteCircuitConnectionData.DeserializePeerExpressRouteCircuitConnectionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((PeerExpressRouteCircuitConnectionData)null, message.Response); default: throw new RequestFailedException(message.Response); } } /// <summary> Gets the specified Peer Express Route Circuit Connection from the specified express route circuit. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the express route circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="connectionName"> The name of the peer express route circuit connection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/>, <paramref name="peeringName"/> or <paramref name="connectionName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/>, <paramref name="peeringName"/> or <paramref name="connectionName"/> is an empty string, and was expected to be non-empty. </exception> public Response<PeerExpressRouteCircuitConnectionData> Get(string subscriptionId, string resourceGroupName, string circuitName, string peeringName, string connectionName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(circuitName, nameof(circuitName)); Argument.AssertNotNullOrEmpty(peeringName, nameof(peeringName)); Argument.AssertNotNullOrEmpty(connectionName, nameof(connectionName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, circuitName, peeringName, connectionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { PeerExpressRouteCircuitConnectionData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = PeerExpressRouteCircuitConnectionData.DeserializePeerExpressRouteCircuitConnectionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((PeerExpressRouteCircuitConnectionData)null, message.Response); default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName, string circuitName, string peeringName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/expressRouteCircuits/", false); uri.AppendPath(circuitName, true); uri.AppendPath("/peerings/", false); uri.AppendPath(peeringName, true); uri.AppendPath("/peerConnections", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Gets all global reach peer connections associated with a private peering in an express route circuit. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<PeerExpressRouteCircuitConnectionListResult>> ListAsync(string subscriptionId, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(circuitName, nameof(circuitName)); Argument.AssertNotNullOrEmpty(peeringName, nameof(peeringName)); using var message = CreateListRequest(subscriptionId, resourceGroupName, circuitName, peeringName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { PeerExpressRouteCircuitConnectionListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = PeerExpressRouteCircuitConnectionListResult.DeserializePeerExpressRouteCircuitConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Gets all global reach peer connections associated with a private peering in an express route circuit. </summary> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is an empty string, and was expected to be non-empty. </exception> public Response<PeerExpressRouteCircuitConnectionListResult> List(string subscriptionId, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(circuitName, nameof(circuitName)); Argument.AssertNotNullOrEmpty(peeringName, nameof(peeringName)); using var message = CreateListRequest(subscriptionId, resourceGroupName, circuitName, peeringName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { PeerExpressRouteCircuitConnectionListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = PeerExpressRouteCircuitConnectionListResult.DeserializePeerExpressRouteCircuitConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string circuitName, string peeringName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Gets all global reach peer connections associated with a private peering in an express route circuit. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<PeerExpressRouteCircuitConnectionListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(circuitName, nameof(circuitName)); Argument.AssertNotNullOrEmpty(peeringName, nameof(peeringName)); using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, circuitName, peeringName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { PeerExpressRouteCircuitConnectionListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = PeerExpressRouteCircuitConnectionListResult.DeserializePeerExpressRouteCircuitConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Gets all global reach peer connections associated with a private peering in an express route circuit. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="circuitName"> The name of the circuit. </param> /// <param name="peeringName"> The name of the peering. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="circuitName"/> or <paramref name="peeringName"/> is an empty string, and was expected to be non-empty. </exception> public Response<PeerExpressRouteCircuitConnectionListResult> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(circuitName, nameof(circuitName)); Argument.AssertNotNullOrEmpty(peeringName, nameof(peeringName)); using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, circuitName, peeringName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { PeerExpressRouteCircuitConnectionListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = PeerExpressRouteCircuitConnectionListResult.DeserializePeerExpressRouteCircuitConnectionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } } }
70.890365
288
0.677617
[ "MIT" ]
KurnakovMaksim/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/PeerExpressRouteCircuitConnectionsRestOperations.cs
21,338
C#
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Serilog; namespace MarketingBox.Bridge.SimpleTrading.Service.Services.Integrations.Contracts.Responses { public static class HttpResponseMessageExtensions { public static async Task<Response<TSuccessResponse, TFailedResponse>> DeserializeTo<TSuccessResponse, TFailedResponse>(this HttpResponseMessage httpResponseMessage) where TSuccessResponse : class where TFailedResponse : class { string resultData = await httpResponseMessage.Content.ReadAsStringAsync(); Log.Logger.Information("SimpleTrading brand return response : {@RawResult}", resultData); try { if (httpResponseMessage.IsSuccessStatusCode) { var response = JsonConvert.DeserializeObject<TSuccessResponse>(resultData); return Response<TSuccessResponse, TFailedResponse>.CreateSuccess(response); } else if (httpResponseMessage.StatusCode == HttpStatusCode.Unauthorized) { throw new Exception(resultData); } else { if (typeof(TFailedResponse) == typeof(string)) return Response<TSuccessResponse, TFailedResponse>.CreateFailed(resultData as TFailedResponse); var response = JsonConvert.DeserializeObject<TFailedResponse>(resultData); return Response<TSuccessResponse, TFailedResponse>.CreateFailed(response); } } catch (Exception e) { Log.Logger.Error(e, "DeserializeTo failed. Response : {resultData}", resultData); throw; } } //public static async Task<ResponseList<TSuccessResponse, TFailedResponse>> DeserializeListTo<TSuccessResponse, // TFailedResponse>(this HttpResponseMessage httpResponseMessage) //where TSuccessResponse : IReadOnlyList<TSuccessResponse> //where TFailedResponse : class //{ // string resultData = await httpResponseMessage.Content.ReadAsStringAsync(); // Log.Logger.Information("SimpleTrading brand return response : {@RawResult}", resultData); // try // { // if (httpResponseMessage.IsSuccessStatusCode) // { // var response = JsonConvert.DeserializeObject<TSuccessResponse>(resultData); // return ResponseList<TSuccessResponse, TFailedResponse>.CreateSuccess(response); // } // else // if (httpResponseMessage.StatusCode == HttpStatusCode.Unauthorized) // { // throw new Exception(resultData); // } // else // { // if (typeof(TFailedResponse) == typeof(string)) // return ResponseList<TSuccessResponse, TFailedResponse>.CreateFailed(resultData as TFailedResponse); // var response = JsonConvert.DeserializeObject<TFailedResponse>(resultData); // return ResponseList<TSuccessResponse, TFailedResponse>.CreateFailed(response); // } // } // catch (Exception e) // { // Log.Logger.Error(e, "DeserializeTo failed. Response : {resultData}", resultData); // throw; // } //} } }
44.317073
125
0.586131
[ "MIT" ]
MyJetMarketingBox/MarketingBox.Bridge.SimpleTrading.Service
src/MarketingBox.Bridge.SimpleTrading.Service/Services/Integrations/Contracts/Responses/HttpResponseMessageExtensions.cs
3,634
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Orchard.PublishLater")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Orchard")] [assembly: AssemblyCopyright("Copyright © Outercurve Foundation 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("41dff4d9-c77b-447f-a557-ca4289b6f50b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.5")] [assembly: AssemblyFileVersion("1.5")]
37.805556
85
0.731815
[ "BSD-3-Clause" ]
akovsh/Orchard
build/MsDeploy/Orchard/Modules/Orchard.PublishLater/Properties/AssemblyInfo.cs
1,364
C#
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Log = Tizen.Log; namespace Tizen.MachineLearning.Inference { /// <summary> /// The TensorsInfo class manages each Tensor information such as Name, Type and Dimension. /// </summary> /// <since_tizen> 6 </since_tizen> public class TensorsInfo : IDisposable { private List<TensorInfo> _infoList; private IntPtr _handle = IntPtr.Zero; private bool _disposed = false; /// <summary> /// Get the number of Tensor information which is added. /// </summary> /// <since_tizen> 6 </since_tizen> public int Count => _infoList.Count; /// <summary> /// Creates a TensorsInfo instance. /// </summary> /// <since_tizen> 6 </since_tizen> public TensorsInfo() { Log.Info(NNStreamer.TAG, "TensorsInfo is created"); _infoList = new List<TensorInfo>(); } /// <summary> /// Destroys the TensorsInfo resource. /// </summary> /// <since_tizen> 6 </since_tizen> ~TensorsInfo() { Dispose(false); } /// <summary> /// Add a Tensor information to the TensorsInfo instance. Note that we support up to 16 tensors in TensorsInfo. /// </summary> /// <param name="type">Data element type of Tensor.</param> /// <param name="dimension">Dimension of Tensor. Note that we support up to 4th ranks.</param> /// <feature>http://tizen.org/feature/machine_learning.inference</feature> /// <exception cref="IndexOutOfRangeException">Thrown when the number of Tensor already exceeds the size limits (i.e. Tensor.SlzeLimit)</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception> /// <since_tizen> 6 </since_tizen> public void AddTensorInfo(TensorType type, int[] dimension) { AddTensorInfo(null, type, dimension); } /// <summary> /// Add a Tensor information to the TensorsInfo instance. Note that we support up to 16 tensors in TensorsInfo. /// </summary> /// <param name="name">Name of Tensor.</param> /// <param name="type">Data element type of Tensor.</param> /// <param name="dimension">Dimension of Tensor. Note that we support up to 4th ranks.</param> /// <feature>http://tizen.org/feature/machine_learning.inference</feature> /// <exception cref="IndexOutOfRangeException">Thrown when the number of Tensor already exceeds the size limits (i.e. Tensor.SlzeLimit)</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception> /// <since_tizen> 6 </since_tizen> public void AddTensorInfo(string name, TensorType type, int[] dimension) { int idx = _infoList.Count; if (idx >= Tensor.SizeLimit) { throw new IndexOutOfRangeException("Max size of the tensors is " + Tensor.SizeLimit); } _infoList.Add(new TensorInfo(name, type, dimension)); if (_handle != IntPtr.Zero) { NNStreamerError ret = NNStreamerError.None; /* Set the number of tensors */ ret = Interop.Util.SetTensorsCount(_handle, _infoList.Count); NNStreamer.CheckException(ret, "unable to set the number of tensors"); /* Set the type and dimension of Tensor */ ret = Interop.Util.SetTensorType(_handle, idx, type); NNStreamer.CheckException(ret, "fail to set TensorsInfo type"); ret = Interop.Util.SetTensorDimension(_handle, idx, dimension); NNStreamer.CheckException(ret, "fail to set TensorsInfo dimension"); } } /// <summary> /// Sets the tensor name with given index. /// </summary> /// <param name="idx">The index of the tensor to be updated.</param> /// <param name="name">The tensor name to be set.</param> /// <feature>http://tizen.org/feature/machine_learning.inference</feature> /// <exception cref="IndexOutOfRangeException">Thrown when the index is greater than the number of Tensor.</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception> /// <since_tizen> 6 </since_tizen> public void SetTensorName(int idx, string name) { CheckIndexBoundary(idx); _infoList[idx].Name = name; if (_handle != IntPtr.Zero) { NNStreamerError ret = NNStreamerError.None; ret = Interop.Util.SetTensorName(_handle, idx, name); NNStreamer.CheckException(ret, "unable to set the name of tensor: " + idx.ToString()); } } /// <summary> /// Gets the tensor name with given index. /// </summary> /// <param name="idx">The index of the tensor.</param> /// <returns>The tensor name.</returns> /// <exception cref="IndexOutOfRangeException">Thrown when the index is greater than the number of Tensor.</exception> /// <since_tizen> 6 </since_tizen> public string GetTensorName(int idx) { CheckIndexBoundary(idx); return _infoList[idx].Name; } /// <summary> /// Sets the tensor type with given index and its type. /// </summary> /// <param name="idx">The index of the tensor to be updated.</param> /// <param name="type">The tensor type to be set.</param> /// <feature>http://tizen.org/feature/machine_learning.inference</feature> /// <exception cref="IndexOutOfRangeException">Thrown when the index is greater than the number of Tensor.</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception> /// <since_tizen> 6 </since_tizen> public void SetTensorType(int idx, TensorType type) { CheckIndexBoundary(idx); _infoList[idx].Type = type; if (_handle != IntPtr.Zero) { NNStreamerError ret = NNStreamerError.None; ret = Interop.Util.SetTensorType(_handle, idx, type); NNStreamer.CheckException(ret, "unable to set the type of tensor: " + idx.ToString()); } } /// <summary> /// Gets the tensor type with given index. /// </summary> /// <param name="idx">The index of the tensor.</param> /// <returns>The tensor type</returns> /// <exception cref="IndexOutOfRangeException">Thrown when the index is greater than the number of Tensor.</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <since_tizen> 6 </since_tizen> public TensorType GetTensorType(int idx) { CheckIndexBoundary(idx); return _infoList[idx].Type; } /// <summary> /// Sets the tensor dimension with given index and dimension. /// </summary> /// <param name="idx">The index of the tensor to be updated.</param> /// <param name="dimension">The tensor dimension to be set.</param> /// <feature>http://tizen.org/feature/machine_learning.inference</feature> /// <exception cref="IndexOutOfRangeException">Thrown when the index is greater than the number of Tensor.</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception> /// <since_tizen> 6 </since_tizen> public void SetDimension(int idx, int[] dimension) { CheckIndexBoundary(idx); _infoList[idx].SetDimension(dimension); if (_handle != IntPtr.Zero) { NNStreamerError ret = NNStreamerError.None; ret = Interop.Util.SetTensorDimension(_handle, idx, dimension); NNStreamer.CheckException(ret, "unable to set the dimension of tensor: " + idx.ToString()); } } /// <summary> /// Gets the tensor dimension with given index. /// </summary> /// <param name="idx">The index of the tensor.</param> /// <returns>The tensor dimension.</returns> /// <exception cref="IndexOutOfRangeException">Thrown when the index is greater than the number of Tensor.</exception> /// <exception cref="ArgumentException">Thrown when the method failed due to an invalid parameter.</exception> /// <since_tizen> 6 </since_tizen> public int[] GetDimension(int idx) { CheckIndexBoundary(idx); return _infoList[idx].Dimension; } /// <summary> /// Creates a TensorsData instance based on informations of TensorsInfo /// </summary> /// <returns>TensorsData instance</returns> /// <feature>http://tizen.org/feature/machine_learning.inference</feature> /// <exception cref="ArgumentException">Thrown when the method failed due to TensorsInfo's information is invalid.</exception> /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception> /// <since_tizen> 6 </since_tizen> public TensorsData GetTensorsData() { IntPtr tensorsData_h; TensorsData retTensorData; NNStreamerError ret = NNStreamerError.None; if (_handle == IntPtr.Zero) { Log.Info(NNStreamer.TAG, "_handle is IntPtr.Zero\n" + " GetTensorsInfoHandle() is called"); GetTensorsInfoHandle(); } ret = Interop.Util.CreateTensorsData(_handle, out tensorsData_h); NNStreamer.CheckException(ret, "unable to create the tensorsData object"); Log.Info(NNStreamer.TAG, "success to CreateTensorsData()\n"); retTensorData = TensorsData.CreateFromNativeHandle(tensorsData_h); return retTensorData; } internal IntPtr GetTensorsInfoHandle() { NNStreamerError ret = NNStreamerError.None; IntPtr ret_handle; int idx; /* Already created */ if (_handle != IntPtr.Zero) return _handle; /* Check required parameters */ int num = _infoList.Count; if (num <= 0 || num > Tensor.SizeLimit) ret = NNStreamerError.InvalidParameter; NNStreamer.CheckException(ret, "number of Tensor in TensorsInfo is invalid: " + _infoList.Count); /* Create TensorsInfo object */ ret = Interop.Util.CreateTensorsInfo(out ret_handle); NNStreamer.CheckException(ret, "fail to create TensorsInfo object"); /* Set the number of tensors */ ret = Interop.Util.SetTensorsCount(ret_handle, _infoList.Count); NNStreamer.CheckException(ret, "unable to set the number of tensors"); /* Set each Tensor info */ idx = 0; foreach (TensorInfo t in _infoList) { ret = Interop.Util.SetTensorType(ret_handle, idx, t.Type); NNStreamer.CheckException(ret, "fail to set the type of tensor" + idx.ToString()); ret = Interop.Util.SetTensorDimension(ret_handle, idx, t.Dimension); NNStreamer.CheckException(ret, "fail to set the dimension of tensor: " + idx.ToString()); idx += 1; } _handle = ret_handle; return ret_handle; } /// <summary> /// Releases any unmanaged resources used by this object. /// </summary> /// <since_tizen> 6 </since_tizen> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. /// </summary> /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param> protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { // release managed objects _infoList.Clear(); } // release unmanaged objects if (_handle != IntPtr.Zero) { NNStreamerError ret = NNStreamerError.None; ret = Interop.Util.DestroyTensorsInfo(_handle); if (ret != NNStreamerError.None) { Log.Error(NNStreamer.TAG, "failed to destroy TensorsInfo object"); } } _disposed = true; } private void CheckIndexBoundary(int idx) { if (idx < 0 || idx >= _infoList.Count) { throw new IndexOutOfRangeException("Invalid index [" + idx + "] of the tensors"); } } private class TensorInfo { public TensorInfo(TensorType type, int[] dimension) { Type = type; SetDimension(dimension); } public TensorInfo(string name, TensorType type, int[] dimension) { Name = name; Type = type; SetDimension(dimension); } public void SetDimension(int[] dimension) { if (dimension == null) { throw new ArgumentException("Max size of the tensor rank is" + Tensor.RankLimit); } if (dimension.Length > Tensor.RankLimit) { throw new ArgumentException("Max size of the tensor rank is" + Tensor.RankLimit); } Dimension = (int[])dimension.Clone(); } public string Name { get; set; } = null; public TensorType Type { get; set; } = TensorType.Int32; public int[] Dimension { get; private set; } = new int[Tensor.RankLimit]; } } }
42.455285
155
0.593578
[ "Apache-2.0" ]
agnelovaz/TizenFX
src/Tizen.MachineLearning.Inference/Tizen.MachineLearning.Inference/TensorsInfo.cs
15,668
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Pinpoint.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for JourneyCustomMessage Object /// </summary> public class JourneyCustomMessageUnmarshaller : IUnmarshaller<JourneyCustomMessage, XmlUnmarshallerContext>, IUnmarshaller<JourneyCustomMessage, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> JourneyCustomMessage IUnmarshaller<JourneyCustomMessage, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public JourneyCustomMessage Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; JourneyCustomMessage unmarshalledObject = new JourneyCustomMessage(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Data", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Data = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static JourneyCustomMessageUnmarshaller _instance = new JourneyCustomMessageUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static JourneyCustomMessageUnmarshaller Instance { get { return _instance; } } } }
35.076087
174
0.628757
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/JourneyCustomMessageUnmarshaller.cs
3,227
C#