content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.AssetModels;
using TTC2017.SmartGrids.CIM.IEC61968.Assets;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Customers;
using TTC2017.SmartGrids.CIM.IEC61968.Work;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssetModels;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCustomers;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfLocations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfTypeAsset;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfWork;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport
{
/// <summary>
/// The public interface for ErpReqLineItem
/// </summary>
[DefaultImplementationTypeAttribute(typeof(ErpReqLineItem))]
[XmlDefaultImplementationTypeAttribute(typeof(ErpReqLineItem))]
public interface IErpReqLineItem : IModelElement, IIdentifiedObject
{
/// <summary>
/// The deliveryDate property
/// </summary>
string DeliveryDate
{
get;
set;
}
/// <summary>
/// The quantity property
/// </summary>
int Quantity
{
get;
set;
}
/// <summary>
/// The code property
/// </summary>
string Code
{
get;
set;
}
/// <summary>
/// The cost property
/// </summary>
float Cost
{
get;
set;
}
/// <summary>
/// The TypeMaterial property
/// </summary>
ITypeMaterial TypeMaterial
{
get;
set;
}
/// <summary>
/// The ErpQuoteLineItem property
/// </summary>
IErpQuoteLineItem ErpQuoteLineItem
{
get;
set;
}
/// <summary>
/// The status property
/// </summary>
IStatus Status
{
get;
set;
}
/// <summary>
/// The ErpRequisition property
/// </summary>
IErpRequisition ErpRequisition
{
get;
set;
}
/// <summary>
/// The TypeAsset property
/// </summary>
ITypeAsset TypeAsset
{
get;
set;
}
/// <summary>
/// The ErpPOLineItem property
/// </summary>
IErpPOLineItem ErpPOLineItem
{
get;
set;
}
/// <summary>
/// Gets fired before the DeliveryDate property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> DeliveryDateChanging;
/// <summary>
/// Gets fired when the DeliveryDate property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> DeliveryDateChanged;
/// <summary>
/// Gets fired before the Quantity property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> QuantityChanging;
/// <summary>
/// Gets fired when the Quantity property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> QuantityChanged;
/// <summary>
/// Gets fired before the Code property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CodeChanging;
/// <summary>
/// Gets fired when the Code property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CodeChanged;
/// <summary>
/// Gets fired before the Cost property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CostChanging;
/// <summary>
/// Gets fired when the Cost property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CostChanged;
/// <summary>
/// Gets fired before the TypeMaterial property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> TypeMaterialChanging;
/// <summary>
/// Gets fired when the TypeMaterial property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> TypeMaterialChanged;
/// <summary>
/// Gets fired before the ErpQuoteLineItem property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> ErpQuoteLineItemChanging;
/// <summary>
/// Gets fired when the ErpQuoteLineItem property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> ErpQuoteLineItemChanged;
/// <summary>
/// Gets fired before the Status property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> StatusChanging;
/// <summary>
/// Gets fired when the Status property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> StatusChanged;
/// <summary>
/// Gets fired before the ErpRequisition property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> ErpRequisitionChanging;
/// <summary>
/// Gets fired when the ErpRequisition property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> ErpRequisitionChanged;
/// <summary>
/// Gets fired before the TypeAsset property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> TypeAssetChanging;
/// <summary>
/// Gets fired when the TypeAsset property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> TypeAssetChanged;
/// <summary>
/// Gets fired before the ErpPOLineItem property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> ErpPOLineItemChanging;
/// <summary>
/// Gets fired when the ErpPOLineItem property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> ErpPOLineItemChanged;
}
}
| 31.908367 | 96 | 0.599825 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/Schema/IEC61970/Informative/InfERPSupport/IErpReqLineItem.cs | 8,011 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EPiServer.Core;
using EPiServer.Filters;
using AlloyDemoKit.Business;
using AlloyDemoKit.Models.Blocks;
using AlloyDemoKit.Models.ViewModels;
using EPiServer.Web.Mvc;
using EPiServer;
using EPiServer.Templates.Blog.Mvc.Models.Blocks;
namespace AlloyDemoKit.Controllers
{
public class CarouselBlockController : BlockController<CarouselBlock>
{
private ContentLocator contentLocator;
private IContentLoader contentLoader;
public CarouselBlockController(ContentLocator contentLocator, IContentLoader contentLoader)
{
this.contentLocator = contentLocator;
this.contentLoader = contentLoader;
}
public override ActionResult Index(CarouselBlock currentBlock)
{
if (currentBlock.MainContentArea == null) {
return PartialView("Carousel", null);
}
var model = new CarouselViewModel
{
Items =
currentBlock.MainContentArea.FilteredItems.Select(
cai => contentLoader.Get<CarouselItemBlock>(cai.ContentLink)).ToList(),
CurrentBlock = currentBlock
};
return PartialView("Carousel", model);
}
}
}
| 30.727273 | 99 | 0.650148 | [
"Apache-2.0"
] | Codecamv/AlloyDemoKit | src/AlloyDemoKit/Controllers/CarouselBlockController.cs | 1,352 | 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 DependencyInjectionValidation {
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", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DependencyInjectionValidation.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to A service extension should add all required interfaces for the exposed class. In some cases, it makes sense to ignore a particular dependency, e.g. when it is configured by the user elsewhere (for example: ILogger<T>). In that case, add the attribute IgnoreDependency(params Type[]) to the service extension (e.g. [IgnoreDependency(typeof(ILogger<MyClass>))])..
/// </summary>
internal static string MissingDependencyAnalyzerDescription {
get {
return ResourceManager.GetString("MissingDependencyAnalyzerDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Service extension is not adding all required interfaces for {0}. Missing interface: {1}..
/// </summary>
internal static string MissingDependencyAnalyzerMessageFormat {
get {
return ResourceManager.GetString("MissingDependencyAnalyzerMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incomplete service extension.
/// </summary>
internal static string MissingDependencyAnalyzerTitle {
get {
return ResourceManager.GetString("MissingDependencyAnalyzerTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A dependency is missing, which means it is unlikely that the program will function correctly. Add the dependency by using either the corresponding service extension, or by adding it with the AddScoped, AddSingleton, or AddTransient methods. If the dependency is added by an extension method that does not communicate which interfaces it exposes (e.g. third party libraries), add the Injects attribute to the DependencyInjectionPoint method. E.g.
///[DependencyInjectionPoint]
///[Injects(typeof(ILogger<>))]
///public [rest of string was truncated]";.
/// </summary>
internal static string MissingDependencyInApplicationDescription {
get {
return ResourceManager.GetString("MissingDependencyInApplicationDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dependency {0} of {1} is missing..
/// </summary>
internal static string MissingDependencyInApplicationMessageFormat {
get {
return ResourceManager.GetString("MissingDependencyInApplicationMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing dependency.
/// </summary>
internal static string MissingDependencyInApplicationTitle {
get {
return ResourceManager.GetString("MissingDependencyInApplicationTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Each class in a class library that is intended for dependency injection should have a corresponding service extension.
///E.g.
///public static class ServiceExtensions
///{
/// [Exposes(typeof(MyService)), As(typeof(IMyService))]
/// public static IServiceCollection AddMyService(this IServiceCollection services)
/// {
/// return services.AddSingleton<IMyService, MyService>();
/// }
///}
///
///If you get this warning in project that is not a class library, consider marking the method that initializes your service c [rest of string was truncated]";.
/// </summary>
internal static string MissingServiceExtensionAnalyzerDescription {
get {
return ResourceManager.GetString("MissingServiceExtensionAnalyzerDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing service extension for class {0}..
/// </summary>
internal static string MissingServiceExtensionAnalyzerMessageFormat {
get {
return ResourceManager.GetString("MissingServiceExtensionAnalyzerMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing service extension.
/// </summary>
internal static string MissingServiceExtensionAnalyzerTitle {
get {
return ResourceManager.GetString("MissingServiceExtensionAnalyzerTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Any given class should only be exposed with a service extension once, to avoid confusion of the user..
/// </summary>
internal static string TooManyServiceExtensionsDescription {
get {
return ResourceManager.GetString("TooManyServiceExtensionsDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Too many service extensions for class {0}. Candidates are: {1}..
/// </summary>
internal static string TooManyServiceExtensionsMessageFormat {
get {
return ResourceManager.GetString("TooManyServiceExtensionsMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Too many service extensions.
/// </summary>
internal static string TooManyServiceExtensionsTitle {
get {
return ResourceManager.GetString("TooManyServiceExtensionsTitle", resourceCulture);
}
}
}
}
| 47.370968 | 499 | 0.623425 | [
"MIT"
] | excubo-ag/Analyzers.DependencyInjectionValidation | DependencyInjectionValidation/Resources.Designer.cs | 8,813 | C# |
using Catalog.API.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Catalog.API.Repositories
{
public interface IProductRepository
{
Task<IEnumerable<Product>> GetProducts();
Task<Product> GetProductById(string productId);
Task<IEnumerable<Product>> GetProductByCategory(string productCategory);
Task<IEnumerable<Product>> GetProductByName(string productName);
Task AddProduct(Product product);
Task<bool> UpdateProduct(Product product);
Task<bool> DeleteProduct(string productId);
}
}
| 24.833333 | 80 | 0.723154 | [
"MIT"
] | majaham/AspnetMicroservices | src/Services/Catalog/Catalog.API/Repositories/IProductRepository.cs | 598 | C# |
namespace PersonInfo
{
using System;
public class StartUp
{
public static void Main()
{
string name = Console.ReadLine();
int age = int.Parse(Console.ReadLine());
string id = Console.ReadLine();
string birthdate = Console.ReadLine();
IIdentifiable identifiable = new Citizen(name, age, id, birthdate);
IBirthable birthable = new Citizen(name, age, id, birthdate);
Console.WriteLine(identifiable.Id);
Console.WriteLine(birthable.Birthdate);
}
}
}
| 26.636364 | 79 | 0.578498 | [
"MIT"
] | dMundov/SoftUni-HomeWorks | CSharp-OOP/05.Interfaces and Abstraction - Exercise/02.MultipleImplementation/StartUp.cs | 588 | C# |
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
using Kaitai;
using System.Collections.Generic;
namespace KCD.Library.Tables
{
public partial class PerkCodex : KaitaiStruct
{
public static PerkCodex FromFile(string fileName)
{
return new PerkCodex(new KaitaiStream(fileName));
}
public PerkCodex(KaitaiStream p__io, KaitaiStruct p__parent = null, PerkCodex p__root = null) : base(p__io)
{
m_parent = p__parent;
m_root = p__root ?? this;
_read();
}
private void _read()
{
_table = new Header(m_io, this, m_root);
_rows = new List<Row>((int) (Table.RowCount));
for (var i = 0; i < Table.RowCount; i++)
{
_rows.Add(new Row(m_io, this, m_root));
}
_strings = new List<string>((int) (Table.UniqueStringsCount));
for (var i = 0; i < Table.UniqueStringsCount; i++)
{
_strings.Add(System.Text.Encoding.GetEncoding("utf-8").GetString(m_io.ReadBytesTerm(0, false, true, true)));
}
}
public partial class Header : KaitaiStruct
{
public static Header FromFile(string fileName)
{
return new Header(new KaitaiStream(fileName));
}
public Header(KaitaiStream p__io, PerkCodex p__parent = null, PerkCodex p__root = null) : base(p__io)
{
m_parent = p__parent;
m_root = p__root;
_read();
}
private void _read()
{
_version = m_io.ReadS4le();
_descriptorsHash = m_io.ReadU4le();
_layoutHash = m_io.ReadU4le();
_tableVersion = m_io.ReadS4le();
_rowCount = m_io.ReadS4le();
_stringDataSize = m_io.ReadS4le();
_uniqueStringsCount = m_io.ReadS4le();
}
private int _version;
private uint _descriptorsHash;
private uint _layoutHash;
private int _tableVersion;
private int _rowCount;
private int _stringDataSize;
private int _uniqueStringsCount;
private PerkCodex m_root;
private PerkCodex m_parent;
public int Version { get { return _version; } }
public uint DescriptorsHash { get { return _descriptorsHash; } }
public uint LayoutHash { get { return _layoutHash; } }
public int TableVersion { get { return _tableVersion; } }
public int RowCount { get { return _rowCount; } }
public int StringDataSize { get { return _stringDataSize; } }
public int UniqueStringsCount { get { return _uniqueStringsCount; } }
public PerkCodex M_Root { get { return m_root; } }
public PerkCodex M_Parent { get { return m_parent; } }
}
public partial class Row : KaitaiStruct
{
public static Row FromFile(string fileName)
{
return new Row(new KaitaiStream(fileName));
}
public Row(KaitaiStream p__io, PerkCodex p__parent = null, PerkCodex p__root = null) : base(p__io)
{
m_parent = p__parent;
m_root = p__root;
_read();
}
private void _read()
{
_perkId = m_io.ReadBytes(16);
_codexUiPageId = m_io.ReadS4le();
_codexUiLayoutId = m_io.ReadS4le();
_codexUiText = m_io.ReadS4le();
_codexUiImage = m_io.ReadS4le();
_defaultLearned = m_io.ReadS1();
}
private byte[] _perkId;
private int _codexUiPageId;
private int _codexUiLayoutId;
private int _codexUiText;
private int _codexUiImage;
private sbyte _defaultLearned;
private PerkCodex m_root;
private PerkCodex m_parent;
public byte[] PerkId { get { return _perkId; } }
public int CodexUiPageId { get { return _codexUiPageId; } }
public int CodexUiLayoutId { get { return _codexUiLayoutId; } }
public int CodexUiText { get { return _codexUiText; } }
public int CodexUiImage { get { return _codexUiImage; } }
public sbyte DefaultLearned { get { return _defaultLearned; } }
public PerkCodex M_Root { get { return m_root; } }
public PerkCodex M_Parent { get { return m_parent; } }
}
private Header _table;
private List<Row> _rows;
private List<string> _strings;
private PerkCodex m_root;
private KaitaiStruct m_parent;
public Header Table { get { return _table; } }
public List<Row> Rows { get { return _rows; } }
public List<string> Strings { get { return _strings; } }
public PerkCodex M_Root { get { return m_root; } }
public KaitaiStruct M_Parent { get { return m_parent; } }
}
}
| 40.578125 | 124 | 0.556026 | [
"MIT"
] | Scrivener07/Kingdom-Come | Source/KCD.Kaitai/Tables/PerkCodex.cs | 5,194 | C# |
using System;
class PrintPerimetarAndArea
{
static void Main()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Console.WriteLine("Enter a radius of circle: ");
double r = double.Parse(Console.ReadLine());
double area = Math.PI * r * r;
double circumference = Math.PI * 2 * r;
Console.WriteLine("{0:F5}", area);
Console.WriteLine("{0:F5}", circumference);
}
} | 32.533333 | 113 | 0.643443 | [
"MIT"
] | iKostov86/CSharp | Homeworks/C# - part 1/ConsoleInputOutput/02.PrintPerimatarAndArea/PrintPerimetarAndArea.cs | 490 | 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 System.Resources
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class NeutralResourcesLanguageAttribute : Attribute
{
public NeutralResourcesLanguageAttribute(string cultureName)
{
if (cultureName == null)
throw new ArgumentNullException(nameof(cultureName));
CultureName = cultureName;
Location = UltimateResourceFallbackLocation.MainAssembly;
}
public NeutralResourcesLanguageAttribute(string cultureName, UltimateResourceFallbackLocation location)
{
if (cultureName == null)
throw new ArgumentNullException(nameof(cultureName));
if (!Enum.IsDefined(typeof(UltimateResourceFallbackLocation), location))
throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, location));
CultureName = cultureName;
Location = location;
}
public string CultureName { get; }
public UltimateResourceFallbackLocation Location { get; }
}
}
| 38.823529 | 117 | 0.690152 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs | 1,320 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("VoicemeeterTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VoicemeeterTest")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9952548a-7ae1-4eab-9b5a-f1fa04954f29")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 30 | 56 | 0.757143 | [
"MIT"
] | DmitriySalnikov/VoicemeeterRemote | VoicemeeterTest/Properties/AssemblyInfo.cs | 631 | C# |
// This file was auto-generated based on version 1.0.0 of the canonical data.
using System;
using System.Collections.Generic;
using Xunit;
public class GoCountingTests
{
[Fact]
public void Black_corner_territory_on_5x5_board()
{
var coordinate = (0, 1);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
var actual = sut.Territory(coordinate);
var expected = (Owner.Black, new[] { (0, 0), (0, 1), (1, 0) });
Assert.Equal(expected.Item1, actual.Item1);
Assert.Equal(expected.Item2, actual.Item2);
}
[Fact(Skip = "Remove to run test")]
public void White_center_territory_on_5x5_board()
{
var coordinate = (2, 3);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
var actual = sut.Territory(coordinate);
var expected = (Owner.White, new[] { (2, 3) });
Assert.Equal(expected.Item1, actual.Item1);
Assert.Equal(expected.Item2, actual.Item2);
}
[Fact(Skip = "Remove to run test")]
public void Open_corner_territory_on_5x5_board()
{
var coordinate = (1, 4);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
var actual = sut.Territory(coordinate);
var expected = (Owner.None, new[] { (0, 3), (0, 4), (1, 4) });
Assert.Equal(expected.Item1, actual.Item1);
Assert.Equal(expected.Item2, actual.Item2);
}
[Fact(Skip = "Remove to run test")]
public void A_stone_and_not_a_territory_on_5x5_board()
{
var coordinate = (1, 1);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
var actual = sut.Territory(coordinate);
var expected = (Owner.None, Array.Empty<(int, int)>());
Assert.Equal(expected.Item1, actual.Item1);
Assert.Equal(expected.Item2, actual.Item2);
}
[Fact(Skip = "Remove to run test")]
public void Invalid_because_x_is_too_low_for_5x5_board()
{
var coordinate = (-1, 1);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
}
[Fact(Skip = "Remove to run test")]
public void Invalid_because_x_is_too_high_for_5x5_board()
{
var coordinate = (5, 1);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
}
[Fact(Skip = "Remove to run test")]
public void Invalid_because_y_is_too_low_for_5x5_board()
{
var coordinate = (1, -1);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
}
[Fact(Skip = "Remove to run test")]
public void Invalid_because_y_is_too_high_for_5x5_board()
{
var coordinate = (1, 5);
var board =
" B \n" +
" B B \n" +
"B W B\n" +
" W W \n" +
" W ";
var sut = new GoCounting(board);
Assert.Throws<ArgumentException>(() => sut.Territory(coordinate));
}
[Fact(Skip = "Remove to run test")]
public void One_territory_is_the_whole_board()
{
var board = " ";
var sut = new GoCounting(board);
var actual = sut.Territories();
var expected = new Dictionary<Owner, (int, int)[]>
{
[Owner.Black] = Array.Empty<(int, int)>(),
[Owner.White] = Array.Empty<(int, int)>(),
[Owner.None] = new[] { (0, 0) }
};
Assert.Equal(expected.Keys, actual.Keys);
Assert.Equal(expected[Owner.Black], actual[Owner.Black]);
Assert.Equal(expected[Owner.White], actual[Owner.White]);
Assert.Equal(expected[Owner.None], actual[Owner.None]);
}
[Fact(Skip = "Remove to run test")]
public void Two_territory_rectangular_board()
{
var board =
" BW \n" +
" BW ";
var sut = new GoCounting(board);
var actual = sut.Territories();
var expected = new Dictionary<Owner, (int, int)[]>
{
[Owner.Black] = new[] { (0, 0), (0, 1) },
[Owner.White] = new[] { (3, 0), (3, 1) },
[Owner.None] = Array.Empty<(int, int)>()
};
Assert.Equal(expected.Keys, actual.Keys);
Assert.Equal(expected[Owner.Black], actual[Owner.Black]);
Assert.Equal(expected[Owner.White], actual[Owner.White]);
Assert.Equal(expected[Owner.None], actual[Owner.None]);
}
[Fact(Skip = "Remove to run test")]
public void Two_region_rectangular_board()
{
var board = " B ";
var sut = new GoCounting(board);
var actual = sut.Territories();
var expected = new Dictionary<Owner, (int, int)[]>
{
[Owner.Black] = new[] { (0, 0), (2, 0) },
[Owner.White] = Array.Empty<(int, int)>(),
[Owner.None] = Array.Empty<(int, int)>()
};
Assert.Equal(expected.Keys, actual.Keys);
Assert.Equal(expected[Owner.Black], actual[Owner.Black]);
Assert.Equal(expected[Owner.White], actual[Owner.White]);
Assert.Equal(expected[Owner.None], actual[Owner.None]);
}
} | 32.037234 | 77 | 0.508052 | [
"MIT"
] | shm613/csharp | exercises/go-counting/GoCountingTests.cs | 6,023 | C# |
using System;
using Xunit;
using System.Linq;
using ToDoApi.Data;
using Microsoft.EntityFrameworkCore;
using ToDoApi.Models;
using ToDoApi.Controllers;
using System.Net;
using Microsoft.AspNetCore.Mvc;
namespace ToDoApiTests
{
public class ToDoControllerTest
{
[Fact]
public void CanCreateAToDoItem()
{
DbContextOptions<ToDoDbContext> options =
new DbContextOptionsBuilder<ToDoDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
using (ToDoDbContext context = new ToDoDbContext(options))
{
ToDoItem item = new ToDoItem
{
Name = "test todo",
IsDone = true
};
ToDoController tdc = new ToDoController(context);
var result = tdc.Create(item).Result;
var r = (ObjectResult)result;
var status = r.StatusCode.Value;
Assert.Equal(HttpStatusCode.Created, (HttpStatusCode)status);
}
}
[Fact]
public async void CanReadAToDoItem()
{
DbContextOptions<ToDoDbContext> options =
new DbContextOptionsBuilder<ToDoDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
using (ToDoDbContext context = new ToDoDbContext(options))
{
ToDoItem item = new ToDoItem
{
Name = "test todo",
IsDone = true,
ListID = 1
};
ToDoList list = new ToDoList
{
ID = 1,
Name = "test list",
IsDone = true
};
ToDoListController tdlc = new ToDoListController(context);
await tdlc.Create(list);
ToDoController tdc = new ToDoController(context);
await tdc.Create(item);
var findItem = await tdc.GetById(item.ID);
var result = (ObjectResult)findItem.Result;
var readItem = (ToDoItem)result.Value;
Assert.Equal(item.Name, readItem.Name);
}
}
[Fact]
public async void CanUpdateAToDoItem()
{
DbContextOptions<ToDoDbContext> options =
new DbContextOptionsBuilder<ToDoDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
using (ToDoDbContext context = new ToDoDbContext(options))
{
ToDoItem item = new ToDoItem
{
Name = "test todo",
IsDone = true,
ListID = 1
};
ToDoList list = new ToDoList
{
ID = 1,
Name = "test list",
IsDone = true
};
ToDoListController tdlc = new ToDoListController(context);
await tdlc.Create(list);
ToDoController tdc = new ToDoController(context);
await tdc.Create(item);
ToDoItem update = new ToDoItem
{
ID = item.ID,
Name = "todo test",
IsDone = false,
ListID = item.ListID
};
await tdc.Update(item.ID, update);
var findItem = await tdc.GetById(update.ID);
var result = (ObjectResult)findItem.Result;
var readItem = (ToDoItem)result.Value;
Assert.Equal(update.Name, readItem.Name);
}
}
[Fact]
public void CanDeleteAToDoItem()
{
DbContextOptions<ToDoDbContext> options =
new DbContextOptionsBuilder<ToDoDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
using (ToDoDbContext context = new ToDoDbContext(options))
{
ToDoItem item = new ToDoItem
{
ID = 1,
Name = "test todo",
IsDone = true
};
ToDoController tdc = new ToDoController(context);
var result = tdc.Create(item).Result;
var results = context.ToDoItems.Where(i => i.Name == "test todo");
Assert.Equal(1, results.Count());
var remove = tdc.Delete(item.ID);
Assert.True(remove.IsCompletedSuccessfully);
}
}
}
}
| 31.025974 | 82 | 0.481582 | [
"MIT"
] | ericsingletonjr/Lab17-API-Double-Resource | ToDoApi/ToDoApiTests/ToDoControllerTest.cs | 4,778 | C# |
using UnityEngine;
using UnityEngine.UI;
namespace TowerBuilder
{
public class TowerGenerator : MonoBehaviour
{
[SerializeField] private Camera _camera;
[SerializeField] private GameObject _brickPrefab;
[SerializeField] private GameObject _towerPools;
[SerializeField] private Text _scoreText;
[SerializeField] private float _moveDistance = 50f;
[SerializeField, Range(0, 1)] private float _speed = 0.2f;
private GameObject _currentBrick;
private bool _moveLeft = false;
private float _nextHeight;
private bool _moveUp = false;
private int _floor = 0;
private float _brickSize;
private float _brickHeight;
private float _moveUpDistance;
private void Awake()
{
_brickSize = _brickPrefab.transform.localScale.x;
_brickHeight = _brickPrefab.transform.localScale.y;
_moveUpDistance = (_brickHeight / 2) * 4;
}
// Start is called before the first frame update
private void Start()
{
transform.position = new Vector3(transform.position.x, _moveUpDistance, transform.position.z);
CreateNewBrick();
_scoreText.text = $"{_floor} floor";
}
// Update is called once per frame
private void Update()
{
if (GameManager.Instance.IsGameEnd) return;
if (Input.GetKeyDown(KeyCode.Space))
{
DropBrick();
CreateNewBrick();
_nextHeight = transform.position.y + _moveUpDistance;
_moveUp = true;
_floor++;
_scoreText.text = $"{_floor} floor";
}
}
private void FixedUpdate()
{
transform.Translate((_moveLeft ? Vector3.left : Vector3.right) * _speed);
if (Mathf.Abs(transform.position.x) > _moveDistance) _moveLeft = !_moveLeft;
if (_moveUp)
{
transform.Translate(Vector3.up);
_camera.transform.Translate(Vector3.back);
if (transform.position.y >= _nextHeight) _moveUp = false;
}
}
private void CreateNewBrick()
{
_currentBrick = Instantiate(_brickPrefab, transform.position, Quaternion.identity, transform);
_currentBrick.transform.localScale = new Vector3(_brickSize, _brickHeight, _brickSize);
_brickSize -= 0.1f;
_currentBrick.GetComponent<Rigidbody>().isKinematic = true;
}
private void DropBrick()
{
_currentBrick.transform.position -= new Vector3(0, -_brickHeight, 0);
_currentBrick.transform.parent = _towerPools.transform;
_currentBrick.GetComponent<Rigidbody>().isKinematic = false;
}
}
}
| 32.370787 | 106 | 0.592156 | [
"MIT"
] | pid011/TowerBuilder | Assets/TowerBuilder/TowerGenerator.cs | 2,881 | C# |
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pakhd.Shared.Models
{
public enum SalesOrderStatus
{
Open,
Released,
Posted
}
public class SalesOrder
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string SalesOrderId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime CreatedOn { get; set; } = DateTime.Now;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime UpdatedOn { get; set; } = DateTime.Now;
public DateTime PostingDate { get; set; }
public string OrderNo { get; set; }
public string PakhdUserId { get; set; }
public PakhdUser PakhdUser { get; set; }
public SalesOrderStatus Status { get; set; }
public List<SalesLine> SalesLines { get; set; }
}
}
| 25.25641 | 63 | 0.651777 | [
"Apache-2.0"
] | pakhd/pakhd | Shared/Models/SalesOrder.cs | 987 | C# |
using AutoMapper;
using Hotel.App.Model;
using Hotel.App.Model.SYS;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Hotel.App.API.ViewModels.Mappings
{
public class DomainToViewModelMappingProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Schedule, ScheduleViewModel>()
.ForMember(vm => vm.Creator,
map => map.MapFrom(s => s.Creator.Name))
.ForMember(vm => vm.Attendees, map =>
map.MapFrom(s => s.Attendees.Select(a => a.UserId)));
Mapper.CreateMap<Schedule, ScheduleDetailsViewModel>()
.ForMember(vm => vm.Creator,
map => map.MapFrom(s => s.Creator.Name))
.ForMember(vm => vm.Attendees, map =>
map.UseValue(new List<UserViewModel>()))
.ForMember(vm => vm.Status, map =>
map.MapFrom(s => ((ScheduleStatus)s.Status).ToString()))
.ForMember(vm => vm.Type, map =>
map.MapFrom(s => ((ScheduleType)s.Type).ToString()))
.ForMember(vm => vm.Statuses, map =>
map.UseValue(Enum.GetNames(typeof(ScheduleStatus)).ToArray()))
.ForMember(vm => vm.Types, map =>
map.UseValue(Enum.GetNames(typeof(ScheduleType)).ToArray()));
Mapper.CreateMap<User, UserViewModel>()
.ForMember(vm => vm.SchedulesCreated,
map => map.MapFrom(u => u.SchedulesCreated.Count()));
Mapper.CreateMap<sys_user, SysUserViewModel>();
Mapper.CreateMap<sys_menu, SysMenuViewModel>();
}
}
}
| 39.022727 | 82 | 0.557368 | [
"MIT"
] | liquanchun/hotel-app-api | Hotel.App.API/ViewModels/Mappings/DomainToViewModelMappingProfile.cs | 1,719 | C# |
namespace OTProyect.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<OTProyect.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(OTProyect.Models.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
| 31.71875 | 106 | 0.564532 | [
"MIT"
] | JeyssonXD/Sistema-Alerta-OT | OTProyect/Migrations/Configuration.cs | 1,015 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace HjtProject.Views.Shared
{
public class PartialFooterModel : PageModel
{
public void OnGet()
{
}
}
}
| 18.764706 | 47 | 0.711599 | [
"MIT",
"Unlicense"
] | MeshalNajdi/Project04_Auth_CRUD_ASP.NET | HjtProject/Views/Shared/PartialFooter.cshtml.cs | 319 | C# |
namespace Project.Controllers.Api
{
using Microsoft.AspNetCore.Mvc;
using Project.Controllers.Api.Cars;
using Project.Services.Cars;
using Project.Services.Cars.Models;
[ApiController]
[Route("api/cars")]
public class CarsApiController : ControllerBase
{
private readonly ICarService cars;
public CarsApiController(ICarService data)
=> this.cars = cars;
[HttpGet]
public CarQueryServiceModel All([FromQuery] AllCarsApiRequestModel query)
{
return this.cars.All(
query.Brand,
query.SearchTerm,
query.Sorting,
query.CurrentPage,
query.CarsPerPage
);
}
}
}
| 22.114286 | 82 | 0.576227 | [
"MIT"
] | HardSmile/ASP.NET---Core-Project | Project/Controllers/Api/CarsApiController.cs | 776 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("InterfaceDeserializer.Test")] | 50 | 60 | 0.85 | [
"MIT"
] | kkikzk/InterfaceDeserializer | InterfaceDeserializer/AssemblyInfo.cs | 102 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/service_service.proto
// </auto-generated>
// Original file comments:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Cloud.Monitoring.V3 {
/// <summary>
/// The Cloud Monitoring Service-Oriented Monitoring API has endpoints for
/// managing and querying aspects of a workspace's services. These include the
/// `Service`'s monitored resources, its Service-Level Objectives, and a taxonomy
/// of categorized Health Metrics.
/// </summary>
public static partial class ServiceMonitoringService
{
static readonly string __ServiceName = "google.monitoring.v3.ServiceMonitoringService";
static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context)
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (message is global::Google.Protobuf.IBufferMessage)
{
context.SetPayloadLength(message.CalculateSize());
global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter());
context.Complete();
return;
}
#endif
context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message));
}
static class __Helper_MessageCache<T>
{
public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T));
}
static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T>
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (__Helper_MessageCache<T>.IsBufferMessage)
{
return parser.ParseFrom(context.PayloadAsReadOnlySequence());
}
#endif
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateServiceRequest> __Marshaller_google_monitoring_v3_CreateServiceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.CreateServiceRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.Service> __Marshaller_google_monitoring_v3_Service = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.Service.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetServiceRequest> __Marshaller_google_monitoring_v3_GetServiceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.GetServiceRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServicesRequest> __Marshaller_google_monitoring_v3_ListServicesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.ListServicesRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServicesResponse> __Marshaller_google_monitoring_v3_ListServicesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.ListServicesResponse.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest> __Marshaller_google_monitoring_v3_UpdateServiceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.UpdateServiceRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest> __Marshaller_google_monitoring_v3_DeleteServiceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.DeleteServiceRequest.Parser));
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_google_protobuf_Empty = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Protobuf.WellKnownTypes.Empty.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_CreateServiceLevelObjectiveRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Marshaller_google_monitoring_v3_ServiceLevelObjective = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_GetServiceLevelObjectiveRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest> __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_UpdateServiceLevelObjectiveRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest.Parser));
static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_DeleteServiceLevelObjectiveRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest.Parser));
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_CreateService = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(
grpc::MethodType.Unary,
__ServiceName,
"CreateService",
__Marshaller_google_monitoring_v3_CreateServiceRequest,
__Marshaller_google_monitoring_v3_Service);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_GetService = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(
grpc::MethodType.Unary,
__ServiceName,
"GetService",
__Marshaller_google_monitoring_v3_GetServiceRequest,
__Marshaller_google_monitoring_v3_Service);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse> __Method_ListServices = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListServices",
__Marshaller_google_monitoring_v3_ListServicesRequest,
__Marshaller_google_monitoring_v3_ListServicesResponse);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_UpdateService = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(
grpc::MethodType.Unary,
__ServiceName,
"UpdateService",
__Marshaller_google_monitoring_v3_UpdateServiceRequest,
__Marshaller_google_monitoring_v3_Service);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteService = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"DeleteService",
__Marshaller_google_monitoring_v3_DeleteServiceRequest,
__Marshaller_google_protobuf_Empty);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_CreateServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(
grpc::MethodType.Unary,
__ServiceName,
"CreateServiceLevelObjective",
__Marshaller_google_monitoring_v3_CreateServiceLevelObjectiveRequest,
__Marshaller_google_monitoring_v3_ServiceLevelObjective);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_GetServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(
grpc::MethodType.Unary,
__ServiceName,
"GetServiceLevelObjective",
__Marshaller_google_monitoring_v3_GetServiceLevelObjectiveRequest,
__Marshaller_google_monitoring_v3_ServiceLevelObjective);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> __Method_ListServiceLevelObjectives = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ListServiceLevelObjectives",
__Marshaller_google_monitoring_v3_ListServiceLevelObjectivesRequest,
__Marshaller_google_monitoring_v3_ListServiceLevelObjectivesResponse);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_UpdateServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(
grpc::MethodType.Unary,
__ServiceName,
"UpdateServiceLevelObjective",
__Marshaller_google_monitoring_v3_UpdateServiceLevelObjectiveRequest,
__Marshaller_google_monitoring_v3_ServiceLevelObjective);
static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
grpc::MethodType.Unary,
__ServiceName,
"DeleteServiceLevelObjective",
__Marshaller_google_monitoring_v3_DeleteServiceLevelObjectiveRequest,
__Marshaller_google_protobuf_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Monitoring.V3.ServiceServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of ServiceMonitoringService</summary>
[grpc::BindServiceMethod(typeof(ServiceMonitoringService), "BindService")]
public abstract partial class ServiceMonitoringServiceBase
{
/// <summary>
/// Create a `Service`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Get the named `Service`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// List `Service`s for this workspace.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Update this `Service`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Soft delete this `Service`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Create a `ServiceLevelObjective` for the given `Service`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Get a `ServiceLevelObjective` by name.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// List the `ServiceLevelObjective`s for the given `Service`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Update the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Delete the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ServiceMonitoringService</summary>
public partial class ServiceMonitoringServiceClient : grpc::ClientBase<ServiceMonitoringServiceClient>
{
/// <summary>Creates a new client for ServiceMonitoringService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ServiceMonitoringServiceClient(grpc::ChannelBase channel) : base(channel)
{
}
/// <summary>Creates a new client for ServiceMonitoringService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ServiceMonitoringServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ServiceMonitoringServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ServiceMonitoringServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Create a `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.Service CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return CreateService(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Create a `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.Service CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateService, null, options, request);
}
/// <summary>
/// Create a `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> CreateServiceAsync(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return CreateServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Create a `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> CreateServiceAsync(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateService, null, options, request);
}
/// <summary>
/// Get the named `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.Service GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetService(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get the named `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.Service GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetService, null, options, request);
}
/// <summary>
/// Get the named `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> GetServiceAsync(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get the named `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> GetServiceAsync(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetService, null, options, request);
}
/// <summary>
/// List `Service`s for this workspace.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ListServicesResponse ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ListServices(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// List `Service`s for this workspace.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ListServicesResponse ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListServices, null, options, request);
}
/// <summary>
/// List `Service`s for this workspace.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServicesAsync(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ListServicesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// List `Service`s for this workspace.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServicesAsync(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListServices, null, options, request);
}
/// <summary>
/// Update this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.Service UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return UpdateService(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Update this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.Service UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UpdateService, null, options, request);
}
/// <summary>
/// Update this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> UpdateServiceAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return UpdateServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Update this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> UpdateServiceAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UpdateService, null, options, request);
}
/// <summary>
/// Soft delete this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return DeleteService(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Soft delete this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteService, null, options, request);
}
/// <summary>
/// Soft delete this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return DeleteServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Soft delete this `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteService, null, options, request);
}
/// <summary>
/// Create a `ServiceLevelObjective` for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return CreateServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Create a `ServiceLevelObjective` for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateServiceLevelObjective, null, options, request);
}
/// <summary>
/// Create a `ServiceLevelObjective` for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return CreateServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Create a `ServiceLevelObjective` for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateServiceLevelObjective, null, options, request);
}
/// <summary>
/// Get a `ServiceLevelObjective` by name.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get a `ServiceLevelObjective` by name.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetServiceLevelObjective, null, options, request);
}
/// <summary>
/// Get a `ServiceLevelObjective` by name.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Get a `ServiceLevelObjective` by name.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetServiceLevelObjective, null, options, request);
}
/// <summary>
/// List the `ServiceLevelObjective`s for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ListServiceLevelObjectives(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// List the `ServiceLevelObjective`s for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListServiceLevelObjectives, null, options, request);
}
/// <summary>
/// List the `ServiceLevelObjective`s for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectivesAsync(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ListServiceLevelObjectivesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// List the `ServiceLevelObjective`s for the given `Service`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectivesAsync(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListServiceLevelObjectives, null, options, request);
}
/// <summary>
/// Update the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return UpdateServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Update the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UpdateServiceLevelObjective, null, options, request);
}
/// <summary>
/// Update the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return UpdateServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Update the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UpdateServiceLevelObjective, null, options, request);
}
/// <summary>
/// Delete the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return DeleteServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Delete the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteServiceLevelObjective, null, options, request);
}
/// <summary>
/// Delete the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return DeleteServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Delete the given `ServiceLevelObjective`.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteServiceLevelObjective, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ServiceMonitoringServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ServiceMonitoringServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ServiceMonitoringServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_CreateService, serviceImpl.CreateService)
.AddMethod(__Method_GetService, serviceImpl.GetService)
.AddMethod(__Method_ListServices, serviceImpl.ListServices)
.AddMethod(__Method_UpdateService, serviceImpl.UpdateService)
.AddMethod(__Method_DeleteService, serviceImpl.DeleteService)
.AddMethod(__Method_CreateServiceLevelObjective, serviceImpl.CreateServiceLevelObjective)
.AddMethod(__Method_GetServiceLevelObjective, serviceImpl.GetServiceLevelObjective)
.AddMethod(__Method_ListServiceLevelObjectives, serviceImpl.ListServiceLevelObjectives)
.AddMethod(__Method_UpdateServiceLevelObjective, serviceImpl.UpdateServiceLevelObjective)
.AddMethod(__Method_DeleteServiceLevelObjective, serviceImpl.DeleteServiceLevelObjective).Build();
}
/// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static void BindService(grpc::ServiceBinderBase serviceBinder, ServiceMonitoringServiceBase serviceImpl)
{
serviceBinder.AddMethod(__Method_CreateService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.CreateService));
serviceBinder.AddMethod(__Method_GetService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.GetService));
serviceBinder.AddMethod(__Method_ListServices, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse>(serviceImpl.ListServices));
serviceBinder.AddMethod(__Method_UpdateService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.UpdateService));
serviceBinder.AddMethod(__Method_DeleteService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteService));
serviceBinder.AddMethod(__Method_CreateServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.CreateServiceLevelObjective));
serviceBinder.AddMethod(__Method_GetServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.GetServiceLevelObjective));
serviceBinder.AddMethod(__Method_ListServiceLevelObjectives, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse>(serviceImpl.ListServiceLevelObjectives));
serviceBinder.AddMethod(__Method_UpdateServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.UpdateServiceLevelObjective));
serviceBinder.AddMethod(__Method_DeleteServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteServiceLevelObjective));
}
}
}
#endregion
| 75.78133 | 411 | 0.739221 | [
"Apache-2.0"
] | garrettwong/google-cloud-dotnet | apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3/ServiceServiceGrpc.g.cs | 59,261 | C# |
using Adnc.Application.Shared.Dtos;
using System;
using System.Collections.Generic;
using System.Text;
namespace Adnc.Usr.Application.Dtos
{
/// <summary>
/// 角色,权限
/// </summary>
[Serializable]
public class RoleMenuCodesDto : BaseDto
{
/// <summary>
/// 菜单Code
/// </summary>
public string Code { get; set; }
/// <summary>
/// 角色ID
/// </summary>
public long RoleId { get; set; }
}
}
| 17.64 | 43 | 0.594104 | [
"MIT"
] | JavaScript-zt/Adnc | src/ServerApi/Portal/Adnc.Usr/Adnc.Usr.Application/Services/Role/Dtos/RoleMenuCodesDto.cs | 461 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
namespace Azure.AI.Language.QuestionAnswering.Models
{
/// <summary> Represent input text record to be queried. </summary>
public partial class TextRecord
{
/// <summary> Initializes a new instance of TextRecord. </summary>
/// <param name="id"> Unique identifier for the text record. </param>
/// <param name="text"> Text contents of the record. </param>
/// <exception cref="ArgumentNullException"> <paramref name="id"/> or <paramref name="text"/> is null. </exception>
public TextRecord(string id, string text)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
Id = id;
Text = text;
}
/// <summary> Unique identifier for the text record. </summary>
public string Id { get; }
/// <summary> Text contents of the record. </summary>
public string Text { get; }
}
}
| 30.925 | 123 | 0.577203 | [
"MIT"
] | EitanGayor/azure-sdk-for-net | sdk/cognitivelanguage/Azure.AI.Language.QuestionAnswering/src/Generated/Models/TextRecord.cs | 1,237 | C# |
using System.Runtime.Serialization;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "searchResult", Namespace = "")]
public class SearchResultItem : EntityBasic
{
/// <summary>
/// The score of the search result
/// </summary>
[DataMember(Name = "score")]
public float Score { get; set; }
}
} | 26.066667 | 58 | 0.575448 | [
"MIT"
] | Abhith/Umbraco-CMS | src/Umbraco.Web/Models/ContentEditing/SearchResultItem.cs | 393 | C# |
// Copyright (c) 2007 James Newton-King. All rights reserved.
// Use of this source code is governed by The MIT License,
// as found in the license.md file.
public class DeserializeCustomCreationConverter : TestFixtureBase
{
#region DeserializeCustomCreationConverterTypes
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}
public class Employee : Person
{
public string Department { get; set; }
public string JobTitle { get; set; }
}
public class PersonConverter : CustomCreationConverter<Person>
{
public override Person Create(Type type) =>
new Employee();
}
#endregion
[Fact]
public void Example()
{
#region DeserializeCustomCreationConverterUsage
var json = @"{
'Department': 'Furniture',
'JobTitle': 'Carpenter',
'FirstName': 'John',
'LastName': 'Joinery',
'BirthDate': '1983-02-02T00:00:00'
}";
var person = JsonConvert.DeserializeObject<Person>(json, new PersonConverter());
Console.WriteLine(person.GetType().Name);
// Employee
var employee = (Employee) person;
Console.WriteLine(employee.JobTitle);
// Carpenter
#endregion
Assert.Equal("Carpenter", employee.JobTitle);
}
} | 25.719298 | 88 | 0.603683 | [
"MIT"
] | SimonCropp/Argon | src/Tests/Documentation/Samples/Serializer/DeserializeCustomCreationConverter.cs | 1,468 | C# |
using UnityEngine;
using Facepunch;
using System.Collections.Generic;
namespace Tub.InputOutput
{
public class ButtonTrigger : Tub.InputOutput.Button, INetworkObserved
{
}
}
| 14.916667 | 70 | 0.793296 | [
"MIT"
] | Facepunch/Tub.Editor | Assets/Internal/Exported/Tub.InputOutput/ButtonTrigger.cs | 179 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Riganti.Utils.Infrastructure.Core;
using System.Collections.Generic;
namespace BcsAdmin.DAL.Api
{
public class BcsObject : IEntity<int>
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IList<int> Classifications { get; set; }
public IList<int> Organisms { get; set; }
public IList<ApiEntityAnotation> Annotations { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ApiEntityStatus? Status { get; set; }
}
}
| 28.409091 | 66 | 0.6624 | [
"Apache-2.0"
] | sybila/BCSParser | BcsAdmin.DAL/Api/BcsObject.cs | 627 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShooter : MonoBehaviour
{
public Transform cameraTransform;
public Transform shotSource;
public GameObject plagueHatProjectilePrefab;
public GameObject spiderHatProjectilePrefab;
// We need this function so that we can find out in what direction do we need to shoot
// from the shot source object so that the projectile goes in the direction that the
// user wanted based on his crosshair.
Vector3 GetThrowMovement()
{
Ray ray = new Ray(cameraTransform.position, cameraTransform.forward);
RaycastHit hit;
const float MAX_DIST = 1000;
// If there is an object in front of the crosshair, move towards it.
if(Physics.Raycast(ray, out hit, MAX_DIST))
{
return (hit.point - shotSource.position).normalized;
}
// Otherwise, just move towards a point that is MAX_DIST forward from the crosshair
// and in its direction.
else
{
return (cameraTransform.forward * MAX_DIST - shotSource.position).normalized;
}
}
void ShootProjectile(GameObject projectilePrefab)
{
Projectile projectile = Instantiate(projectilePrefab, shotSource.position, Quaternion.LookRotation(cameraTransform.forward)).GetComponent<Projectile>();
projectile.direction = GetThrowMovement();
}
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
ShootProjectile(plagueHatProjectilePrefab);
}
else if(Input.GetButtonDown("Fire2"))
{
ShootProjectile(spiderHatProjectilePrefab);
}
}
}
| 33.075472 | 160 | 0.67142 | [
"MIT"
] | frostblooded/ArenaShooterGame | Assets/Scripts/PlayerShooter.cs | 1,753 | C# |
namespace Gripper.ChromeDevTools.Target
{
using Newtonsoft.Json;
/// <summary>
/// Controls whether to discover available targets and notify via
/// `targetCreated/targetInfoChanged/targetDestroyed` events.
/// </summary>
public sealed class SetDiscoverTargetsCommand : ICommand
{
private const string ChromeRemoteInterface_CommandName = "Target.setDiscoverTargets";
[JsonIgnore]
public string CommandName
{
get { return ChromeRemoteInterface_CommandName; }
}
/// <summary>
/// Whether to discover available targets.
/// </summary>
[JsonProperty("discover")]
public bool Discover
{
get;
set;
}
}
public sealed class SetDiscoverTargetsCommandResponse : ICommandResponse<SetDiscoverTargetsCommand>
{
}
} | 26.939394 | 103 | 0.624297 | [
"MIT"
] | tomaskrupka/Gripper | src/Gripper.ChromeDevTools/Target/SetDiscoverTargetsCommand.cs | 889 | C# |
using Liquid.Repository;
using MediatR;
namespace Liquid.Domain.Extensions.Crud.Queries.GetAllGenericEntity
{
/// <summary>
/// Query to Get All Entities
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TIdentifier"></typeparam>
public class GetAllGenericEntityQuery<TEntity, TIdentifier> : IRequest<GetAllGenericEntityQueryResponse<TEntity>> where TEntity : LiquidEntity<TIdentifier>
{
/// <summary>
/// Initialize an instance of <see cref="GetAllGenericEntityQuery{TEntity, TIdentifier}"/>
/// </summary>
public GetAllGenericEntityQuery() { }
}
} | 35.777778 | 159 | 0.684783 | [
"MIT"
] | Control-Alt-Sistemas/Liquid-Application-Framework | src/Liquid.Domain.Extensions.Crud/Queries/GetAllGenericEntity/GetAllGenericEntityQuery.cs | 646 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Specification.Tests;
using Microsoft.EntityFrameworkCore.Specification.Tests.TestModels.Northwind;
using Microsoft.EntityFrameworkCore.Specification.Tests.TestUtilities.Xunit;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests
{
[MonoVersionCondition(Min = "4.2.0", SkipReason = "Queries fail on Mono < 4.2.0 due to differences in the implementation of LINQ")]
public class RowNumberPagingTest : QueryTestBase<NorthwindRowNumberPagingQuerySqlServerFixture>, IDisposable
{
public RowNumberPagingTest(NorthwindRowNumberPagingQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
//TestSqlLoggerFactory.CaptureOutput(testOutputHelper);
}
public void Dispose()
{
//Assert for all tests that OFFSET or FETCH is never used
Assert.DoesNotContain("OFFSET ", Sql);
Assert.DoesNotContain("FETCH ", Sql);
}
public override void Skip()
{
base.Skip();
Assert.Equal(
@"@__p_0: 5
SELECT [t].[CustomerID], [t].[Address], [t].[City], [t].[CompanyName], [t].[ContactName], [t].[ContactTitle], [t].[Country], [t].[Fax], [t].[Phone], [t].[PostalCode], [t].[Region]
FROM (
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], ROW_NUMBER() OVER(ORDER BY [c].[CustomerID]) AS [__RowNumber__]
FROM [Customers] AS [c]
) AS [t]
WHERE [t].[__RowNumber__] > @__p_0",
Sql);
}
public override void Skip_no_orderby()
{
base.Skip_no_orderby();
Assert.EndsWith(
@"@__p_0: 5
SELECT [t].[CustomerID], [t].[Address], [t].[City], [t].[CompanyName], [t].[ContactName], [t].[ContactTitle], [t].[Country], [t].[Fax], [t].[Phone], [t].[PostalCode], [t].[Region]
FROM (
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], ROW_NUMBER() OVER(ORDER BY @@RowCount) AS [__RowNumber__]
FROM [Customers] AS [c]
) AS [t]
WHERE [t].[__RowNumber__] > @__p_0",
Sql);
}
public override void Skip_Take()
{
base.Skip_Take();
Assert.Equal(
@"@__p_0: 5
@__p_1: 10
SELECT [t].[CustomerID], [t].[Address], [t].[City], [t].[CompanyName], [t].[ContactName], [t].[ContactTitle], [t].[Country], [t].[Fax], [t].[Phone], [t].[PostalCode], [t].[Region]
FROM (
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region], ROW_NUMBER() OVER(ORDER BY [c].[ContactName]) AS [__RowNumber__]
FROM [Customers] AS [c]
) AS [t]
WHERE ([t].[__RowNumber__] > @__p_0) AND ([t].[__RowNumber__] <= (@__p_0 + @__p_1))",
Sql);
}
public override void Join_Customers_Orders_Skip_Take()
{
base.Join_Customers_Orders_Skip_Take();
Assert.Equal(
@"@__p_0: 10
@__p_1: 5
SELECT [t].[ContactName], [t].[OrderID]
FROM (
SELECT [c].[ContactName], [o].[OrderID], ROW_NUMBER() OVER(ORDER BY [o].[OrderID]) AS [__RowNumber__]
FROM [Customers] AS [c]
INNER JOIN [Orders] AS [o] ON [c].[CustomerID] = [o].[CustomerID]
) AS [t]
WHERE ([t].[__RowNumber__] > @__p_0) AND ([t].[__RowNumber__] <= (@__p_0 + @__p_1))",
Sql);
}
public override void Join_Customers_Orders_Projection_With_String_Concat_Skip_Take()
{
base.Join_Customers_Orders_Projection_With_String_Concat_Skip_Take();
Assert.Equal(
@"@__p_0: 10
@__p_1: 5
SELECT [t].[c0], [t].[OrderID]
FROM (
SELECT ([c].[ContactName] + N' ') + [c].[ContactTitle] AS [c0], [o].[OrderID], ROW_NUMBER() OVER(ORDER BY [o].[OrderID]) AS [__RowNumber__]
FROM [Customers] AS [c]
INNER JOIN [Orders] AS [o] ON [c].[CustomerID] = [o].[CustomerID]
) AS [t]
WHERE ([t].[__RowNumber__] > @__p_0) AND ([t].[__RowNumber__] <= (@__p_0 + @__p_1))",
Sql);
}
public override void Take_Skip()
{
base.Take_Skip();
Assert.Equal(@"@__p_0: 10
@__p_1: 5
SELECT [t0].*
FROM (
SELECT [t].*, ROW_NUMBER() OVER(ORDER BY [t].[ContactName]) AS [__RowNumber__]
FROM (
SELECT TOP(@__p_0) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
ORDER BY [c].[ContactName]
) AS [t]
) AS [t0]
WHERE [t0].[__RowNumber__] > @__p_1",
Sql);
}
public override void Take_Skip_Distinct()
{
base.Take_Skip_Distinct();
Assert.Equal(
@"@__p_0: 10
@__p_1: 5
SELECT DISTINCT [t0].*
FROM (
SELECT [t1].*
FROM (
SELECT [t].*, ROW_NUMBER() OVER(ORDER BY [t].[ContactName]) AS [__RowNumber__]
FROM (
SELECT TOP(@__p_0) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
ORDER BY [c].[ContactName]
) AS [t]
) AS [t1]
WHERE [t1].[__RowNumber__] > @__p_1
) AS [t0]",
Sql);
}
public override void Take_skip_null_coalesce_operator()
{
base.Take_skip_null_coalesce_operator();
Assert.Equal(@"@__p_0: 10
@__p_1: 5
SELECT DISTINCT [t0].*
FROM (
SELECT [t1].*
FROM (
SELECT [t].*, ROW_NUMBER() OVER(ORDER BY COALESCE([t].[Region], N'ZZ')) AS [__RowNumber__]
FROM (
SELECT TOP(@__p_0) [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
ORDER BY COALESCE([c].[Region], N'ZZ')
) AS [t]
) AS [t1]
WHERE [t1].[__RowNumber__] > @__p_1
) AS [t0]",
Sql);
}
public override void Select_take_skip_null_coalesce_operator()
{
base.Select_take_skip_null_coalesce_operator();
Assert.Equal(@"@__p_0: 10
@__p_1: 5
SELECT [t0].*
FROM (
SELECT [t].*, ROW_NUMBER() OVER(ORDER BY [Coalesce]) AS [__RowNumber__]
FROM (
SELECT TOP(@__p_0) [c].[CustomerID], [c].[CompanyName], COALESCE([c].[Region], N'ZZ') AS [Coalesce]
FROM [Customers] AS [c]
ORDER BY [Coalesce]
) AS [t]
) AS [t0]
WHERE [t0].[__RowNumber__] > @__p_1",
Sql);
}
public override void String_Contains_Literal()
{
AssertQuery<Customer>(
cs => cs.Where(c => c.ContactName.Contains("M")), // case-insensitive
cs => cs.Where(c => c.ContactName.Contains("M") || c.ContactName.Contains("m")), // case-sensitive
entryCount: 34);
Assert.Equal(
@"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[ContactName] LIKE (N'%' + N'M') + N'%'",
Sql);
}
public override void String_Contains_MethodCall()
{
AssertQuery<Customer>(
cs => cs.Where(c => c.ContactName.Contains(LocalMethod1())), // case-insensitive
cs => cs.Where(c => c.ContactName.Contains(LocalMethod1().ToLower()) || c.ContactName.Contains(LocalMethod1().ToUpper())), // case-sensitive
entryCount: 34);
Assert.Equal(
@"@__LocalMethod1_0: M
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[ContactName] LIKE (N'%' + @__LocalMethod1_0) + N'%'",
Sql);
}
private const string FileLineEnding = @"
";
private static string Sql => TestSqlLoggerFactory.Sql.Replace(Environment.NewLine, FileLineEnding);
}
}
| 37.037815 | 249 | 0.570278 | [
"Apache-2.0"
] | davidroth/EntityFrameworkCore | test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/RowNumberPagingTest.cs | 8,815 | C# |
using System;
namespace PubNubAPI
{
public class PNPushRemoveChannelResult: PNResult
{
public string Message {get; set;}
}
} | 16.111111 | 52 | 0.675862 | [
"MIT"
] | BananiumLabs/bullet-heaven | BulletHeaven/Assets/PubNub/Models/Consumer/Push/PNPushRemoveChannelResult.cs | 145 | 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 SRD.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", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Sql {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Sql() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SRD.Properties.Sql", typeof(Sql).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to SELECT A.ApplicationID, A.Name AS [Application],
/// M.Name AS [Manufacturer],
/// L.Name AS [Language],
/// A.OSType,
/// A.ApplicationType,
/// A.OverridesApplicationID,
/// A.IsOS,
/// A.IsGroup,
/// A.IsBundle,
/// A.IsHidden,
/// A.NoLicenseRequired,
/// A.GloballyGeneratedApplication,
/// AF.Name AS [Family Name],
/// A.EditionIndex,
/// A.VersionIndex,
/// A.CompatibleWithID,
/// A.NoMetering,
/// A.SRSUpdateDate,
/// [rest of string was truncated]";.
/// </summary>
internal static string GetApplicationListAll {
get {
return ResourceManager.GetString("GetApplicationListAll", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT TOP 0 A.ApplicationID, A.Name AS [Application],
/// M.Name AS [Manufacturer],
/// L.Name AS [Language],
/// A.OSType,
/// A.ApplicationType,
/// A.OverridesApplicationID,
/// A.IsOS,
/// A.IsGroup,
/// A.IsBundle,
/// A.IsHidden,
/// A.NoLicenseRequired,
/// A.GloballyGeneratedApplication,
/// AF.Name AS [Family Name],
/// A.EditionIndex,
/// A.VersionIndex,
/// A.CompatibleWithID,
/// A.NoMetering,
/// A.SRSUpdateDate, [rest of string was truncated]";.
/// </summary>
internal static string GetApplicationListEmpty {
get {
return ResourceManager.GetString("GetApplicationListEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT TOP 100 A.ApplicationID, A.Name AS [Application],
/// M.Name AS [Manufacturer],
/// L.Name AS [Language],
/// A.OSType,
/// A.ApplicationType,
/// A.OverridesApplicationID,
/// A.IsOS,
/// A.IsGroup,
/// A.IsBundle,
/// A.IsHidden,
/// A.NoLicenseRequired,
/// A.GloballyGeneratedApplication,
/// AF.Name AS [Family Name],
/// A.EditionIndex,
/// A.VersionIndex,
/// A.CompatibleWithID,
/// A.NoMetering,
/// A.SRSUpdateDat [rest of string was truncated]";.
/// </summary>
internal static string GetApplicationListTop100 {
get {
return ResourceManager.GetString("GetApplicationListTop100", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DECLARE @return_value VARCHAR
///EXEC @return_value = [SnowLicenseManager].[dbo].[ApplicationRuleList]
/// @ApplicationID = @AppID.
/// </summary>
internal static string GetApplicationRules {
get {
return ResourceManager.GetString("GetApplicationRules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT A.ApplicationID, A.Name AS [Application],
/// M.Name AS [Manufacturer],
/// L.Name AS [Language],
/// A.OSType,
/// A.ApplicationType,
/// A.OverridesApplicationID,
/// A.IsOS,
/// A.IsGroup,
/// A.IsBundle,
/// A.IsHidden,
/// A.NoLicenseRequired,
/// A.GloballyGeneratedApplication,
/// AF.Name AS [Family Name],
/// A.EditionIndex,
/// A.VersionIndex,
/// A.CompatibleWithID,
/// A.NoMetering,
/// A.SRSUpdateDate,
/// [rest of string was truncated]";.
/// </summary>
internal static string GetApplicationSearch {
get {
return ResourceManager.GetString("GetApplicationSearch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT U.CID,
/// S.*
///FROM SnowLicenseManager.dbo.tblSoftwareCIDUnassigned U
/// JOIN SnowLicenseManager.dbo.tblSoftware S ON S.SoftwareCheckSum = U.SoftwareCheckSum;.
/// </summary>
internal static string GetUnassignedApplicationListAll {
get {
return ResourceManager.GetString("GetUnassignedApplicationListAll", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT AC.ComputerName,
/// FS.AppName,
/// FS.AppVersion,
/// FS.AppManufacturer,
/// FS.AppIsOs,
/// FS.SwName,
/// FS.SwManufacturer,
/// FS.SwVersion,
/// FS.SwPathName,
/// FS.SwFileName,
/// FS.SwFileSize,
/// FS.SwInstallDate,
/// FS.SwIsLocal,
/// FS.SwIsMSI,
/// FS.SwLicenseNumber,
/// FS.SwLastScanned
///FROM SnowInventory.inv.vFilterSoftware FS LEFT JOIN SnowInventory.inv.vAllComputers AC ON AC.ComputerID = FS.ComputerID
///WHERE {ColumnName} = @Searc [rest of string was truncated]";.
/// </summary>
internal static string GetUnassignedApplicationListComp {
get {
return ResourceManager.GetString("GetUnassignedApplicationListComp", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT TOP 0 U.CID,
/// S.*
///FROM SnowLicenseManager.dbo.tblSoftwareCIDUnassigned U
/// JOIN SnowLicenseManager.dbo.tblSoftware S ON S.SoftwareCheckSum = U.SoftwareCheckSum;.
/// </summary>
internal static string GetUnassignedApplicationListEmpty {
get {
return ResourceManager.GetString("GetUnassignedApplicationListEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SELECT U.CID,
/// S.*
///FROM SnowLicenseManager.dbo.tblSoftwareCIDUnassigned U
/// JOIN SnowLicenseManager.dbo.tblSoftware S ON S.SoftwareCheckSum = U.SoftwareCheckSum
///WHERE {ColumnName} {Operator} @SearchTerm.
/// </summary>
internal static string GetUnassignedApplicationListSearch {
get {
return ResourceManager.GetString("GetUnassignedApplicationListSearch", resourceCulture);
}
}
}
}
| 40.930328 | 157 | 0.531891 | [
"MIT"
] | goosetuv/Snow-Recognition-Database | Properties/Sql.Designer.cs | 9,989 | C# |
/*
* Copyright © 2016-2018 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using EliteDangerousCore.DB;
using QuickJSON;
using System.Linq;
namespace EliteDangerousCore.JournalEvents
{
[JournalEntryType(JournalTypeEnum.SupercruiseEntry)]
public class JournalSupercruiseEntry : JournalEntry, IShipInformation
{
public JournalSupercruiseEntry(JObject evt ) : base(evt, JournalTypeEnum.SupercruiseEntry)
{
StarSystem = evt["StarSystem"].Str();
SystemAddress = evt["SystemAddress"].LongNull();
Taxi = evt["Taxi"].BoolNull();
Multicrew = evt["Multicrew"].BoolNull();
}
public string StarSystem { get; set; }
public long? SystemAddress { get; set; }
public bool? Taxi { get; set; } //4.0 alpha 4
public bool? Multicrew { get; set; }
public override void FillInformation(ISystem sys, string whereami, out string info, out string detailed)
{
info = StarSystem;
detailed = "";
}
public void ShipInformation(ShipInformationList shp, string whereami, ISystem system)
{
shp.SupercruiseEntry(this);
}
}
[JournalEntryType(JournalTypeEnum.SupercruiseExit)]
public class JournalSupercruiseExit : JournalEntry, IBodyNameAndID
{
public JournalSupercruiseExit(JObject evt) : base(evt, JournalTypeEnum.SupercruiseExit)
{
StarSystem = evt["StarSystem"].Str();
SystemAddress = evt["SystemAddress"].LongNull();
Body = evt["Body"].Str();
BodyID = evt["BodyID"].IntNull();
BodyType = JournalFieldNaming.NormaliseBodyType(evt["BodyType"].Str());
Taxi = evt["Taxi"].BoolNull();
Multicrew = evt["Multicrew"].BoolNull();
}
public string StarSystem { get; set; }
public long? SystemAddress { get; set; }
public string Body { get; set; }
public int? BodyID { get; set; }
public string BodyType { get; set; }
public string BodyDesignation { get; set; }
public bool? Taxi { get; set; } //4.0 alpha 4
public bool? Multicrew { get; set; }
public override void FillInformation(ISystem sys, string whereami, out string info, out string detailed)
{
info = BaseUtils.FieldBuilder.Build("At ".T(EDCTx.JournalSupercruiseExit_At), Body, "< in ".T(EDCTx.JournalSupercruiseExit_in), StarSystem, "Type: ".T(EDCTx.JournalEntry_Type), BodyType);
detailed = "";
}
}
}
| 39.059524 | 200 | 0.626333 | [
"Apache-2.0"
] | EDDiscovery/EliteDangerous | EliteDangerous/JournalEvents/JournalSupercruise.cs | 3,201 | C# |
#region License
/* **************************************************************************************
* Copyright (c) Librame Pong All rights reserved.
*
* https://github.com/librame
*
* You must not remove this notice, or any other, from this software.
* **************************************************************************************/
#endregion
using Librame.AspNetCore.Web.Builders;
using Librame.Extensions;
using Librame.Extensions.Core.Builders;
using Librame.Extensions.Core.Options;
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Web 构建器静态扩展。
/// </summary>
public static class WebBuilderExtensions
{
/// <summary>
/// 启用支持泛型控制器。
/// </summary>
/// <param name="builder">给定的 <see cref="IWebBuilder"/>。</param>
/// <returns>返回 <see cref="IWebBuilder"/>。</returns>
public static IWebBuilder EnableSupportedGenericController(this IWebBuilder builder)
=> builder.SetProperty(p => p.SupportedGenericController, true);
/// <summary>
/// 添加 Web 扩展(支持多次添加,从第二次开始,返回适配器模式)。
/// </summary>
/// <param name="parentBuilder">给定的父级 <see cref="IExtensionBuilder"/>。</param>
/// <param name="configureDependency">给定的配置依赖动作方法(可选)。</param>
/// <param name="builderFactory">给定创建 Web 构建器的工厂方法(可选)。</param>
/// <returns>返回 <see cref="IWebBuilder"/>。</returns>
public static IWebBuilder AddWeb(this IExtensionBuilder parentBuilder,
Action<WebBuilderDependency> configureDependency = null,
Func<IExtensionBuilder, WebBuilderDependency, IWebBuilder> builderFactory = null)
=> parentBuilder.AddWeb<WebBuilderDependency>(configureDependency, builderFactory);
/// <summary>
/// 添加 Web 扩展(支持多次添加,从第二次开始,返回适配器模式)。
/// </summary>
/// <typeparam name="TDependency">指定的依赖类型。</typeparam>
/// <param name="parentBuilder">给定的父级 <see cref="IExtensionBuilder"/>。</param>
/// <param name="configureDependency">给定的配置依赖动作方法(可选)。</param>
/// <param name="builderFactory">给定创建 Web 构建器的工厂方法(可选)。</param>
/// <returns>返回 <see cref="IWebBuilder"/>。</returns>
[SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static IWebBuilder AddWeb<TDependency>(this IExtensionBuilder parentBuilder,
Action<TDependency> configureDependency = null,
Func<IExtensionBuilder, TDependency, IWebBuilder> builderFactory = null)
where TDependency : WebBuilderDependency
{
// 如果已经添加过 Web 扩展,则直接返回适配器模式
if (parentBuilder.TryGetBuilder(out IWebBuilder webBuilder))
return new WebBuilderAdapter(parentBuilder, webBuilder);
// Clear Options Cache
ConsistencyOptionsCache.TryRemove<WebBuilderOptions>();
// Add Builder Dependency
var dependency = parentBuilder.AddBuilderDependency(out var dependencyType, configureDependency);
parentBuilder.Services.TryAddReferenceBuilderDependency<WebBuilderDependency>(dependency, dependencyType);
// Create Builder
return builderFactory.NotNullOrDefault(()
=> (b, d) => new WebBuilder(b, d)).Invoke(parentBuilder, dependency);
}
}
}
| 42.6125 | 118 | 0.626283 | [
"MIT"
] | gitter-badger/aspnetcore | src/Librame.AspNetCore.Web/Builders/WebBuilderExtensions.cs | 3,797 | C# |
using Kaiyuanshe.OpenHackathon.Server.Biz;
using Kaiyuanshe.OpenHackathon.Server.Models;
using Kaiyuanshe.OpenHackathon.Server.ResponseBuilder;
using Kaiyuanshe.OpenHackathon.Server.Swagger;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
namespace Kaiyuanshe.OpenHackathon.Server.Controllers
{
public class UserController : HackathonControllerBase
{
public IUserManagement UserManagement { get; set; }
public IResponseBuilder ResponseBuilder { get; set; }
#region Authing
/// <summary>
/// Post the data from Authing after completing the Login process. Open hackathon API
/// relies on the data for user profile and the token.
/// </summary>
/// <param name="parameter"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost]
[SwaggerErrorResponse(400)]
[Route("login")]
public async Task<object> Authing([FromBody] UserInfo parameter,
CancellationToken cancellationToken)
{
var tokenStatus = await UserManagement.ValidateTokenRemotelyAsync(parameter.UserPoolId, parameter.Token, cancellationToken);
if (!tokenStatus.Status.GetValueOrDefault(false))
{
// token invalid
return BadRequest(string.Format(
Resources.Auth_Token_ValidateRemoteFailed,
tokenStatus.Code.GetValueOrDefault(0),
tokenStatus.Message));
}
await UserManagement.AuthingAsync(parameter, cancellationToken);
return Ok(parameter);
}
#endregion
#region GetUserById
/// <summary>
/// Get user info by user id. The info is synced from Authing during login.
/// </summary>
/// <param name="userId" example="1">unique id of the user</param>
/// <param name="cancellationToken"></param>
/// <returns>the user</returns>
/// <response code="200">Success. The response describes a user.</response>
[HttpGet]
[ProducesResponseType(typeof(UserInfo), StatusCodes.Status200OK)]
[SwaggerErrorResponse(404)]
[Route("user/{userId}")]
public async Task<object> GetUserById([FromRoute, Required] string userId,
CancellationToken cancellationToken)
{
var userInfo = await UserManagement.GetUserByIdAsync(userId, cancellationToken);
return Ok(userInfo);
}
#endregion
}
}
| 39 | 137 | 0.627106 | [
"MIT"
] | think-in-universe/open-hackathon | src/open-hackathon-server/Kaiyuanshe.OpenHackathon.Server/Controllers/UserController.cs | 2,732 | C# |
namespace _02.Bank_accounts
{
public abstract class Account : Bank, IAccount
{
public Customer Customer { get; set; }
public decimal Balance { get; set; }
public decimal InterestRate { get; set; }
public Account(Bank inputBank)
: base (inputBank.BankName)
{
}
public Account(Bank inputBank, Customer inputCustomer, decimal inputBalance, decimal inputInterestRate)
: this(inputBank)
{
this.Customer = inputCustomer;
this.Balance = inputBalance;
this.InterestRate = inputInterestRate;
}
public abstract decimal CalculateInterestAmount(int months);
}
} | 25.714286 | 111 | 0.6 | [
"MIT"
] | fr0wsTyl/TelerikAcademy-2015 | Telerik - C# OOP/Old Homeworks/05. OOP Principles - Part 2/02. Bank accounts/Account.cs | 720 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.fund.trans.trusteeship.account.create
/// </summary>
public class AlipayFundTransTrusteeshipAccountCreateRequest : IAlipayRequest<AlipayFundTransTrusteeshipAccountCreateResponse>
{
/// <summary>
/// 创建托管账号接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.fund.trans.trusteeship.account.create";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.064516 | 129 | 0.554196 | [
"MIT"
] | Msy1989/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayFundTransTrusteeshipAccountCreateRequest.cs | 2,878 | C# |
#pragma checksum "E:\BIS SCHOOL\SUMMER 2020\CIS174Advanced C#.NetCore\Code\AssignmentsAtanga\Areas\Users\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "133a33518c4528443463b520b41b5ecef54e39d2"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Users_Views_Home_Index), @"mvc.1.0.view", @"/Areas/Users/Views/Home/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"133a33518c4528443463b520b41b5ecef54e39d2", @"/Areas/Users/Views/Home/Index.cshtml")]
public class Areas_Users_Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 2 "E:\BIS SCHOOL\SUMMER 2020\CIS174Advanced C#.NetCore\Code\AssignmentsAtanga\Areas\Users\Views\Home\Index.cshtml"
ViewBag.Title = "User Page";
Layout = "~/Views/Shared/_Layout.cshtml";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>User Area</h1>\r\n\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 53.425532 | 213 | 0.748706 | [
"BSD-2-Clause"
] | eatanga/Advanced-C--Asp.NetCore | Code/AssignmentsAtanga/obj/Debug/netcoreapp3.1/Razor/Areas/Users/Views/Home/Index.cshtml.g.cs | 2,511 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// queue to provide sliding window capabilities for auto size functionality
/// It provides caching capabilities (either the first N objects in a group
/// or all the objects in a group)
/// </summary>
internal sealed class OutputGroupQueue
{
/// <summary>
/// create a grouping cache
/// </summary>
/// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param>
/// <param name="objectCount">Max number of objects to be cached.</param>
internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification callBack, int objectCount)
{
_notificationCallBack = callBack;
_objectCount = objectCount;
}
/// <summary>
/// create a time-bounded grouping cache
/// </summary>
/// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param>
/// <param name="groupingDuration">Max amount of time to cache of objects.</param>
internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification callBack, TimeSpan groupingDuration)
{
_notificationCallBack = callBack;
_groupingDuration = groupingDuration;
}
/// <summary>
/// add an object to the cache
/// </summary>
/// <param name="o">Object to add.</param>
/// <returns>Objects the cache needs to return. It can be null.</returns>
internal List<PacketInfoData> Add(PacketInfoData o)
{
FormatStartData fsd = o as FormatStartData;
if (fsd != null)
{
// just cache the reference (used during the notification call)
_formatStartData = fsd;
}
UpdateObjectCount(o);
// STATE TRANSITION: we are not processing and we start
if (!_processingGroup && (o is GroupStartData))
{
// just set the flag and start caching
_processingGroup = true;
_currentObjectCount = 0;
if (_groupingDuration > TimeSpan.MinValue)
{
_groupingTimer = Stopwatch.StartNew();
}
_queue.Enqueue(o);
return null;
}
// STATE TRANSITION: we are processing and we stop
if (_processingGroup &&
((o is GroupEndData) ||
(_objectCount > 0) && (_currentObjectCount >= _objectCount)) ||
((_groupingTimer != null) && (_groupingTimer.Elapsed > _groupingDuration))
)
{
// reset the object count
_currentObjectCount = 0;
if (_groupingTimer != null)
{
_groupingTimer.Stop();
_groupingTimer = null;
}
// add object to queue, to be picked up
_queue.Enqueue(o);
// we are at the end of a group, drain the queue
Notify();
_processingGroup = false;
List<PacketInfoData> retVal = new List<PacketInfoData>();
while (_queue.Count > 0)
{
retVal.Add(_queue.Dequeue());
}
return retVal;
}
// NO STATE TRANSITION: check the state we are in
if (_processingGroup)
{
// we are in the caching state
_queue.Enqueue(o);
return null;
}
// we are not processing, so just return it
List<PacketInfoData> ret = new List<PacketInfoData>();
ret.Add(o);
return ret;
}
private void UpdateObjectCount(PacketInfoData o)
{
// add only of it's not a control message
// and it's not out of band
FormatEntryData fed = o as FormatEntryData;
if (fed == null || fed.outOfBand)
return;
_currentObjectCount++;
}
private void Notify()
{
if (_notificationCallBack == null)
return;
// filter out the out of band data, since they do not participate in the
// auto resize algorithm
List<PacketInfoData> validObjects = new List<PacketInfoData>();
foreach (PacketInfoData x in _queue)
{
FormatEntryData fed = x as FormatEntryData;
if (fed != null && fed.outOfBand)
continue;
validObjects.Add(x);
}
_notificationCallBack(_formatStartData, validObjects);
}
/// <summary>
/// remove a single object from the queue
/// </summary>
/// <returns>Object retrieved, null if queue is empty.</returns>
internal PacketInfoData Dequeue()
{
if (_queue.Count == 0)
return null;
return _queue.Dequeue();
}
/// <summary>
/// queue to store the currently cached objects
/// </summary>
private Queue<PacketInfoData> _queue = new Queue<PacketInfoData>();
/// <summary>
/// number of objects to compute the best fit.
/// Zero: all the objects
/// a positive number N: use the first N
/// </summary>
private int _objectCount = 0;
/// <summary>
/// Maximum amount of time for record processing to compute the best fit.
/// MaxValue: all the objects.
/// A positive timespan: use all objects that have been processed within the timeframe.
/// </summary>
private TimeSpan _groupingDuration = TimeSpan.MinValue;
private Stopwatch _groupingTimer = null;
/// <summary>
/// notification callback to be called when we have accumulated enough
/// data to compute a hint
/// </summary>
private FormattedObjectsCache.ProcessCachedGroupNotification _notificationCallBack = null;
/// <summary>
/// reference kept to be used during notification
/// </summary>
private FormatStartData _formatStartData = null;
/// <summary>
/// state flag to signal we are queuing
/// </summary>
private bool _processingGroup = false;
/// <summary>
/// current object count
/// </summary>
private int _currentObjectCount = 0;
}
/// <summary>
/// facade class managing the front end and the autosize cache
/// </summary>
internal sealed class FormattedObjectsCache
{
/// <summary>
/// delegate to allow notifications when the autosize queue is about to be drained
/// </summary>
/// <param name="formatStartData">Current Fs control message.</param>
/// <param name="objects">Enumeration of PacketInfoData objects.</param>
internal delegate void ProcessCachedGroupNotification(FormatStartData formatStartData, List<PacketInfoData> objects);
/// <summary>
/// decide right away if we need a front end cache (e.g. printing)
/// </summary>
/// <param name="cacheFrontEnd">If true, create a front end cache object.</param>
internal FormattedObjectsCache(bool cacheFrontEnd)
{
if (cacheFrontEnd)
_frontEndQueue = new Queue<PacketInfoData>();
}
/// <summary>
/// if needed, add a back end autosize (grouping) cache
/// </summary>
/// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param>
/// <param name="objectCount">Max number of objects to be cached.</param>
internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, int objectCount)
{
if (callBack != null)
_groupQueue = new OutputGroupQueue(callBack, objectCount);
}
/// <summary>
/// if needed, add a back end autosize (grouping) cache
/// </summary>
/// <param name="callBack">Notification callback to be called when the desired number of objects is reached.</param>
/// <param name="groupingDuration">Max amount of time to cache of objects.</param>
internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, TimeSpan groupingDuration)
{
if (callBack != null)
_groupQueue = new OutputGroupQueue(callBack, groupingDuration);
}
/// <summary>
/// add an object to the cache. the behavior depends on the object added, the
/// objects already in the cache and the cache settings
/// </summary>
/// <param name="o">Object to add.</param>
/// <returns>List of objects the cache is flushing.</returns>
internal List<PacketInfoData> Add(PacketInfoData o)
{
// if neither there, pass thru
if (_frontEndQueue == null && _groupQueue == null)
{
List<PacketInfoData> retVal = new List<PacketInfoData>();
retVal.Add(o);
return retVal;
}
// if front present, add to front
if (_frontEndQueue != null)
{
_frontEndQueue.Enqueue(o);
return null;
}
// if back only, add to back
return _groupQueue.Add(o);
}
/// <summary>
/// remove all the objects from the cache
/// </summary>
/// <returns>All the objects that were in the cache.</returns>
internal List<PacketInfoData> Drain()
{
// if neither there,we did not cache at all
if (_frontEndQueue == null && _groupQueue == null)
{
return null;
}
List<PacketInfoData> retVal = new List<PacketInfoData>();
if (_frontEndQueue != null)
{
if (_groupQueue == null)
{
// drain the front queue and return the data
while (_frontEndQueue.Count > 0)
retVal.Add(_frontEndQueue.Dequeue());
return retVal;
}
// move from the front to the back queue
while (_frontEndQueue.Count > 0)
{
List<PacketInfoData> groupQueueOut = _groupQueue.Add(_frontEndQueue.Dequeue());
if (groupQueueOut != null)
foreach (PacketInfoData x in groupQueueOut)
retVal.Add(x);
}
}
// drain the back queue
while (true)
{
PacketInfoData obj = _groupQueue.Dequeue();
if (obj == null)
break;
retVal.Add(obj);
}
return retVal;
}
/// <summary>
/// front end queue (if present, cache ALL, if not, bypass)
/// </summary>
private Queue<PacketInfoData> _frontEndQueue;
/// <summary>
/// back end grouping queue
/// </summary>
private OutputGroupQueue _groupQueue = null;
}
}
| 34.669617 | 125 | 0.545988 | [
"MIT"
] | renovate-mirrors/PowerShell | src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs | 11,753 | C# |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using dnlib.Utils;
using dnlib.W32Resources;
using dnlib.IO;
using dnlib.Threading;
namespace dnlib.PE {
/// <summary>
/// Image layout
/// </summary>
public enum ImageLayout {
/// <summary>
/// Use this if the PE file has a normal structure (eg. it's been read from a file on disk)
/// </summary>
File,
/// <summary>
/// Use this if the PE file has been loaded into memory by the OS PE file loader
/// </summary>
Memory,
}
/// <summary>
/// Accesses a PE file
/// </summary>
public sealed class PEImage : IPEImage {
// Default to false because an OS loaded PE image may contain memory holes. If there
// are memory holes, other code (eg. .NET resource creator) must verify that all memory
// is available, which will be slower.
const bool USE_MEMORY_LAYOUT_WITH_MAPPED_FILES = false;
static readonly IPEType MemoryLayout = new MemoryPEType();
static readonly IPEType FileLayout = new FilePEType();
IImageStream imageStream;
IImageStreamCreator imageStreamCreator;
IPEType peType;
PEInfo peInfo;
UserValue<Win32Resources> win32Resources;
#if THREAD_SAFE
readonly Lock theLock = Lock.Create();
#endif
sealed class FilePEType : IPEType {
/// <inheritdoc/>
public RVA ToRVA(PEInfo peInfo, FileOffset offset) {
return peInfo.ToRVA(offset);
}
/// <inheritdoc/>
public FileOffset ToFileOffset(PEInfo peInfo, RVA rva) {
return peInfo.ToFileOffset(rva);
}
}
sealed class MemoryPEType : IPEType {
/// <inheritdoc/>
public RVA ToRVA(PEInfo peInfo, FileOffset offset) {
return (RVA)offset;
}
/// <inheritdoc/>
public FileOffset ToFileOffset(PEInfo peInfo, RVA rva) {
return (FileOffset)rva;
}
}
/// <inheritdoc/>
public bool IsFileImageLayout {
get { return peType is FilePEType; }
}
/// <inheritdoc/>
public bool MayHaveInvalidAddresses {
get { return !IsFileImageLayout; }
}
/// <inheritdoc/>
public string FileName {
get { return imageStreamCreator.FileName; }
}
/// <inheritdoc/>
public ImageDosHeader ImageDosHeader {
get { return peInfo.ImageDosHeader; }
}
/// <inheritdoc/>
public ImageNTHeaders ImageNTHeaders {
get { return peInfo.ImageNTHeaders; }
}
/// <inheritdoc/>
public IList<ImageSectionHeader> ImageSectionHeaders {
get { return peInfo.ImageSectionHeaders; }
}
/// <inheritdoc/>
public Win32Resources Win32Resources {
get { return win32Resources.Value; }
set {
IDisposable origValue = null;
if (win32Resources.IsValueInitialized) {
origValue = win32Resources.Value;
if (origValue == value)
return;
}
win32Resources.Value = value;
if (origValue != null)
origValue.Dispose();
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="imageStreamCreator">The PE stream creator</param>
/// <param name="imageLayout">Image layout</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(IImageStreamCreator imageStreamCreator, ImageLayout imageLayout, bool verify) {
try {
this.imageStreamCreator = imageStreamCreator;
this.peType = ConvertImageLayout(imageLayout);
ResetReader();
this.peInfo = new PEInfo(imageStream, verify);
Initialize();
}
catch {
Dispose();
throw;
}
}
void Initialize() {
win32Resources.ReadOriginalValue = () => {
var dataDir = peInfo.ImageNTHeaders.OptionalHeader.DataDirectories[2];
if (dataDir.VirtualAddress == 0 || dataDir.Size == 0)
return null;
return new Win32ResourcesPE(this);
};
#if THREAD_SAFE
win32Resources.Lock = theLock;
#endif
}
static IPEType ConvertImageLayout(ImageLayout imageLayout) {
switch (imageLayout) {
case ImageLayout.File: return FileLayout;
case ImageLayout.Memory: return MemoryLayout;
default: throw new ArgumentException("imageLayout");
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileName">Name of the file</param>
/// <param name="mapAsImage"><c>true</c> if we should map it as an executable</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(string fileName, bool mapAsImage, bool verify)
: this(ImageStreamCreator.Create(fileName, mapAsImage), mapAsImage ? ImageLayout.Memory : ImageLayout.File, verify) {
try {
if (mapAsImage && imageStreamCreator is MemoryMappedFileStreamCreator) {
((MemoryMappedFileStreamCreator)imageStreamCreator).Length = peInfo.GetImageSize();
ResetReader();
}
}
catch {
Dispose();
throw;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileName">Name of the file</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(string fileName, bool verify)
: this(fileName, USE_MEMORY_LAYOUT_WITH_MAPPED_FILES, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileName">Name of the file</param>
public PEImage(string fileName)
: this(fileName, true) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">The PE file data</param>
/// <param name="filename">Filename or null</param>
/// <param name="imageLayout">Image layout</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(byte[] data, string filename, ImageLayout imageLayout, bool verify)
: this(new MemoryStreamCreator(data) { FileName = filename }, imageLayout, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">The PE file data</param>
/// <param name="imageLayout">Image layout</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(byte[] data, ImageLayout imageLayout, bool verify)
: this(data, null, imageLayout, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">The PE file data</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(byte[] data, bool verify)
: this(data, null, ImageLayout.File, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">The PE file data</param>
/// <param name="filename">Filename or null</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(byte[] data, string filename, bool verify)
: this(data, filename, ImageLayout.File, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">The PE file data</param>
public PEImage(byte[] data)
: this(data, null, true) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">The PE file data</param>
/// <param name="filename">Filename or null</param>
public PEImage(byte[] data, string filename)
: this(data, filename, true) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseAddr">Address of PE image</param>
/// <param name="length">Length of PE image</param>
/// <param name="imageLayout">Image layout</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(IntPtr baseAddr, long length, ImageLayout imageLayout, bool verify)
: this(new UnmanagedMemoryStreamCreator(baseAddr, length), imageLayout, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseAddr">Address of PE image</param>
/// <param name="length">Length of PE image</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(IntPtr baseAddr, long length, bool verify)
: this(baseAddr, length, ImageLayout.Memory, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseAddr">Address of PE image</param>
/// <param name="length">Length of PE image</param>
public PEImage(IntPtr baseAddr, long length)
: this(baseAddr, length, true) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseAddr">Address of PE image</param>
/// <param name="imageLayout">Image layout</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(IntPtr baseAddr, ImageLayout imageLayout, bool verify)
: this(new UnmanagedMemoryStreamCreator(baseAddr, 0x10000), imageLayout, verify) {
try {
((UnmanagedMemoryStreamCreator)imageStreamCreator).Length = peInfo.GetImageSize();
ResetReader();
}
catch {
Dispose();
throw;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseAddr">Address of PE image</param>
/// <param name="verify">Verify PE file data</param>
public PEImage(IntPtr baseAddr, bool verify)
: this(baseAddr, ImageLayout.Memory, verify) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseAddr">Address of PE image</param>
public PEImage(IntPtr baseAddr)
: this(baseAddr, true) {
}
void ResetReader() {
if (imageStream != null) {
imageStream.Dispose();
imageStream = null;
}
imageStream = imageStreamCreator.CreateFull();
}
/// <inheritdoc/>
public RVA ToRVA(FileOffset offset) {
return peType.ToRVA(peInfo, offset);
}
/// <inheritdoc/>
public FileOffset ToFileOffset(RVA rva) {
return peType.ToFileOffset(peInfo, rva);
}
/// <inheritdoc/>
public void Dispose() {
IDisposable id;
if (win32Resources.IsValueInitialized && (id = win32Resources.Value) != null)
id.Dispose();
if ((id = imageStream) != null)
id.Dispose();
if ((id = imageStreamCreator) != null)
id.Dispose();
win32Resources.Value = null;
imageStream = null;
imageStreamCreator = null;
peType = null;
peInfo = null;
}
/// <inheritdoc/>
public IImageStream CreateStream(FileOffset offset) {
if ((long)offset > imageStreamCreator.Length)
throw new ArgumentOutOfRangeException("offset");
long length = imageStreamCreator.Length - (long)offset;
return CreateStream(offset, length);
}
/// <inheritdoc/>
public IImageStream CreateStream(FileOffset offset, long length) {
return imageStreamCreator.Create(offset, length);
}
/// <inheritdoc/>
public IImageStream CreateFullStream() {
return imageStreamCreator.CreateFull();
}
/// <inheritdoc/>
public void UnsafeDisableMemoryMappedIO() {
var creator = imageStreamCreator as MemoryMappedFileStreamCreator;
if (creator != null)
creator.UnsafeDisableMemoryMappedIO();
}
/// <inheritdoc/>
public bool IsMemoryMappedIO {
get {
var creator = imageStreamCreator as MemoryMappedFileStreamCreator;
return creator == null ? false : creator.IsMemoryMappedIO;
}
}
}
}
| 27.568831 | 120 | 0.668457 | [
"MIT"
] | CodeShark-Dev/dnlib | src/PE/PEImage.cs | 10,614 | 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.DataFactory.Latest.Inputs
{
/// <summary>
/// Amazon Marketplace Web Service dataset.
/// </summary>
public sealed class AmazonMWSObjectDatasetArgs : Pulumi.ResourceArgs
{
[Input("annotations")]
private InputList<object>? _annotations;
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public InputList<object> Annotations
{
get => _annotations ?? (_annotations = new InputList<object>());
set => _annotations = value;
}
/// <summary>
/// Dataset description.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The folder that this Dataset is in. If not specified, Dataset will appear at the root level.
/// </summary>
[Input("folder")]
public Input<Inputs.DatasetFolderArgs>? Folder { get; set; }
/// <summary>
/// Linked service reference.
/// </summary>
[Input("linkedServiceName", required: true)]
public Input<Inputs.LinkedServiceReferenceArgs> LinkedServiceName { get; set; } = null!;
[Input("parameters")]
private InputMap<Inputs.ParameterSpecificationArgs>? _parameters;
/// <summary>
/// Parameters for dataset.
/// </summary>
public InputMap<Inputs.ParameterSpecificationArgs> Parameters
{
get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>());
set => _parameters = value;
}
/// <summary>
/// Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement.
/// </summary>
[Input("schema")]
public Input<object>? Schema { get; set; }
/// <summary>
/// Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement.
/// </summary>
[Input("structure")]
public Input<object>? Structure { get; set; }
/// <summary>
/// The table name. Type: string (or Expression with resultType string).
/// </summary>
[Input("tableName")]
public Input<object>? TableName { get; set; }
/// <summary>
/// Type of dataset.
/// Expected value is 'AmazonMWSObject'.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public AmazonMWSObjectDatasetArgs()
{
}
}
}
| 33.6 | 159 | 0.596892 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataFactory/Latest/Inputs/AmazonMWSObjectDatasetArgs.cs | 3,024 | C# |
using YuzuDelivery.Umbraco.Core;
using YuzuDelivery.Umbraco.Forms;
using YuzuDelivery.Umbraco.Grid;
//----------------------
// <auto-generated>
// Generated using the NJsonSchema v10.0.23.0 (Newtonsoft.Json v12.0.0.0) (http://NJsonSchema.org)
// </auto-generated>
//----------------------
namespace YuzuDelivery.ViewModels
{
#pragma warning disable // Disable all warnings
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.0.23.0 (Newtonsoft.Json v12.0.0.0)")]
[YuzuMap("SiteNav")]
public partial class vmBlock_SiteNav
{
[Newtonsoft.Json.JsonProperty("navLinks", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Collections.Generic.List<vmBlock_DataLink> NavLinks { get; set; }
[Newtonsoft.Json.JsonProperty("_ref", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string _ref { get; set; }
[Newtonsoft.Json.JsonProperty("_modifiers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Collections.Generic.List<string> _modifiers { get; set; }
}
} | 44.137931 | 164 | 0.703906 | [
"MIT"
] | balanced-dev/yuzu-example-lambda | delivery.src/Lambda/App_Data/ViewModels/vmBlock_SiteNav.generated.cs | 1,280 | C# |
namespace Bulwark.Integration.GitLab.Events
{
public class UpdateMergeRequestEvent
{
public int ProjectId { get; set; }
public int MergeRequestIid { get; set; }
}
} | 22.444444 | 48 | 0.628713 | [
"MIT"
] | pauldotknopf/bulwark | src/integration/Bulwark.Integration.GitLab/Events/UpdateMergeRequestEvent.cs | 204 | C# |
using System;
using AspNetCoreSample.Domain;
using BE.CQRS.Data.MongoDb;
using BE.CQRS.Di.AspCore;
using BE.CQRS.Domain.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
namespace AspNetCoreSample
{
public static class CQRSBooter
{
public static IServiceCollection AddCqrs(this IServiceCollection serivces, IConfiguration config)
{
Console.WriteLine("Adding CQRS...");
string url = config["CustomerDatabase:MongoDb:Host"];
string db = config["CustomerDatabase:MongoDb:Name"];
Console.WriteLine($"ES DB: {url} - {db}");
IMongoDatabase mongodb = new MongoClient(url).GetDatabase(db);
serivces.AddEventSource(
new EventSourceConfiguration()
.SetDomainObjectAssemblies(typeof(Customer).Assembly)
.SetServiceProviderActivator()
.SetMongoDomainObjectRepository(mongodb)
.SetConventionBasedInMemoryCommandBus());
Console.WriteLine($"CQRS added");
return serivces;
}
public static IApplicationBuilder UseCqrs(this IApplicationBuilder app)
{
app.UseServiceProviderActivator();
return app;
}
}
} | 34.45 | 105 | 0.653846 | [
"MIT"
] | AlexZeitler/BE.CQRS | Samples/2_ASPNET_Core/AspNetCoreSample/CQRSBooter.cs | 1,378 | C# |
using QuizyfyAPI.Contracts.Responses.Pagination;
namespace QuizyfyAPI.Data;
public interface IQuizRepository : IRepository
{
PagedList<Quiz> GetQuizzes(PagingParams pagingParams, bool includeQuestions = false);
Task<Quiz> GetQuiz(int id, bool includeQuestions = false);
}
| 28.3 | 89 | 0.791519 | [
"MIT"
] | Layfully/QuizyfyAPI | QuizyfyAPI/Data/Repositories/IQuizRepository.cs | 285 | C# |
namespace TraktNet.Objects.Get.Tests.Collections.Implementations
{
using FluentAssertions;
using System;
using System.Threading.Tasks;
using Trakt.NET.Tests.Utility.Traits;
using TraktNet.Enums;
using TraktNet.Objects.Get.Collections;
using TraktNet.Objects.Get.Collections.Json.Reader;
using Xunit;
[Category("Objects.Get.Collections.Implementations")]
public class TraktCollectionShowEpisode_Tests
{
[Fact]
public void Test_TraktCollectionShowEpisode_Default_Constructor()
{
var collectionShowEpisode = new TraktCollectionShowEpisode();
collectionShowEpisode.Number.Should().BeNull();
collectionShowEpisode.CollectedAt.Should().BeNull();
collectionShowEpisode.Metadata.Should().BeNull();
}
[Fact]
public async Task Test_TraktCollectionShowEpisode_From_Json()
{
var jsonReader = new CollectionShowEpisodeObjectJsonReader();
var collectionShowEpisode = await jsonReader.ReadObjectAsync(JSON) as TraktCollectionShowEpisode;
collectionShowEpisode.Should().NotBeNull();
collectionShowEpisode.Number.Should().Be(1);
collectionShowEpisode.CollectedAt.Should().Be(DateTime.Parse("2014-07-14T01:00:00.000Z").ToUniversalTime());
collectionShowEpisode.Metadata.Should().NotBeNull();
collectionShowEpisode.Metadata.MediaType.Should().Be(TraktMediaType.Digital);
collectionShowEpisode.Metadata.MediaResolution.Should().Be(TraktMediaResolution.HD_720p);
collectionShowEpisode.Metadata.Audio.Should().Be(TraktMediaAudio.AAC);
collectionShowEpisode.Metadata.AudioChannels.Should().Be(TraktMediaAudioChannel.Channels_5_1);
collectionShowEpisode.Metadata.ThreeDimensional.Should().BeTrue();
}
private const string JSON =
@"{
""number"": 1,
""collected_at"": ""2014-07-14T01:00:00.000Z"",
""metadata"": {
""media_type"": ""digital"",
""resolution"": ""hd_720p"",
""audio"": ""aac"",
""audio_channels"": ""5.1"",
""3d"": true
}
}";
}
}
| 41.142857 | 120 | 0.634549 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Tests/Trakt.NET.Objects.Get.Tests/Collections/Implementations/TraktCollectionShowEpisode_Tests.cs | 2,306 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.CloudMine.Core.Collectors.Context;
using Microsoft.CloudMine.Core.Collectors.Telemetry;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CloudMine.Core.Collectors.IO
{
public class AzureBlobRecordWriter<T> : RecordWriterCore<T> where T : FunctionContext
{
private const long FileSizeLimit = 1024 * 1024 * 512; // 512 MB.
private const long RecordSizeLimit = 1024 * 1024 * 4; // 4 MB.
private readonly string blobRoot;
private readonly string outputQueueName;
private readonly string storageConnectionEnvironmentVariable;
private readonly string notificationQueueConnectionEnvironmentVariable;
private CloudBlobContainer outContainer;
private CloudBlockBlob outputBlob;
private CloudQueue queue;
public AzureBlobRecordWriter(string blobRoot,
string outputQueueName,
string identifier,
ITelemetryClient telemetryClient,
T functionContext,
ContextWriter<T> contextWriter,
string storageConnectionEnvironmentVariable = "AzureWebJobsStorage",
string notificationQueueConnectionEnvironmentVariable = "AzureWebJobsStorage")
: this(blobRoot, outputQueueName, identifier, telemetryClient, functionContext, contextWriter, outputPathPrefix: null, storageConnectionEnvironmentVariable, notificationQueueConnectionEnvironmentVariable)
{
}
public AzureBlobRecordWriter(string blobRoot,
string outputQueueName,
string identifier,
ITelemetryClient telemetryClient,
T functionContext,
ContextWriter<T> contextWriter,
string outputPathPrefix,
string storageConnectionEnvironmentVariable = "AzureWebJobsStorage",
string notificationQueueConnectionEnvironmentVariable = "AzureWebJobsStorage")
: base(identifier, telemetryClient, functionContext, contextWriter, outputPathPrefix, RecordSizeLimit, FileSizeLimit, source: RecordWriterSource.AzureBlob)
{
this.blobRoot = blobRoot;
this.outputQueueName = outputQueueName;
this.storageConnectionEnvironmentVariable = storageConnectionEnvironmentVariable;
this.notificationQueueConnectionEnvironmentVariable = notificationQueueConnectionEnvironmentVariable;
}
protected override async Task InitializeInternalAsync()
{
this.queue = string.IsNullOrWhiteSpace(this.notificationQueueConnectionEnvironmentVariable) ? null : await AzureHelpers.GetStorageQueueAsync(this.outputQueueName, this.notificationQueueConnectionEnvironmentVariable).ConfigureAwait(false);
this.outContainer = await AzureHelpers.GetStorageContainerAsync(this.blobRoot, this.storageConnectionEnvironmentVariable).ConfigureAwait(false);
}
protected override async Task<StreamWriter> NewStreamWriterAsync(string suffix)
{
this.outputBlob = this.outContainer.GetBlockBlobReference($"{this.OutputPathPrefix}{suffix}.json");
CloudBlobStream cloudBlobStream = await this.outputBlob.OpenWriteAsync().ConfigureAwait(false);
return new StreamWriter(cloudBlobStream, Encoding.UTF8);
}
protected override async Task NotifyCurrentOutputAsync()
{
string notificiationMessage = AzureHelpers.GenerateNotificationMessage(this.outputBlob);
if (this.queue != null)
{
await this.queue.AddMessageAsync(new CloudQueueMessage(notificiationMessage)).ConfigureAwait(false);
}
this.AddOutputPath(this.outputBlob.Name);
}
}
}
| 52.219512 | 250 | 0.659505 | [
"MIT"
] | dorfire/CEDAR.Core.Collector | Core.Collectors/IO/AzureBlobRecordWriter.cs | 4,284 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ComplaintBox.Web.Models
{
public class Subject
{
public int Id { get; set; }
public string Title { get; set; }
public Organization Organization { get; set; }
public int OrganizationId { get; set; }
}
} | 23.4 | 55 | 0.632479 | [
"MIT"
] | ahmedshuhel/Feedback | Source/Models/Subject.cs | 353 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("KindOfMagic Build Task")]
[assembly: AssemblyProduct("KindOfMagic")]
[assembly: AssemblyCopyright("Copyright © 2010-2016 Lex Lavnikov")]
[assembly: AssemblyVersion("1.3.1.0")]
[assembly: AssemblyFileVersion("1.3.1.0")]
[assembly: ComVisible(false)]
| 34 | 67 | 0.773529 | [
"MIT"
] | demigor/kindofmagic | KindOfMagic/Properties/AssemblyInfo.cs | 343 | C# |
namespace Library.Web.ViewModels.Admin.Books
{
using Library.Data.Models;
using Library.Services.Mapping;
public class DeleteModel : IMapFrom<Book>
{
public int Id { get; set; }
public string Title { get; set; }
}
}
| 19.615385 | 45 | 0.635294 | [
"MIT"
] | maria-tananska/Library | Web/Library.Web.ViewModels/Admin/Books/DeleteModel.cs | 257 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace GoodCodeBadCode.CH03.SingleResponsibility
{
public struct Recipient
{
public string Name { get; }
public string Email { get; }
public RecipientType RecipientType { get; }
public Recipient(string name, string email, RecipientType recipientType)
{
Name = name;
Email = email;
RecipientType = recipientType;
}
}
}
| 23.190476 | 80 | 0.62423 | [
"MIT"
] | afshaank/Clean-Code-in-C- | GoodCodeBadCode/CH03/SingleResponsibility/Recipient.cs | 489 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace RoomValue.Models
{
public class DetailsModel
{
public String EMail { get; set; }
public String Phone { get; set; }
}
public class HaveToPayModel
{
public String ExpenditureID { get; set; }
public String Item { get; set; }
public String Amount { get; set; }
}
public class GotPaidModel
{
public String ExpenditureID { get; set; }
public String Item { get; set; }
public String TotalAmount { get; set; }
public String PaidAmount { get; set; }
public String Payer { get; set; }
}
public class ExpenditureForPersonModel
{
public String ExpenditureID { get; set; }
public String Item { get; set; }
public String TotalAmount { get; set; }
public String Status { get; set; }
public String PaidBy { get; set; }
public String PaidTo { get; set; }
public String Date { get; set; }
public String PayType { get; set; }
public String BalanceAmount { get; set; }
}
public class UserModel
{
public static int GetMembersCount()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetMembersCount", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Read();
int count = int.Parse(sqlDataReader[0].ToString());
sqlConnection.Close();
return count;
}
public static List<Member> GetMembersIHaveToPay()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("MembersIHaveToPay", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID",System.Web.HttpContext.Current.Session["UserName"].ToString()));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
List<String> list = new List<string>();
while (sqlDataReader.Read())
{
list.Add(sqlDataReader[0].ToString());
}
sqlDataReader.Close();
List<Member> nameList = new List<Member>();
foreach (String temp in list)
{
SqlCommand sqlCommandForName = new SqlCommand("GetNameFromID", sqlConnection);
sqlCommandForName.CommandType = CommandType.StoredProcedure;
sqlCommandForName.Parameters.Add(new SqlParameter("@ID", temp));
SqlDataReader sqlDataReaderForName = sqlCommandForName.ExecuteReader();
sqlDataReaderForName.Read();
Member tempMember = new Member();
tempMember.ID = temp;
tempMember.Name = sqlDataReaderForName[0].ToString();
nameList.Add(tempMember);
sqlDataReaderForName.Close();
}
sqlConnection.Close();
return nameList;
}
public static List<String> GetAllMembers()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetAllMembers", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
List<String> list = new List<string>();
while (sqlDataReader.Read())
{
list.Add(sqlDataReader[0].ToString());
}
sqlConnection.Close();
return list;
}
internal static bool ExpenditureMade(string item, decimal perHead, List<string> checkboxList,String type)
{
try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
foreach (String checkBoxListItem in checkboxList)
{
SqlCommand sqlCommand = new SqlCommand("ExpenditureMade", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@Item", item));
sqlCommand.Parameters.Add(new SqlParameter("@Amount", perHead));
sqlCommand.Parameters.Add(new SqlParameter("@PaidTo", checkBoxListItem));
sqlCommand.Parameters.Add(new SqlParameter("@PayType", type));
sqlCommand.Parameters.Add(new SqlParameter("@PaidBy", System.Web.HttpContext.Current.Session["UserName"].ToString()));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
}
sqlConnection.Close();
return true;
}
catch (Exception)
{
return false;
}
}
public static List<HaveToPayModel> GetHaveToPayList(String payeeID)
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetHaveToPayList", sqlConnection);
sqlCommand.Parameters.Add(new SqlParameter("@PayeeID", payeeID));
sqlCommand.Parameters.Add(new SqlParameter("@PayerID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
List<HaveToPayModel> list = new List<HaveToPayModel>();
while (sqlDataReader.Read())
{
HaveToPayModel haveToPay = new HaveToPayModel();
haveToPay.ExpenditureID = sqlDataReader[0].ToString();
haveToPay.Item = sqlDataReader[1].ToString();
haveToPay.Amount = sqlDataReader[2].ToString();
list.Add(haveToPay);
}
sqlConnection.Close();
return list;
}
internal static bool CombinedPayment(string payTo)
{
try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("CombinedPayment", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@PayerID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
sqlCommand.Parameters.Add(new SqlParameter("@PayeeID", payTo));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlConnection.Close();
return true;
}
catch (Exception)
{
return false;
}
}
internal static bool SinglePayment(string expenditureID,string amount)
{
try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("SinglePayment", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ExpenditureID",expenditureID));
sqlCommand.Parameters.Add(new SqlParameter("@Amount", amount));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlConnection.Close();
return true;
}
catch (Exception)
{
return false;
}
}
public static List<GotPaidModel> GetGotPaidList()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetGotPaidList", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
List<GotPaidModel> list = new List<GotPaidModel>();
while (sqlDataReader.Read())
{
GotPaidModel tempGotPaid = new GotPaidModel();
tempGotPaid.ExpenditureID = sqlDataReader[0].ToString();
tempGotPaid.Item = sqlDataReader[1].ToString();
tempGotPaid.TotalAmount = sqlDataReader[2].ToString();
tempGotPaid.PaidAmount = sqlDataReader[3].ToString();
tempGotPaid.Payer = sqlDataReader[4].ToString();
list.Add(tempGotPaid);
}
sqlConnection.Close();
return list;
}
public static int RejectApproval(String expenditureID)
{
try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("RejectPayment", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
sqlCommand.Parameters.Add(new SqlParameter("@ExpenditureID", expenditureID));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Read();
int result = int.Parse(sqlDataReader[0].ToString());
sqlConnection.Close();
return result;
}
catch (Exception)
{
return 3;
}
}
public static int AcceptApproval(String expenditureID)
{
try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("AcceptPayment", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
sqlCommand.Parameters.Add(new SqlParameter("@ExpenditureID", expenditureID));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Read();
int result = int.Parse(sqlDataReader[0].ToString());
sqlConnection.Close();
return result;
}
catch (Exception)
{
return 3;
}
}
public static DetailsModel GetUserDetails()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetUserDetails", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Read();
DetailsModel details = new DetailsModel();
details.EMail = sqlDataReader[0].ToString();
details.Phone = sqlDataReader[1].ToString();
sqlConnection.Close();
return details;
}
public static bool UpdateUserDetails(String mail, String phone)
{
try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("UpdateUserDetails", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
sqlCommand.Parameters.Add(new SqlParameter("@Mail", mail));
sqlCommand.Parameters.Add(new SqlParameter("@Phone", phone));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
return true;
}
catch (Exception)
{
return false;
}
}
public static List<ExpenditureForPersonModel> GetExpenditureDetails()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetExpenditureDetails", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", System.Web.HttpContext.Current.Session["UserName"].ToString()));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
List<ExpenditureForPersonModel> list = new List<ExpenditureForPersonModel>();
while (sqlDataReader.Read())
{
ExpenditureForPersonModel expenditureItem = new ExpenditureForPersonModel();
expenditureItem.Date = sqlDataReader[0].ToString().Split(' ')[0];
expenditureItem.Item = sqlDataReader[1].ToString();
expenditureItem.TotalAmount = sqlDataReader[2].ToString();
expenditureItem.PaidBy = GetNameByID(sqlDataReader[3].ToString());
expenditureItem.PaidTo = GetNameByID(sqlDataReader[4].ToString());
expenditureItem.PayType = GetFullType(sqlDataReader[5].ToString());
expenditureItem.Status = sqlDataReader[6].ToString();
expenditureItem.BalanceAmount = sqlDataReader[7].ToString();
list.Add(expenditureItem);
}
sqlConnection.Close();
return list;
}
public static String GetNameByID(String ID)
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("GetNameFromID", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@ID", ID));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Read();
String name = sqlDataReader[0].ToString();
sqlConnection.Close();
return name;
}
public static String GetFullType(String status)
{
if(status.Equals("All"))
return "All People";
else if(status.Equals("WMe"))
return "With Me";
else
return "Without Me";
}
}
} | 48.233236 | 140 | 0.593448 | [
"MIT"
] | harimaruthachalam/RoomValue | RoomValue/Models/UserModel.cs | 16,546 | C# |
using System.Security.Claims;
namespace Dddify.Security.Identity;
/// <summary>
/// Used to get dddify specified claim type names.
/// </summary>
public static class DefaultClaimTypes
{
/// <summary>
/// Default: <see cref="ClaimTypes.Name"/>
/// </summary>
public static string UserName { get; set; } = ClaimTypes.Name;
/// <summary>
/// Default: <see cref="ClaimTypes.GivenName"/>
/// </summary>
public static string Name { get; set; } = ClaimTypes.GivenName;
/// <summary>
/// Default: <see cref="ClaimTypes.NameIdentifier"/>
/// </summary>
public static string UserId { get; set; } = ClaimTypes.NameIdentifier;
/// <summary>
/// Default: <see cref="ClaimTypes.Role"/>
/// </summary>
public static string Role { get; set; } = ClaimTypes.Role;
/// <summary>
/// Default: <see cref="ClaimTypes.Email"/>
/// </summary>
public static string Email { get; set; } = ClaimTypes.Email;
/// <summary>
/// Default: "email_verified".
/// </summary>
public static string EmailVerified { get; set; } = "email_verified";
/// <summary>
/// Default: "phone_number".
/// </summary>
public static string PhoneNumber { get; set; } = "phone_number";
/// <summary>
/// Default: "phone_number_verified".
/// </summary>
public static string PhoneNumberVerified { get; set; } = "phone_number_verified";
/// <summary>
/// Default: "tenantid".
/// </summary>
public static string TenantId { get; set; } = "tenantid";
}
| 28.181818 | 85 | 0.607742 | [
"MIT"
] | esofar/dddify | src/Dddify/Security/Identity/DefaultClaimTypes.cs | 1,552 | C# |
#if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.Threading;
using ModestTree;
using UnityEngine;
using Zenject.Internal;
#if UNITY_EDITOR
#endif
namespace Zenject
{
public class ProjectContext : Context
{
public event Action PreInstall;
public event Action PostInstall;
public event Action PreResolve;
public event Action PostResolve;
public const string ProjectContextResourcePath = "ProjectContext";
public const string ProjectContextResourcePathOld = "ProjectCompositionRoot";
static ProjectContext _instance;
// TODO: Set this to false the next time major version is incremented
[Tooltip("When true, objects that are created at runtime will be parented to the ProjectContext")]
[SerializeField]
bool _parentNewObjectsUnderContext = true;
[SerializeField]
ReflectionBakingCoverageModes _editorReflectionBakingCoverageMode;
[SerializeField]
ReflectionBakingCoverageModes _buildsReflectionBakingCoverageMode;
[SerializeField]
ZenjectSettings _settings;
DiContainer _container;
public override DiContainer Container
{
get { return _container; }
}
public static bool HasInstance
{
get { return _instance != null; }
}
public static ProjectContext Instance
{
get
{
if (_instance == null)
{
InstantiateAndInitialize();
Assert.IsNotNull(_instance);
}
return _instance;
}
}
#if UNITY_EDITOR
public static bool ValidateOnNextRun
{
get;
set;
}
#endif
public override IEnumerable<GameObject> GetRootGameObjects()
{
return new[] { gameObject };
}
public static GameObject TryGetPrefab()
{
var prefabs = Resources.LoadAll(ProjectContextResourcePath, typeof(GameObject));
if (prefabs.Length > 0)
{
Assert.That(prefabs.Length == 1,
"Found multiple project context prefabs at resource path '{0}'", ProjectContextResourcePath);
return (GameObject)prefabs[0];
}
prefabs = Resources.LoadAll(ProjectContextResourcePathOld, typeof(GameObject));
if (prefabs.Length > 0)
{
Assert.That(prefabs.Length == 1,
"Found multiple project context prefabs at resource path '{0}'", ProjectContextResourcePathOld);
return (GameObject)prefabs[0];
}
return null;
}
static void InstantiateAndInitialize()
{
#if UNITY_EDITOR
ProfileBlock.UnityMainThread = Thread.CurrentThread;
#endif
Assert.That(FindObjectsOfType<ProjectContext>().IsEmpty(),
"Tried to create multiple instances of ProjectContext!");
var prefab = TryGetPrefab();
var prefabWasActive = false;
#if ZEN_INTERNAL_PROFILING
using (ProfileTimers.CreateTimedBlock("GameObject.Instantiate"))
#endif
{
if (prefab == null)
{
_instance = new GameObject("ProjectContext")
.AddComponent<ProjectContext>();
}
else
{
prefabWasActive = prefab.activeSelf;
GameObject gameObjectInstance;
#if UNITY_EDITOR
if(prefabWasActive)
{
// This ensures the prefab's Awake() methods don't fire (and, if in the editor, that the prefab file doesn't get modified)
gameObjectInstance = GameObject.Instantiate(prefab, ZenUtilInternal.GetOrCreateInactivePrefabParent());
gameObjectInstance.SetActive(false);
gameObjectInstance.transform.SetParent(null, false);
}
else
{
gameObjectInstance = GameObject.Instantiate(prefab);
}
#else
if(prefabWasActive)
{
prefab.SetActive(false);
gameObjectInstance = GameObject.Instantiate(prefab);
prefab.SetActive(true);
}
else
{
gameObjectInstance = GameObject.Instantiate(prefab);
}
#endif
_instance = gameObjectInstance.GetComponent<ProjectContext>();
Assert.IsNotNull(_instance,
"Could not find ProjectContext component on prefab 'Resources/{0}.prefab'", ProjectContextResourcePath);
}
}
// Note: We use Initialize instead of awake here in case someone calls
// ProjectContext.Instance while ProjectContext is initializing
_instance.Initialize();
if (prefabWasActive)
{
#if ZEN_INTERNAL_PROFILING
using (ProfileTimers.CreateTimedBlock("User Code"))
#endif
{
// We always instantiate it as disabled so that Awake and Start events are triggered after inject
_instance.gameObject.SetActive(true);
}
}
}
public bool ParentNewObjectsUnderContext
{
get { return _parentNewObjectsUnderContext; }
set { _parentNewObjectsUnderContext = value; }
}
public void EnsureIsInitialized()
{
// Do nothing - Initialize occurs in Instance property
}
public void Awake()
{
if (Application.isPlaying)
// DontDestroyOnLoad can only be called when in play mode and otherwise produces errors
// ProjectContext is created during design time (in an empty scene) when running validation
// and also when running unit tests
// In these cases we don't need DontDestroyOnLoad so just skip it
{
DontDestroyOnLoad(gameObject);
}
}
void Initialize()
{
Assert.IsNull(_container);
if (Application.isEditor)
{
TypeAnalyzer.ReflectionBakingCoverageMode = _editorReflectionBakingCoverageMode;
}
else
{
TypeAnalyzer.ReflectionBakingCoverageMode = _buildsReflectionBakingCoverageMode;
}
bool isValidating = false;
#if UNITY_EDITOR
isValidating = ValidateOnNextRun;
// Reset immediately to ensure it doesn't get used in another run
ValidateOnNextRun = false;
#endif
_container = new DiContainer(
new[] { StaticContext.Container }, isValidating);
// Do this after creating DiContainer in case it's needed by the pre install logic
if (PreInstall != null)
{
PreInstall();
}
var injectableMonoBehaviours = new List<MonoBehaviour>();
GetInjectableMonoBehaviours(injectableMonoBehaviours);
foreach (var instance in injectableMonoBehaviours)
{
_container.QueueForInject(instance);
}
_container.IsInstalling = true;
try
{
InstallBindings(injectableMonoBehaviours);
}
finally
{
_container.IsInstalling = false;
}
if (PostInstall != null)
{
PostInstall();
}
if (PreResolve != null)
{
PreResolve();
}
_container.ResolveRoots();
if (PostResolve != null)
{
PostResolve();
}
}
protected override void GetInjectableMonoBehaviours(List<MonoBehaviour> monoBehaviours)
{
ZenUtilInternal.AddStateMachineBehaviourAutoInjectersUnderGameObject(gameObject);
ZenUtilInternal.GetInjectableMonoBehavioursUnderGameObject(gameObject, monoBehaviours);
}
void InstallBindings(List<MonoBehaviour> injectableMonoBehaviours)
{
if (_parentNewObjectsUnderContext)
{
_container.DefaultParent = transform;
}
else
{
_container.DefaultParent = null;
}
_container.Settings = _settings ?? ZenjectSettings.Default;
_container.Bind<ZenjectSceneLoader>().AsSingle();
ZenjectManagersInstaller.Install(_container);
_container.Bind<Context>().FromInstance(this);
_container.Bind(typeof(ProjectKernel), typeof(MonoKernel))
.To<ProjectKernel>().FromNewComponentOn(gameObject).AsSingle().NonLazy();
_container.Bind<SceneContextRegistry>().AsSingle();
InstallSceneBindings(injectableMonoBehaviours);
InstallInstallers();
}
}
}
#endif
| 30.75817 | 146 | 0.556524 | [
"MIT"
] | AlexandrBashkirev/innovate_afr_gauge | innovate_afr_gauge/Assets/Scripts/Tools/Zenject/Source/Install/Contexts/ProjectContext.cs | 9,412 | C# |
using System;
using FitChallenge.Server.Data.Models.Base;
using Microsoft.AspNetCore.Identity;
namespace FitChallenge.Server.Data.Models
{
public class User : IdentityUser, IEntity
{
public Profile Profile { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
}
}
| 22.05 | 49 | 0.659864 | [
"MIT"
] | LuGeorgiev/SoftUni.React | 99.FitChallenge/FitChallenge.Server/Data/Models/User.cs | 443 | C# |
using System.Collections.Generic;
using CodeHub.Core.Services;
using GitHubSharp;
using GitHubSharp.Models;
namespace CodeHub.Core.ViewModels.Events
{
public class RepositoryEventsViewModel : BaseEventsViewModel
{
public string RepositoryName { get; set; }
public string RepositoryOwner { get; set; }
public RepositoryEventsViewModel(IApplicationService applicationService)
: base(applicationService)
{
}
protected override GitHubRequest<List<EventModel>> CreateRequest(int page, int perPage)
{
return ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetEvents(page, perPage);
}
}
} | 29.958333 | 113 | 0.705146 | [
"Apache-2.0"
] | gitter-badger/CodeHub | CodeHub.Core/ViewModels/Events/RepositoryEventsViewModel.cs | 719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace azure_ad_samples
{
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.Configure<CookiePolicyOptions>(options => {
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
}
}
| 31.769231 | 119 | 0.656174 | [
"MIT"
] | tuomast/azure-ad-sample | azure-ad-samples/Startup.cs | 1,652 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Network.Models
{
public partial class BastionSessionDeleteResult
{
internal static BastionSessionDeleteResult DeserializeBastionSessionDeleteResult(JsonElement element)
{
IReadOnlyList<BastionSessionState> value = default;
string nextLink = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("value"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
List<BastionSessionState> array = new List<BastionSessionState>();
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(BastionSessionState.DeserializeBastionSessionState(item));
}
}
value = array;
continue;
}
if (property.NameEquals("nextLink"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
nextLink = property.Value.GetString();
continue;
}
}
return new BastionSessionDeleteResult(value, nextLink);
}
}
}
| 33.210526 | 109 | 0.479134 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/Models/BastionSessionDeleteResult.Serialization.cs | 1,893 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Ads.GoogleAds.V7.Services.Snippets
{
using Google.Ads.GoogleAds.V7.Resources;
using Google.Ads.GoogleAds.V7.Services;
using System.Threading.Tasks;
public sealed partial class GeneratedCampaignAssetServiceClientStandaloneSnippets
{
/// <summary>Snippet for GetCampaignAssetAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetCampaignAssetAsync()
{
// Create client
CampaignAssetServiceClient campaignAssetServiceClient = await CampaignAssetServiceClient.CreateAsync();
// Initialize request argument(s)
string resourceName = "customers/[CUSTOMER_ID]/campaignAssets/[CAMPAIGN_ID]~[ASSET_ID]~[FIELD_TYPE]";
// Make the request
CampaignAsset response = await campaignAssetServiceClient.GetCampaignAssetAsync(resourceName);
}
}
}
| 41.073171 | 115 | 0.710808 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/ads/googleads/v7/googleads-csharp/Google.Ads.GoogleAds.V7.Services.StandaloneSnippets/CampaignAssetServiceClient.GetCampaignAssetAsyncSnippet.g.cs | 1,684 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class TutorialPopupDisplayController : inkWidgetLogicController
{
[Ordinal(0)] [RED("image")] public inkImageWidgetReference Image { get; set; }
[Ordinal(1)] [RED("inputHint")] public inkWidgetReference InputHint { get; set; }
[Ordinal(2)] [RED("message")] public inkTextWidgetReference Message { get; set; }
[Ordinal(3)] [RED("title")] public inkTextWidgetReference Title { get; set; }
[Ordinal(4)] [RED("video_1024x576")] public inkVideoWidgetReference Video_1024x576 { get; set; }
[Ordinal(5)] [RED("video_1280x720")] public inkVideoWidgetReference Video_1280x720 { get; set; }
[Ordinal(6)] [RED("video_1360x768")] public inkVideoWidgetReference Video_1360x768 { get; set; }
[Ordinal(7)] [RED("video_720x405")] public inkVideoWidgetReference Video_720x405 { get; set; }
public TutorialPopupDisplayController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 47.391304 | 117 | 0.722936 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/TutorialPopupDisplayController.cs | 1,068 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// ---------------------------------------------------------------
// <copyright file="CameraFollow.cs">
// MIT Licence Copyright (c) 2019.
// </copyright>
// <author>James Mead Heath</author>
// <summary>
// Allows the camera to follow the player when the player moves.
// Keeps the camera at the same distance from the player at all times.
// The camera position is decided within the Unity Editor.
// </summary>
// ---------------------------------------------------------------
public class CameraFollow : MonoBehaviour
{
//Player postion value
public Transform target;
//Distance between player and camera.
private Vector3 offset;
/// <summary>
/// Creates a value for offset which defines where the camera is in relation to the player.
/// </summary>
void Start()
{
offset = this.transform.position - target.position;
}
/// <summary>
/// Moves the camera to follow the player when they move.
/// Keeps the camera at the same distance away.
/// </summary>
void Update()
{
this.transform.position = offset + target.position;
}
}
| 28.642857 | 95 | 0.598504 | [
"MIT"
] | GamesDevDave/Comp120-TinkeringAudio | Contract #1 - Sound Effect Generation/Assets/Scripts/CameraFollow.cs | 1,205 | C# |
using System;
using Microsoft.Xrm.Sdk;
namespace CCLLC.CDS.Sdk
{
using CCLLC.Core;
public class XmlConfigurationResourceFactory : IXmlConfigurationResourceFactory
{
private ICache Cache { get; }
public XmlConfigurationResourceFactory(ICache cache)
{
Cache = cache ?? throw new ArgumentNullException("cache is required.");
}
public IXmlConfigurationResource CreateConfigurationResources(IOrganizationService orgService)
{
return new XmlConfigurationResource(orgService, Cache);
}
}
}
| 25.391304 | 102 | 0.683219 | [
"MIT"
] | ScottColson/CCLLCBusinessTransactionFramework | CDS/CCLLC.BTF.Process.CDSSolution/Plugins/App_Packages/CCLLC.CDS.Sdk.1.4.2/XmlConfigurationResourceFactory.cs | 586 | 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("Labs_86_async")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("Labs_86_async")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2019")]
[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("f05b958d-e303-46f7-88dd-5a0759f6e8a1")]
// 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.054054 | 84 | 0.747869 | [
"MIT"
] | SebastianTrifa/c- | Labs_86_async/Properties/AssemblyInfo.cs | 1,411 | C# |
#pragma warning disable 414
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using g3;
using f3;
using gs;
namespace cotangent
{
public class SupportSettingsPanelSetup : MonoBehaviour
{
Toggle generateSupport;
InputField overhangAngle;
Toggle supportMinZTips;
InputField supportSpacing;
InputField supportGap;
Toggle supportShell;
Toggle supportReleaseOpt;
GameObject overhangAngleRow;
GameObject supportMinZTipsRow;
GameObject supportSpacingRow;
GameObject supportShellRow;
GameObject supportGapRow;
public void Start()
{
CC.Settings.OnNewSettings += Settings_OnNewSettings;
CC.Settings.OnSettingModified += Settings_OnSettingModified;
generateSupport = UnityUIUtil.FindToggleAndConnectToSource(this.gameObject, "GenerateSupportToggle",
() => { return CC.Settings.GenerateSupport; },
(boolValue) => { CC.Settings.GenerateSupport = boolValue; });
overhangAngle = UnityUIUtil.FindInputAndAddFloatHandlers(this.gameObject, "OverhangAngleInputField",
() => { return (float)CC.Settings.OverhangAngleDeg; },
(floatValue) => { CC.Settings.OverhangAngleDeg = Math.Round(floatValue, 2); }, 0.01f, 89.99f);
overhangAngleRow = overhangAngle.transform.parent.gameObject;
supportMinZTips = UnityUIUtil.FindToggleAndConnectToSource(this.gameObject, "SupportTipsToggle",
() => { return CC.Settings.SupportMinZTips; },
(boolValue) => { CC.Settings.SupportMinZTips = boolValue; });
supportMinZTipsRow = supportMinZTips.transform.parent.gameObject;
supportSpacing = UnityUIUtil.FindInputAndAddFloatHandlers(this.gameObject, "SupportSpacingInputField",
() => { return (float)CC.Settings.SupportStepX; },
(floatValue) => { CC.Settings.SupportStepX = Math.Round(floatValue, 5); }, 1.0f, 9999.0f);
supportSpacingRow = supportSpacing.transform.parent.gameObject;
supportShell = UnityUIUtil.FindToggleAndConnectToSource(this.gameObject, "SupportShellToggle",
() => { return CC.Settings.EnableSupportShell; },
(boolValue) => { CC.Settings.EnableSupportShell = boolValue; });
supportShellRow = supportShell.transform.parent.gameObject;
supportReleaseOpt = UnityUIUtil.FindToggleAndConnectToSource(this.gameObject, "SupportReleaseOptToggle",
() => { return CC.Settings.EnableSupportReleaseOpt; },
(boolValue) => { CC.Settings.EnableSupportReleaseOpt = boolValue; });
supportGap = UnityUIUtil.FindInputAndAddFloatHandlers(this.gameObject, "SupportGapInputField",
() => { return (float)CC.Settings.SupportSolidSpace; },
(floatValue) => { CC.Settings.SupportSolidSpace = Math.Round(floatValue, 5); }, 0.0f, 100.0f);
supportGapRow = supportGap.transform.parent.gameObject;
is_expanded = true;
update_visibility();
}
bool is_expanded;
private void update_visibility()
{
if ( CC.Settings.GenerateSupport != is_expanded) {
is_expanded = CC.Settings.GenerateSupport;
overhangAngleRow.SetVisible(is_expanded);
supportMinZTipsRow.SetVisible(is_expanded);
}
}
private void Settings_OnSettingModified(PrintSettings settings)
{
SingleMaterialFFFSettings S = CC.PrinterDB.ActivePreset.Settings as SingleMaterialFFFSettings;
if (generateSupport.isOn != CC.Settings.GenerateSupport)
generateSupport.isOn = CC.Settings.GenerateSupport;
UnityUIUtil.SetBackgroundColor(generateSupport, settings.GenerateSupport_Modified ?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
UnityUIUtil.SetBackgroundColor(overhangAngle, settings.OverhangAngleDeg_Modified?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
UnityUIUtil.SetBackgroundColor(supportMinZTips, settings.SupportMinZTips_Modified?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
UnityUIUtil.SetBackgroundColor(supportSpacing, settings.SupportStepX_Modified ?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
UnityUIUtil.SetBackgroundColor(supportShell, settings.EnableSupportShell_Modified ?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
UnityUIUtil.SetBackgroundColor(supportReleaseOpt, settings.EnableSupportReleaseOpt_Modified ?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
UnityUIUtil.SetBackgroundColor(supportGap, settings.SupportSolidSpace_Modified?
CotangentUI.ModifiedSettingColor : CotangentUI.NormalSettingColor);
update_visibility();
}
private void Settings_OnNewSettings(PrintSettings settings)
{
generateSupport.isOn = CC.Settings.GenerateSupport;
UnityUIUtil.SetBackgroundColor(generateSupport, CotangentUI.NormalSettingColor);
overhangAngle.text = CC.Settings.OverhangAngleDeg.ToString();
UnityUIUtil.SetBackgroundColor(overhangAngle, CotangentUI.NormalSettingColor);
supportMinZTips.isOn = CC.Settings.SupportMinZTips;
UnityUIUtil.SetBackgroundColor(supportMinZTips, CotangentUI.NormalSettingColor);
supportSpacing.text = CC.Settings.SupportStepX.ToString();
UnityUIUtil.SetBackgroundColor(supportSpacing, CotangentUI.NormalSettingColor);
supportShell.isOn = CC.Settings.EnableSupportShell;
UnityUIUtil.SetBackgroundColor(supportShell, CotangentUI.NormalSettingColor);
supportReleaseOpt.isOn = CC.Settings.EnableSupportReleaseOpt;
UnityUIUtil.SetBackgroundColor(supportReleaseOpt, CotangentUI.NormalSettingColor);
supportGap.text = CC.Settings.SupportSolidSpace.ToString();
UnityUIUtil.SetBackgroundColor(supportGap, CotangentUI.NormalSettingColor);
update_visibility();
}
}
}
| 45.521127 | 116 | 0.686881 | [
"MIT"
] | EnvyKong/Cotangent | Assets/cotangentApp/unity_ui/SupportSettingsPanelSetup.cs | 6,466 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.AdvocacyPlatform.Functions.FunctionalTests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AdvocacyPlatform.Clients;
using Microsoft.AdvocacyPlatform.Contracts;
using Microsoft.AdvocacyPlatform.Functions.Module;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Twilio.Rest.Api.V2010.Account;
using TH = System.Threading;
using TwilioHttp = Twilio.Http;
/// <summary>
/// Functional test for PullRecordingHttpTrigger.
/// </summary>
[TestClass]
public class PullRecordingFunctionalTest
{
/// <summary>
/// Twilio base URL for REST calls.
/// </summary>
public const string TwilioBaseUrl = "https://api.twilio.com";
/// <summary>
/// Name of app setting with data store connection string.
/// </summary>
public const string StorageAccessConnectionStringAppSettingName = "storageAccessConnectionString";
/// <summary>
/// Name of app setting with secret identifier for storage read access key.
/// </summary>
public const string StorageReadAccessKeySecretNameAppSettingName = "storageReadAccessKeySecretName";
/// <summary>
/// Name of app setting with container name.
/// </summary>
public const string StorageContainerNameAppSettingName = "storageContainerName";
/// <summary>
/// Name of app setting for URL of token issuing authority.
/// </summary>
public const string AuthorityAppSettingName = "authority";
/// <summary>
/// Function configuration.
/// </summary>
private IConfiguration _functionConfig;
/// <summary>
/// Internal logger.
/// </summary>
private ConsoleLogger _log = new ConsoleLogger();
/// <summary>
/// Test configuration.
/// </summary>
private TestConfiguration _config;
/// <summary>
/// Test configuration for concurrent executions.
/// </summary>
private ConcurrentTestConfiguration _concurrentConfig;
/// <summary>
/// Formats connection string with data store access key.
/// </summary>
/// <param name="connectionString">Partial connection string.</param>
/// <returns>The full connection string.</returns>
public static string GetBlobEndpoint(string connectionString)
{
string[] connectionStringParts = connectionString.Split(new char[] { ';' });
foreach (string connectionStringPart in connectionStringParts)
{
if (connectionStringPart.Contains("BlobEndpoint", System.StringComparison.OrdinalIgnoreCase))
{
string[] kvp = connectionStringPart.Split(new char[] { '=' });
return kvp[1];
}
}
return null;
}
/// <summary>
/// Initialize tests.
/// </summary>
[TestInitialize]
public void InitializeTests()
{
Tuple<TestConfiguration, ConcurrentTestConfiguration> configs = TestHelper.InitializeTest(_log);
_config = configs.Item1;
_concurrentConfig = configs.Item2;
_functionConfig = TestHelper.GetConfiguration();
}
/// <summary>
/// Ensures PullRecordingHttpTrigger.Run() implementation runs correctly.
/// </summary>
[TestMethod]
public void PullRecordingHttpTriggerRun()
{
HttpRequest request = CreateHttpPostRequest(_config.InputId, _config.CallSid);
ExecutionContext context = new ExecutionContext()
{
FunctionAppDirectory = Directory.GetCurrentDirectory(),
};
string expectedStorageContainerName = _functionConfig[StorageContainerNameAppSettingName];
string expectedDestinationPathPrefix = $"{_config.InputId}/file_";
string expectedBlobEndpoint = GetBlobEndpoint(_functionConfig[StorageAccessConnectionStringAppSettingName]);
string expectedFullPathPrefix = $"{expectedBlobEndpoint}{expectedStorageContainerName}/{expectedDestinationPathPrefix}";
ISecretStore secretStore = PullRecordingHttpTrigger.Container.GetService<ISecretStore>();
Secret expectedStorageReadAccessKey = secretStore.GetSecretAsync(_functionConfig[StorageReadAccessKeySecretNameAppSettingName], _functionConfig[AuthorityAppSettingName]).Result;
IActionResult result = PullRecordingHttpTrigger.Run(request, _log, context).Result;
Assert.IsInstanceOfType(result, typeof(OkObjectResult));
OkObjectResult okResult = (OkObjectResult)result;
Assert.AreEqual(200, okResult.StatusCode);
Assert.IsInstanceOfType(okResult.Value, typeof(PullRecordingResponse));
PullRecordingResponse response = (PullRecordingResponse)okResult.Value;
Assert.AreEqual(_config.CallSid, response.CallSid);
Assert.IsNotNull(response.RecordingUri);
Assert.IsTrue(response.RecordingUri.StartsWith(expectedDestinationPathPrefix));
Assert.IsTrue(response.FullRecordingUrl.StartsWith(expectedFullPathPrefix));
Assert.IsTrue(response.FullRecordingUrl.EndsWith($"?{expectedStorageReadAccessKey.Value}"));
Assert.IsTrue(response.RecordingLength > 600000); // Recording size should be ~800KB
Assert.IsNotNull(response.FullRecordingUrl);
Assert.AreEqual((int)CommonStatusCode.Ok, response.StatusCode);
Assert.AreEqual(Enum.GetName(typeof(CommonStatusCode), CommonStatusCode.Ok), response.StatusDesc);
Assert.IsFalse(response.HasError);
Assert.AreEqual((int)CommonErrorCode.NoError, response.ErrorCode);
Assert.IsNull(response.ErrorDetails);
_log.LogInformation("Writing returned recording URI to test configuration...");
_config.RecordingUri = response.RecordingUri;
_config.Save(GlobalTestConstants.TestConfigurationFilePath);
}
/// <summary>
/// Ensures PullRecordingHttpTrigger.Run() implementation runs correctly for concurrent executions.
/// </summary>
[TestMethod]
public void PullRecordingImplementationConcurrentRuns()
{
Task[] threads = new Task[_concurrentConfig.NumberOfThreads];
for (int i = 0; i < _concurrentConfig.NumberOfThreads; i++)
{
threads[i] = Task.Run(
new Action(
() => PullRecordingRunnerLocal(_concurrentConfig.TestConfigurationQueue)));
}
_log.LogInformation("Waiting on threads...");
Task.WaitAll(threads);
_log.LogInformation("All threads completed...");
}
/// <summary>
/// Runner for ensuring PullRecordingHttpTrigger.Run() implementation runs correctly for concurrent executions.
/// </summary>
/// <param name="queue">The queue of tests to run.</param>
public void PullRecordingRunnerLocal(ConcurrentQueue<TestConfiguration> queue)
{
TestConfiguration nextTestConfiguration = null;
while (!queue.IsEmpty)
{
if (queue.TryDequeue(out nextTestConfiguration))
{
HttpRequest request = CreateHttpPostRequest(nextTestConfiguration.InputId, nextTestConfiguration.CallSid);
ExecutionContext context = new ExecutionContext()
{
FunctionAppDirectory = Directory.GetCurrentDirectory(),
};
IActionResult result = PullRecordingHttpTrigger.Run(request, _log, context).Result;
Assert.IsInstanceOfType(result, typeof(OkObjectResult));
OkObjectResult okResult = (OkObjectResult)result;
Assert.AreEqual(200, okResult.StatusCode);
Assert.IsInstanceOfType(okResult.Value, typeof(PullRecordingResponse));
PullRecordingResponse response = (PullRecordingResponse)okResult.Value;
Assert.AreEqual(nextTestConfiguration.CallSid, response.CallSid);
Assert.IsNotNull(response.RecordingUri);
// Assert.IsTrue(response.RecordingLength > 600000); // Recording size should be ~800KB
Assert.IsNotNull(response.FullRecordingUrl);
Assert.AreEqual((int)CommonStatusCode.Ok, response.StatusCode);
Assert.AreEqual(Enum.GetName(typeof(CommonStatusCode), CommonStatusCode.Ok), response.StatusDesc);
Assert.IsFalse(response.HasError);
Assert.AreEqual((int)CommonErrorCode.NoError, response.ErrorCode);
Assert.IsNull(response.ErrorDetails);
_log.LogInformation("Writing returned recording uri to test configuration...");
nextTestConfiguration.RecordingUri = response.RecordingUri;
}
TH.Thread.Sleep(2000);
}
_concurrentConfig.Save(GlobalTestConstants.ConcurrentTestConfigurationFilePath);
}
/// <summary>
/// Ensures PullRecordingHttpTrigger runs correctly for concurrent executions against a remote Azure Function.
/// </summary>
[TestMethod]
public void PullRecordingHttpTriggerConcurrentRuns()
{
FunctionSettings functionSettings = FunctionSettings.Load(@".\functionSettings.json");
using (HttpClient httpClient = new HttpClient())
{
string accessToken = AzureADHelper.GetAccessTokenAsync(functionSettings.Authority, functionSettings.ApplicationId, functionSettings.ClientSecret, functionSettings.ResourceId).Result;
if (accessToken == null)
{
throw new Exception("Could not obtain access token!");
}
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
Task[] threads = new Task[_concurrentConfig.NumberOfThreads];
for (int i = 0; i < _concurrentConfig.NumberOfThreads; i++)
{
threads[i] = Task.Run(
new Action(
() => PullRecordingRunnerAsync(httpClient, functionSettings, _concurrentConfig.TestConfigurationQueue).Wait()));
}
_log.LogInformation("Waiting on threads...");
Task.WaitAll(threads);
_log.LogInformation("All threads completed...");
}
_concurrentConfig.Save(GlobalTestConstants.ConcurrentTestConfigurationFilePath);
}
/// <summary>
/// Runner to ensure PullRecordingHttpTrigger runs correctly for concurrent executions against a remote Azure Function.
/// </summary>
/// <param name="httpClient">The HttpClient instance to use.</param>
/// <param name="functionSettings">Configuration information required to make calls to the Azure Function.</param>
/// <param name="queue">The queue of tests to run.</param>
/// <returns>An asynchronous task.</returns>
public async Task PullRecordingRunnerAsync(HttpClient httpClient, FunctionSettings functionSettings, ConcurrentQueue<TestConfiguration> queue)
{
TestConfiguration nextTestConfiguration = null;
while (!queue.IsEmpty)
{
if (queue.TryDequeue(out nextTestConfiguration))
{
HttpContent requestContent = CreateHttpPostContent(nextTestConfiguration.InputId, nextTestConfiguration.CallSid);
HttpResponseMessage httpResponse = await httpClient.PostAsync(functionSettings.PullRecordingUrl, requestContent);
string responseContent = await httpResponse.Content.ReadAsStringAsync();
PullRecordingResponse response = JsonConvert.DeserializeObject<PullRecordingResponse>(responseContent);
Assert.AreEqual(nextTestConfiguration.CallSid, response.CallSid);
Assert.IsNotNull(response.RecordingUri);
// Assert.IsTrue(response.RecordingLength > 600000); // Recording size should be ~800KB
Assert.IsNotNull(response.FullRecordingUrl);
Assert.AreEqual((int)CommonStatusCode.Ok, response.StatusCode);
Assert.AreEqual(Enum.GetName(typeof(CommonStatusCode), CommonStatusCode.Ok), response.StatusDesc);
Assert.IsFalse(response.HasError);
Assert.AreEqual((int)CommonErrorCode.NoError, response.ErrorCode);
Assert.IsNull(response.ErrorDetails);
_log.LogInformation("Writing returned recording uri to test configuration...");
nextTestConfiguration.RecordingUri = response.RecordingUri;
}
TH.Thread.Sleep(2000);
}
}
/// <summary>
/// Creates an HTTP POST request for PullRecording.
/// </summary>
/// <param name="inputId">The inputId to set in the request body.</param>
/// <param name="callSid">The callSid to set in the request body.</param>
/// <returns>The HTTP request.</returns>
private static HttpRequest CreateHttpPostRequest(string inputId, string callSid)
{
HttpContext httpContext = new DefaultHttpContext();
HttpRequest request = new DefaultHttpRequest(httpContext);
PullRecordingRequest requestObj = new PullRecordingRequest()
{
InputId = inputId,
CallSid = callSid,
};
Stream contentBytes = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(requestObj)));
request.Body = contentBytes;
return request;
}
/// <summary>
/// Creates content for a request to PullRecording.
/// </summary>
/// <param name="inputId">The inputId to set in the content.</param>
/// <param name="callSid">The callSid to set in the content.</param>
/// <returns>The content.</returns>
private static HttpContent CreateHttpPostContent(string inputId, string callSid)
{
PullRecordingRequest requestObj = new PullRecordingRequest()
{
InputId = inputId,
CallSid = callSid,
};
return new StringContent(
JsonConvert.SerializeObject(requestObj));
}
}
}
| 42.309783 | 198 | 0.631535 | [
"MIT"
] | Bhaskers-Blu-Org2/AdvocacyPlatform | API/Microsoft.AdvocacyPlatform.Functions.FunctionalTests/PullRecordingFunctionalTest.cs | 15,572 | C# |
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.Events;
using EasyNetQ.FluentConfiguration;
using EasyNetQ.Topology;
using Newtonsoft.Json;
namespace EasyNetQ.Producer
{
/// <summary>
/// Default implementation of EasyNetQ's request-response pattern
/// </summary>
public class Rpc : IRpc
{
private readonly ConnectionConfiguration connectionConfiguration;
protected readonly IAdvancedBus advancedBus;
protected readonly IConventions conventions;
protected readonly IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy;
protected readonly IMessageDeliveryModeStrategy messageDeliveryModeStrategy;
private readonly ITimeoutStrategy timeoutStrategy;
private readonly ITypeNameSerializer typeNameSerializer;
private readonly object responseQueuesAddLock = new object();
private readonly ConcurrentDictionary<RpcKey, string> responseQueues = new ConcurrentDictionary<RpcKey, string>();
private readonly ConcurrentDictionary<string, ResponseAction> responseActions = new ConcurrentDictionary<string, ResponseAction>();
protected readonly TimeSpan disablePeriodicSignaling = TimeSpan.FromMilliseconds(-1);
protected const string isFaultedKey = "IsFaulted";
protected const string exceptionMessageKey = "ExceptionMessage";
public Rpc(
ConnectionConfiguration connectionConfiguration,
IAdvancedBus advancedBus,
IEventBus eventBus,
IConventions conventions,
IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy,
IMessageDeliveryModeStrategy messageDeliveryModeStrategy,
ITimeoutStrategy timeoutStrategy,
ITypeNameSerializer typeNameSerializer)
{
Preconditions.CheckNotNull(connectionConfiguration, "configuration");
Preconditions.CheckNotNull(advancedBus, "advancedBus");
Preconditions.CheckNotNull(eventBus, "eventBus");
Preconditions.CheckNotNull(conventions, "conventions");
Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "publishExchangeDeclareStrategy");
Preconditions.CheckNotNull(messageDeliveryModeStrategy, "messageDeliveryModeStrategy");
Preconditions.CheckNotNull(timeoutStrategy, "timeoutStrategy");
Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");
this.connectionConfiguration = connectionConfiguration;
this.advancedBus = advancedBus;
this.conventions = conventions;
this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy;
this.messageDeliveryModeStrategy = messageDeliveryModeStrategy;
this.timeoutStrategy = timeoutStrategy;
this.typeNameSerializer = typeNameSerializer;
eventBus.Subscribe<ConnectionCreatedEvent>(OnConnectionCreated);
}
private void OnConnectionCreated(ConnectionCreatedEvent @event)
{
var copyOfResponseActions = responseActions.Values;
responseActions.Clear();
responseQueues.Clear();
// retry in-flight requests.
foreach (var responseAction in copyOfResponseActions)
{
responseAction.OnFailure();
}
}
public virtual Task<TResponse> Request<TRequest, TResponse>(TRequest request, Action<IRequestConfiguration> configure)
where TRequest : class
where TResponse : class
{
Preconditions.CheckNotNull(request, "request");
var correlationId = Guid.NewGuid();
var requestType = typeof(TRequest);
var configuration = new RequestConfiguration();
configure(configuration);
var tcs = new TaskCompletionSource<TResponse>();
var timeout = timeoutStrategy.GetTimeoutSeconds(requestType);
Timer timer = null;
if (timeout > 0)
{
timer = new Timer(state =>
{
tcs.TrySetException(new TimeoutException(string.Format("Request timed out. CorrelationId: {0}", correlationId.ToString())));
responseActions.TryRemove(correlationId.ToString(), out ResponseAction responseAction);
}, null, TimeSpan.FromSeconds(timeout), disablePeriodicSignaling);
}
RegisterErrorHandling(correlationId, timer, tcs);
var queueName = SubscribeToResponse<TRequest, TResponse>();
var routingKey = configuration.QueueName ?? conventions.RpcRoutingKeyNamingConvention(requestType);
RequestPublish(request, routingKey, queueName, correlationId);
return tcs.Task;
}
protected void RegisterErrorHandling<TResponse>(Guid correlationId, Timer timer, TaskCompletionSource<TResponse> tcs)
where TResponse : class
{
responseActions.TryAdd(correlationId.ToString(), new ResponseAction
{
OnSuccess = message =>
{
timer?.Dispose();
var msg = ((IMessage<TResponse>)message);
bool isFaulted = false;
string exceptionMessage = "The exception message has not been specified.";
if(msg.Properties.HeadersPresent)
{
if(msg.Properties.Headers.ContainsKey(isFaultedKey))
{
isFaulted = Convert.ToBoolean(msg.Properties.Headers[isFaultedKey]);
}
if(msg.Properties.Headers.ContainsKey(exceptionMessageKey))
{
exceptionMessage = Encoding.UTF8.GetString((byte[])msg.Properties.Headers[exceptionMessageKey]);
}
}
if(isFaulted)
{
tcs.TrySetException(new EasyNetQResponderException(exceptionMessage));
}
else
{
tcs.TrySetResult(msg.Body);
}
},
OnFailure = () =>
{
timer?.Dispose();
tcs.TrySetException(new EasyNetQException("Connection lost while request was in-flight. CorrelationId: {0}", correlationId.ToString()));
}
});
}
protected virtual string SubscribeToResponse<TRequest, TResponse>()
where TResponse : class
{
var responseType = typeof(TResponse);
var rpcKey = new RpcKey { Request = typeof(TRequest), Response = responseType };
string queueName;
if (responseQueues.TryGetValue(rpcKey, out queueName))
return queueName;
lock (responseQueuesAddLock)
{
if (responseQueues.TryGetValue(rpcKey, out queueName))
return queueName;
var queue = advancedBus.QueueDeclare(
conventions.RpcReturnQueueNamingConvention(),
passive: false,
durable: false,
exclusive: true,
autoDelete: true);
var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(responseType));
advancedBus.Bind(exchange, queue, queue.Name);
advancedBus.Consume<TResponse>(queue, (message, messageReceivedInfo) => Task.Factory.StartNew(() =>
{
ResponseAction responseAction;
if(responseActions.TryRemove(message.Properties.CorrelationId, out responseAction))
{
responseAction.OnSuccess(message);
}
}));
responseQueues.TryAdd(rpcKey, queue.Name);
return queue.Name;
}
}
protected struct RpcKey
{
public Type Request;
public Type Response;
}
protected class ResponseAction
{
public Action<object> OnSuccess { get; set; }
public Action OnFailure { get; set; }
}
protected virtual void RequestPublish<TRequest>(TRequest request, string routingKey, string returnQueueName, Guid correlationId)
where TRequest : class
{
var requestType = typeof(TRequest);
var exchange = publishExchangeDeclareStrategy.DeclareExchange(conventions.RpcRequestExchangeNamingConvention(requestType), ExchangeType.Direct);
var requestMessage = new Message<TRequest>(request)
{
Properties =
{
ReplyTo = returnQueueName,
CorrelationId = correlationId.ToString(),
Expiration = (timeoutStrategy.GetTimeoutSeconds(requestType) * 1000).ToString(),
DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(requestType)
}
};
advancedBus.Publish(exchange, routingKey, false, requestMessage);
}
public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder)
where TRequest : class
where TResponse : class
{
return Respond(responder, c => { });
}
public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class
{
Preconditions.CheckNotNull(responder, "responder");
Preconditions.CheckNotNull(configure, "configure");
// We're explicitly validating TResponse here because the type won't be used directly.
// It'll only be used when executing a successful responder, which will silently fail if TResponse serialized length exceeds the limit.
Preconditions.CheckShortString(typeNameSerializer.Serialize(typeof(TResponse)), "TResponse");
var requestType = typeof(TRequest);
var configuration = new ResponderConfiguration(connectionConfiguration.PrefetchCount);
configure(configuration);
var routingKey = configuration.QueueName ?? conventions.RpcRoutingKeyNamingConvention(requestType);
var exchange = advancedBus.ExchangeDeclare(conventions.RpcRequestExchangeNamingConvention(requestType), ExchangeType.Direct);
var queue = advancedBus.QueueDeclare(routingKey);
advancedBus.Bind(exchange, queue, routingKey);
return advancedBus.Consume<TRequest>(queue, (requestMessage, messageReceivedInfo) => ExecuteResponder(responder, requestMessage),
c => c.WithPrefetchCount(configuration.PrefetchCount));
}
protected Task ExecuteResponder<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, IMessage<TRequest> requestMessage)
where TRequest : class
where TResponse : class
{
var tcs = new TaskCompletionSource<object>();
try
{
responder(requestMessage.Body).ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
var exception = task.IsCanceled
? new EasyNetQResponderException("The responder task was cancelled.")
: task.Exception?.InnerException ?? new EasyNetQResponderException("The responder faulted while dispatching the message.");
OnResponderFailure<TRequest, TResponse>(requestMessage, exception.Message, exception);
tcs.SetException(exception);
}
else
{
OnResponderSuccess(requestMessage, task.Result);
tcs.SetResult(null);
}
});
}
catch (Exception e)
{
OnResponderFailure<TRequest, TResponse>(requestMessage, e.Message, e);
tcs.SetException(e);
}
return tcs.Task;
}
protected virtual void OnResponderSuccess<TRequest, TResponse>(IMessage<TRequest> requestMessage, TResponse response)
where TRequest : class
where TResponse : class
{
var responseMessage = new Message<TResponse>(response)
{
Properties =
{
CorrelationId = requestMessage.Properties.CorrelationId,
DeliveryMode = MessageDeliveryMode.NonPersistent
}
};
var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(typeof(TResponse)));
advancedBus.Publish(exchange, requestMessage.Properties.ReplyTo, false, responseMessage);
}
protected virtual void OnResponderFailure<TRequest, TResponse>(IMessage<TRequest> requestMessage, string exceptionMessage, Exception exception)
where TRequest : class
where TResponse : class
{
// HACK: I think we can live with this, because it will run only on exception,
// it tries to preserve the default serialization behavior,
// being able to also deserialize POCO objects that has constructors with parameters
// this avoids to introduce a custom class wrapper that will change the message payload
var body = JsonConvert.DeserializeObject<TResponse>(typeof(TResponse) == typeof(string) ? "''" : "{}");
var responseMessage = new Message<TResponse>(body);
responseMessage.Properties.Headers.Add(isFaultedKey, true);
responseMessage.Properties.Headers.Add(exceptionMessageKey, exceptionMessage);
responseMessage.Properties.CorrelationId = requestMessage.Properties.CorrelationId;
responseMessage.Properties.DeliveryMode = MessageDeliveryMode.NonPersistent;
var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(typeof(TResponse)));
advancedBus.Publish(exchange, requestMessage.Properties.ReplyTo, false, responseMessage);
}
private IExchange DeclareRpcExchange(string exchangeName)
{
return publishExchangeDeclareStrategy.DeclareExchange(exchangeName, ExchangeType.Direct);
}
}
} | 45.042169 | 196 | 0.615019 | [
"MIT"
] | mariuszwojcik/EasyNetQ | Source/EasyNetQ/Producer/Rpc.cs | 14,956 | C# |
using System.ComponentModel;
using System.Drawing.Design;
using System.Drawing;
using System.Windows.Forms;
namespace osfDesigner
{
public class DataGridTableStyle : System.Windows.Forms.DataGridTableStyle
{
public System.Windows.Forms.DataGridTableStyle M_DataGridTableStyle;
[Browsable(false)]
public System.Windows.Forms.DataGridTableStyle OriginalObj
{
get { return M_DataGridTableStyle; }
set { M_DataGridTableStyle = value; }
}
public DataGridTableStyle()
{
}
[DisplayName("ИмяОтображаемого")]
[Description("Возвращает или задает имя, используемое для сопоставления этой таблицы с конкретным источником данных.")]
[Category("Прочее")]
[Browsable(true)]
public new string MappingName
{
get { return M_DataGridTableStyle.MappingName; }
set { M_DataGridTableStyle.MappingName = value; }
}
[DisplayName("ОсновнойЦвет")]
[Description("Возвращает или задает основной цвет таблицы.")]
[Category("Цвета")]
[Browsable(true)]
[TypeConverter(typeof(MyColorConverter))]
[Editor(typeof(MyColorEditor), typeof(UITypeEditor))]
public new Color ForeColor
{
get { return M_DataGridTableStyle.ForeColor; }
set { M_DataGridTableStyle.ForeColor = value; }
}
[DisplayName("ОсновнойЦветЗаголовков")]
[Description("Возвращает или задает основной цвет заголовков.")]
[Category("Цвета")]
[Browsable(true)]
[TypeConverter(typeof(MyColorConverter))]
[Editor(typeof(MyColorEditor), typeof(UITypeEditor))]
public new Color HeaderForeColor
{
get { return M_DataGridTableStyle.HeaderForeColor; }
set { M_DataGridTableStyle.HeaderForeColor = value; }
}
[DisplayName("ОтображатьЗаголовкиСтолбцов")]
[Description("Возвращает или задает значение, показывающее, являются ли заголовки столбцов видимыми.")]
[Category("Показать")]
[Browsable(true)]
[TypeConverter(typeof(MyBooleanConverter))]
public new bool ColumnHeadersVisible
{
get { return M_DataGridTableStyle.ColumnHeadersVisible; }
set { M_DataGridTableStyle.ColumnHeadersVisible = value; }
}
[DisplayName("ОтображатьЗаголовкиСтрок")]
[Description("Возвращает или задает значение, показывающее, являются ли заголовки строк видимыми.")]
[Category("Показать")]
[Browsable(true)]
[TypeConverter(typeof(MyBooleanConverter))]
public new bool RowHeadersVisible
{
get { return M_DataGridTableStyle.RowHeadersVisible; }
set { M_DataGridTableStyle.RowHeadersVisible = value; }
}
[DisplayName("ПредпочтительнаяВысотаСтрок")]
[Description("Возвращает или задает высоту, используемую для создания строк при отображении новой сетки.")]
[Category("Макет")]
[Browsable(true)]
public new int PreferredRowHeight
{
get { return M_DataGridTableStyle.PreferredRowHeight; }
set { M_DataGridTableStyle.PreferredRowHeight = value; }
}
[DisplayName("ПредпочтительнаяШиринаСтолбцов")]
[Description("Возвращает или задает ширину, используемую для создания столбцов при отображении новой сетки.")]
[Category("Макет")]
[Browsable(true)]
public new int PreferredColumnWidth
{
get { return M_DataGridTableStyle.PreferredColumnWidth; }
set { M_DataGridTableStyle.PreferredColumnWidth = value; }
}
[DisplayName("РазрешитьСортировку")]
[Description("Возвращает или задает значение, показывающее, разрешена ли сортировка в таблице.")]
[Category("Поведение")]
[Browsable(true)]
[TypeConverter(typeof(MyBooleanConverter))]
public new bool AllowSorting
{
get { return M_DataGridTableStyle.AllowSorting; }
set { M_DataGridTableStyle.AllowSorting = value; }
}
[DisplayName("СтилиКолонкиСеткиДанных")]
[Description("Возвращает коллекцию колонок, нарисованных для этой таблицы.")]
[Category("Прочее")]
[Browsable(true)]
[TypeConverter(typeof(MyCollectionConverter))]
[Editor(typeof(MyGridColumnStylesCollectionEditor), typeof(UITypeEditor))]
public new GridColumnStylesCollection GridColumnStyles
{
get { return M_DataGridTableStyle.GridColumnStyles; }
}
[DisplayName("ТолькоЧтение")]
[Description("Возвращает или задает значение, показывающее, разрешено ли редактирование столбцов.")]
[Category("Прочее")]
[Browsable(true)]
[TypeConverter(typeof(MyBooleanConverter))]
public new bool ReadOnly
{
get { return M_DataGridTableStyle.ReadOnly; }
set { M_DataGridTableStyle.ReadOnly = value; }
}
[DisplayName("ЦветСетки")]
[Description("Возвращает или задает цвет линий сетки.")]
[Category("Цвета")]
[Browsable(true)]
[TypeConverter(typeof(MyColorConverter))]
[Editor(typeof(MyColorEditor), typeof(UITypeEditor))]
public new Color GridLineColor
{
get { return M_DataGridTableStyle.GridLineColor; }
set { M_DataGridTableStyle.GridLineColor = value; }
}
[DisplayName("ЦветФона")]
[Description("Возвращает или задает цвет фона строк сетки с четными номерами.")]
[Category("Цвета")]
[Browsable(true)]
[TypeConverter(typeof(MyColorConverter))]
[Editor(typeof(MyColorEditor), typeof(UITypeEditor))]
public new Color BackColor
{
get { return M_DataGridTableStyle.BackColor; }
set { M_DataGridTableStyle.BackColor = value; }
}
[DisplayName("ЦветФонаЗаголовков")]
[Description("Возвращает или задает цвет фона заголовков.")]
[Category("Цвета")]
[Browsable(true)]
[TypeConverter(typeof(MyColorConverter))]
[Editor(typeof(MyColorEditor), typeof(UITypeEditor))]
public new Color HeaderBackColor
{
get { return M_DataGridTableStyle.HeaderBackColor; }
set { M_DataGridTableStyle.HeaderBackColor = value; }
}
[DisplayName("ЦветФонаНечетныхСтрок")]
[Description("Возвращает или задает цвет фона строк сетки с нечетными номерами.")]
[Category("Цвета")]
[Browsable(true)]
[TypeConverter(typeof(MyColorConverter))]
[Editor(typeof(MyColorEditor), typeof(UITypeEditor))]
public new Color AlternatingBackColor
{
get { return M_DataGridTableStyle.AlternatingBackColor; }
set { M_DataGridTableStyle.AlternatingBackColor = value; }
}
[DisplayName("ШиринаЗаголовковСтрок")]
[Description("Возвращает или задает ширину заголовков строк.")]
[Category("Макет")]
[Browsable(true)]
public new int RowHeaderWidth
{
get { return M_DataGridTableStyle.RowHeaderWidth; }
set { M_DataGridTableStyle.RowHeaderWidth = value; }
}
[DisplayName("ШрифтЗаголовков")]
[Description("Возвращает или задает шрифт, используемый для названий заголовков.")]
[Category("Внешний вид")]
[Browsable(true)]
[TypeConverter(typeof(MyFontConverter))]
public new Font HeaderFont
{
get { return M_DataGridTableStyle.HeaderFont; }
set { M_DataGridTableStyle.HeaderFont = value; }
}
[Browsable(false)]
[ReadOnly(true)]
public new System.Windows.Forms.DataGridLineStyle GridLineStyle { get; set; }
[Browsable(false)]
[ReadOnly(true)]
public new System.Drawing.Color LinkColor { get; set; }
[Browsable(false)]
[ReadOnly(true)]
public new System.Drawing.Color SelectionBackColor { get; set; }
[Browsable(false)]
[ReadOnly(true)]
public new System.Drawing.Color SelectionForeColor { get; set; }
[DisplayName("ИмяСтиля")]
[Category("Прочее")]
[Browsable(true)]
[ReadOnly(true)]
public string NameStyle { get; set; }
[DisplayName("Текст")]
[Category("Прочее")]
[Browsable(true)]
public string Text { get; set; }
[Browsable(false)]
public string DefaultValues { get; set; }
[Browsable(false)]
public string RequiredValues
{
get
{
return @"
СтилиКолонкиСеткиДанных ==
Текст ==
";
}
}
}
}
| 36.17623 | 127 | 0.626713 | [
"MPL-2.0"
] | ahyahy/OneScriptFormsDesigner | OneScriptFormsDesigner/DataGridTableStyle.cs | 10,220 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DDPA.DTO
{
public class SMTPOptions
{
public string UserName { get; set; }
public string Password { get; set; }
public string FromName { get; set; }
public string FromAddress { get; set; }
public string DeliveryMethod { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public bool EnableSsl { get; set; }
}
}
| 19.115385 | 50 | 0.599598 | [
"MIT"
] | docukit-dpa/ddpa | src/ddpa-core/DDPA.DTO/Main/Support/SMTPOptions.cs | 499 | C# |
using Nano.Net.Extensions;
using Xunit;
namespace Nano.Net.Tests;
public class AccountTest
{
[Fact]
public void NewAccount_FromPrivateKey_ValidAddress()
{
var account = new Account(privateKey: "066A6E2AC1E75E18A6D0A9586348245FB302D9ECE17D4557EAF2AEF8C6E0DA90");
Assert.Equal("nano_3fkaipau6kpfejzsr6c4itkm3zkf3jqd9dxkccr3so5fbypop4uu9f4fcacz", account.Address);
}
[Fact]
public void NewAccount_FromSeed_ValidProperties()
{
var account = new Account("7B58BB18E887F5146DD46ACAD89E5139D363F5F4A50DE9A0B465217A51D1BFDF", 63);
Assert.Equal("003D0478B4E3F01889A0E9BB149C701E90EFC0E1BC1702671AA9790F71FED69E".HexToBytes(), account.PrivateKey);
Assert.Equal("83778F31E96011CC3C132680A512FECC24E33174F4FB8443A583D6B30F744AAA".HexToBytes(), account.PublicKey);
Assert.Equal("nano_31uqjwrykr1jsiy38bn1nnbhxm36werqbx9uij3td1yppe9qakocutbzzmd9", account.Address);
}
}
| 37.88 | 122 | 0.780359 | [
"MIT"
] | RestoreMonarchy/Nano.Net | Nano.Net.Tests/AccountTest.cs | 947 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.34014
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Genlog.Properties {
using System;
/// <summary>
/// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées.
/// </summary>
// Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder
// à l'aide d'un outil, tel que ResGen ou Visual Studio.
// Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen
// avec l'option /str ou régénérez votre projet VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Retourne l'instance ResourceManager mise en cache utilisée par cette classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Genlog.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Remplace la propriété CurrentUICulture du thread actuel pour toutes
/// les recherches de ressources à l'aide de cette classe de ressource fortement typée.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 45.890625 | 172 | 0.625468 | [
"MIT"
] | skaaj/genlog | Solution/Application/Properties/Resources.Designer.cs | 2,971 | C# |
namespace Karoterra.AupDotNet.ExEdit
{
/// <summary>
/// フィルタ効果のファクトリを表すインタフェース。
/// </summary>
public interface IEffectFactory
{
/// <summary>
/// フィルタ効果を生成します。
/// </summary>
/// <param name="type">フィルタ効果定義</param>
/// <param name="trackbars">トラックバー情報</param>
/// <param name="checkboxes">チェックボックス情報</param>
/// <param name="data">拡張データ</param>
/// <returns>フィルタ効果</returns>
Effect Create(EffectType type, Trackbar[] trackbars, int[] checkboxes, byte[] data);
}
}
| 29.578947 | 92 | 0.572954 | [
"MIT"
] | karoterra/AupDotNet | src/AupDotNet/ExEdit/IEffectFactory.cs | 708 | C# |
using System.Collections.Generic;
using FluentAssertions;
using Monifier.BusinessLogic.Distribution;
using Monifier.BusinessLogic.Model.Base;
using Monifier.BusinessLogic.Model.Expenses;
using Monifier.DataAccess.Model.Base;
using Xunit;
namespace Monifier.BusinessLogic.Model.Tests
{
public class DistributionModelTests
{
public DistributionModelTests()
{
DebitCardAccount = new AccountModel
{
Id = 1,
AccountType = AccountType.DebitCard,
AvailBalance = 15000
};
CashAccount = new AccountModel
{
Id = 2,
AccountType = AccountType.Cash,
AvailBalance = 1200
};
FoodFlow = new ExpenseFlowModel
{
Id = 1,
Balance = 100,
};
TechFlow = new ExpenseFlowModel
{
Id = 2,
Balance = 0
};
Debit = new DistributionAccount
{
Account = DebitCardAccount,
UseInDistribution = true
};
Cash = new DistributionAccount
{
Account = CashAccount,
UseInDistribution = true
};
Food = new DistributionItem
{
Flow = FoodFlow,
Mode = DistributionMode.RegularExpenses,
Amount = 10000
};
Tech = new DistributionItem
{
Flow = TechFlow,
Mode = DistributionMode.Accumulation,
Amount = 1000
};
Model = new DistributionModel
{
Accounts = new List<DistributionAccount> { Debit, Cash },
Items = new List<DistributionItem> { Food, Tech }
};
}
[Fact]
public void DefaultCase_Test()
{
Model.FlowFund.ShouldBeEquivalentTo(100);
Model.TotalFund.ShouldBeEquivalentTo(16300);
Model.Total.ShouldBeEquivalentTo(11000);
Model.CanDistribute.Should().BeTrue();
}
[Fact]
public void NegativeAccountBalance_Test()
{
CashAccount.AvailBalance = -1000;
Model.FlowFund.ShouldBeEquivalentTo(100);
Model.TotalFund.ShouldBeEquivalentTo(15100);
Model.Total.ShouldBeEquivalentTo(11000);
Model.CanDistribute.Should().BeTrue();
}
[Fact]
public void NegativeFlowBalance_Test()
{
FoodFlow.Balance = -100;
Model.FlowFund.ShouldBeEquivalentTo(0);
Model.TotalFund.ShouldBeEquivalentTo(16200);
Model.Total.ShouldBeEquivalentTo(11100);
Model.CanDistribute.Should().BeTrue();
}
[Fact]
public void CompensateWithAccumulativeFlow_Test()
{
TechFlow.Balance = 10000;
Tech.Amount = 8000;
Model.FlowFund.ShouldBeEquivalentTo(2100);
Model.TotalFund.ShouldBeEquivalentTo(18300);
Model.Total.ShouldBeEquivalentTo(10000);
Model.CanDistribute.Should().BeTrue();
}
[Fact]
public void TotalAboveFund_CantDistribute_Test()
{
Tech.Amount = 15000;
Model.FlowFund.ShouldBeEquivalentTo(100);
Model.TotalFund.ShouldBeEquivalentTo(16300);
Model.Total.ShouldBeEquivalentTo(25000);
Model.CanDistribute.Should().BeFalse();
}
[Fact]
public void ExludeAccount_Test()
{
Cash.UseInDistribution = false;
Model.FlowFund.ShouldBeEquivalentTo(100);
Model.TotalFund.ShouldBeEquivalentTo(15100);
Model.Total.ShouldBeEquivalentTo(11000);
Model.CanDistribute.Should().BeTrue();
}
[Fact]
public void NonZeroAccumulativeFlow_Test()
{
TechFlow.Balance = 1000;
Tech.Amount = 3000;
Model.FlowFund.ShouldBeEquivalentTo(100);
Model.TotalFund.ShouldBeEquivalentTo(16300);
Model.Total.ShouldBeEquivalentTo(12000);
Model.CanDistribute.Should().BeTrue();
}
[Fact]
public void NegativeAccumulatuveFlowBalance_Test()
{
TechFlow.Balance = -1500;
Model.FlowFund.ShouldBeEquivalentTo(100);
Model.TotalFund.ShouldBeEquivalentTo(16300);
Model.Total.ShouldBeEquivalentTo(12500);
Model.CanDistribute.Should().BeTrue();
}
public AccountModel DebitCardAccount { get; }
public AccountModel CashAccount { get; }
public ExpenseFlowModel FoodFlow { get; }
public ExpenseFlowModel TechFlow { get; }
public DistributionAccount Debit { get; }
public DistributionAccount Cash { get; }
public DistributionItem Food { get; }
public DistributionItem Tech { get; }
public DistributionModel Model { get; }
}
} | 32.574074 | 74 | 0.539132 | [
"MIT"
] | Ivan-Proskurin/Monifier | Monifier.BusinessLogic.Model.Tests/DistributionModelTests.cs | 5,279 | C# |
using System.Xml;
namespace Doc.Odf
{
public class BaseStyle : DocumentElementCollection
{
public BaseStyle(ODFDocument document, XmlElement Element)
: base(document, Element)
{ }
public string Name
{
get { return Element.GetAttribute("style:name"); }
set { Service.SetAttribute(Element, "style:name", Service.nsStyle, value); }
}
}
} | 25.882353 | 89 | 0.577273 | [
"MIT"
] | alexandrvslv/datawf | DataWF.Odf/Style/BaseStyle.cs | 442 | C# |
using Ryujinx.HLE.HOS.Ipc;
using System.Collections.Generic;
namespace Ryujinx.HLE.HOS.Services.Aud
{
class IHardwareOpusDecoderManager : IpcService
{
private Dictionary<int, ServiceProcessRequest> _commands;
public override IReadOnlyDictionary<int, ServiceProcessRequest> Commands => _commands;
public IHardwareOpusDecoderManager()
{
_commands = new Dictionary<int, ServiceProcessRequest>
{
{ 0, Initialize },
{ 1, GetWorkBufferSize }
};
}
public long Initialize(ServiceCtx context)
{
int sampleRate = context.RequestData.ReadInt32();
int channelsCount = context.RequestData.ReadInt32();
MakeObject(context, new IHardwareOpusDecoder(sampleRate, channelsCount));
return 0;
}
public long GetWorkBufferSize(ServiceCtx context)
{
//Note: The sample rate is ignored because it is fixed to 48KHz.
int sampleRate = context.RequestData.ReadInt32();
int channelsCount = context.RequestData.ReadInt32();
context.ResponseData.Write(GetOpusDecoderSize(channelsCount));
return 0;
}
private static int GetOpusDecoderSize(int channelsCount)
{
const int silkDecoderSize = 0x2198;
if (channelsCount < 1 || channelsCount > 2)
{
return 0;
}
int celtDecoderSize = GetCeltDecoderSize(channelsCount);
int opusDecoderSize = (channelsCount * 0x800 + 0x4807) & -0x800 | 0x50;
return opusDecoderSize + silkDecoderSize + celtDecoderSize;
}
private static int GetCeltDecoderSize(int channelsCount)
{
const int decodeBufferSize = 0x2030;
const int celtDecoderSize = 0x58;
const int celtSigSize = 0x4;
const int overlap = 120;
const int eBandsCount = 21;
return (decodeBufferSize + overlap * 4) * channelsCount +
eBandsCount * 16 +
celtDecoderSize +
celtSigSize;
}
}
}
| 30.753425 | 94 | 0.579955 | [
"Unlicense"
] | AlexLavoie42/Ryujinx | Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoderManager.cs | 2,245 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26.Maps
{
using V26;
/// <summary>
/// TCU_U10_TEST_CONFIGURATION (GroupMap) -
/// </summary>
public class TCU_U10_TEST_CONFIGURATIONMap :
HL7V26LayoutMap<TCU_U10_TEST_CONFIGURATION>
{
public TCU_U10_TEST_CONFIGURATIONMap()
{
Segment(x => x.SPM, 0);
Segment(x => x.TCC, 1, x => x.Required = true);
}
}
} | 30.8 | 105 | 0.644481 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.HL7Schema/Generated/V26/Groups/Maps/TCU_U10_TEST_CONFIGURATIONMap.cs | 616 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: general.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using scg = global::System.Collections.Generic;
namespace General {
#region Messages
/// <summary>
///定义武将信息结构
/// </summary>
public sealed class general_info : pb::IMessage {
private static readonly pb::MessageParser<general_info> _parser = new pb::MessageParser<general_info>(() => new general_info());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<general_info> Parser { get { return _parser; } }
/// <summary>Field number for the "index" field.</summary>
public const int IndexFieldNumber = 1;
private uint index_;
/// <summary>
///武将索引
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Index {
get { return index_; }
set {
index_ = value;
}
}
/// <summary>Field number for the "gid" field.</summary>
public const int GidFieldNumber = 2;
private uint gid_;
/// <summary>
///武将id
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Gid {
get { return gid_; }
set {
gid_ = value;
}
}
/// <summary>Field number for the "army_id" field.</summary>
public const int ArmyIdFieldNumber = 3;
private uint armyId_;
/// <summary>
///所属军团(1-5) 0表示不在军团
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint ArmyId {
get { return armyId_; }
set {
armyId_ = value;
}
}
/// <summary>Field number for the "pos" field.</summary>
public const int PosFieldNumber = 4;
private uint pos_;
/// <summary>
///阵位编号(1-6) 0表示不在军团
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Pos {
get { return pos_; }
set {
pos_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Index != 0) {
output.WriteRawTag(8);
output.WriteUInt32(Index);
}
if (Gid != 0) {
output.WriteRawTag(16);
output.WriteUInt32(Gid);
}
if (ArmyId != 0) {
output.WriteRawTag(24);
output.WriteUInt32(ArmyId);
}
if (Pos != 0) {
output.WriteRawTag(32);
output.WriteUInt32(Pos);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Index != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Index);
}
if (Gid != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Gid);
}
if (ArmyId != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(ArmyId);
}
if (Pos != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Pos);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Index = input.ReadUInt32();
break;
}
case 16: {
Gid = input.ReadUInt32();
break;
}
case 24: {
ArmyId = input.ReadUInt32();
break;
}
case 32: {
Pos = input.ReadUInt32();
break;
}
}
}
}
}
/// <summary>
///获取所有武将信息
/// </summary>
public sealed class req_getAll : pb::IMessage {
private static readonly pb::MessageParser<req_getAll> _parser = new pb::MessageParser<req_getAll>(() => new req_getAll());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<req_getAll> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
public sealed class rsp_getAll : pb::IMessage {
private static readonly pb::MessageParser<rsp_getAll> _parser = new pb::MessageParser<rsp_getAll>(() => new rsp_getAll());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<rsp_getAll> Parser { get { return _parser; } }
/// <summary>Field number for the "generals" field.</summary>
public const int GeneralsFieldNumber = 1;
private static readonly pb::FieldCodec<global::General.general_info> _repeated_generals_codec
= pb::FieldCodec.ForMessage(10, global::General.general_info.Parser);
private readonly pbc::RepeatedField<global::General.general_info> generals_ = new pbc::RepeatedField<global::General.general_info>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::General.general_info> Generals {
get { return generals_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
generals_.WriteTo(output, _repeated_generals_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += generals_.CalculateSize(_repeated_generals_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
generals_.AddEntriesFrom(input, _repeated_generals_codec);
break;
}
}
}
}
}
/// <summary>
///武将布阵
/// </summary>
public sealed class req_embattle : pb::IMessage {
private static readonly pb::MessageParser<req_embattle> _parser = new pb::MessageParser<req_embattle>(() => new req_embattle());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<req_embattle> Parser { get { return _parser; } }
/// <summary>Field number for the "index" field.</summary>
public const int IndexFieldNumber = 1;
private uint index_;
/// <summary>
///武将索引
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Index {
get { return index_; }
set {
index_ = value;
}
}
/// <summary>Field number for the "army_id" field.</summary>
public const int ArmyIdFieldNumber = 2;
private uint armyId_;
/// <summary>
///军团编号(1-5) 0表示下阵
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint ArmyId {
get { return armyId_; }
set {
armyId_ = value;
}
}
/// <summary>Field number for the "pos" field.</summary>
public const int PosFieldNumber = 3;
private uint pos_;
/// <summary>
///阵位编号(1-6) 0表示下阵
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint Pos {
get { return pos_; }
set {
pos_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Index != 0) {
output.WriteRawTag(8);
output.WriteUInt32(Index);
}
if (ArmyId != 0) {
output.WriteRawTag(16);
output.WriteUInt32(ArmyId);
}
if (Pos != 0) {
output.WriteRawTag(24);
output.WriteUInt32(Pos);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Index != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Index);
}
if (ArmyId != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(ArmyId);
}
if (Pos != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Pos);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Index = input.ReadUInt32();
break;
}
case 16: {
ArmyId = input.ReadUInt32();
break;
}
case 24: {
Pos = input.ReadUInt32();
break;
}
}
}
}
}
public sealed class rsp_embattle : pb::IMessage {
private static readonly pb::MessageParser<rsp_embattle> _parser = new pb::MessageParser<rsp_embattle>(() => new rsp_embattle());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<rsp_embattle> Parser { get { return _parser; } }
/// <summary>Field number for the "changes" field.</summary>
public const int ChangesFieldNumber = 1;
private static readonly pb::FieldCodec<global::General.general_info> _repeated_changes_codec
= pb::FieldCodec.ForMessage(10, global::General.general_info.Parser);
private readonly pbc::RepeatedField<global::General.general_info> changes_ = new pbc::RepeatedField<global::General.general_info>();
/// <summary>
///发生变化的武将
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::General.general_info> Changes {
get { return changes_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
changes_.WriteTo(output, _repeated_changes_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += changes_.CalculateSize(_repeated_changes_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
changes_.AddEntriesFrom(input, _repeated_changes_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 29.417323 | 137 | 0.613223 | [
"Apache-2.0"
] | fqkw6/ILRuntimeMyFrame | protobuf3.4.1Tool/Protoc_3.4.0_bin/OutputC#/General.cs | 11,358 | 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("16.BitsExchangeAdvanced")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("16.BitsExchangeAdvanced")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("eb8a59a1-3942-4e76-8f0d-a9315d1221c8")]
// 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.351351 | 84 | 0.74771 | [
"MIT"
] | TsvetanRazsolkov/Telerik-Academy | Homeworks/Programming/C# Basics - Part I/05-OperatorsAndExpressions/16.BitsExchangeAdvanced/Properties/AssemblyInfo.cs | 1,422 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
//inputs
public Controls controls;
Vector2 inputs;
[HideInInspector]
public Vector2 inputNormalized;
[HideInInspector]
public float rotation;
bool run = true, jump;
[HideInInspector]
public bool steer, autoRun;
//velocity
Vector3 velocity;
float gravity = -18, velocityY, terminalVelocity = -25;
float fallMult;
//Running
float currentSpeed;
public float baseSpeed = 1, runSpeed = 4, rotateSpeed = 2;
//ground
Vector3 forwardDirection, collisionPoint;
float slopeAngle, directionAngle, forwardAngle, strafeAngle;
float forwardMult, strafeMult;
Ray groundRay;
RaycastHit groundHit;
//Jumping
bool jumping;
float jumpSpeed, jumpHeight = 3;
Vector3 jumpDirection;
//Debug
public bool showGroundRay, showMoveDirection, showForwardDirection, showStrafeDirection, showFallNormal;
//references
CharacterController controller;
public Transform groundDirection, moveDirection, fallDirection;
[HideInInspector]
public CameraController mainCam;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
GetInputs();
Locomotion();
}
void Locomotion()
{
GroundDirection();
//running and walking
if (controller.isGrounded && slopeAngle <= controller.slopeLimit)
{
currentSpeed = baseSpeed;
if (run)
{
currentSpeed *= runSpeed;
if (inputNormalized.y < 0)
currentSpeed = currentSpeed / 2;
}
}
else if(!controller.isGrounded || slopeAngle > controller.slopeLimit)
{
inputNormalized = Vector2.Lerp(inputNormalized, Vector2.zero, 0.025f);
currentSpeed = Mathf.Lerp(currentSpeed, 0, 0.025f);
}
//Rotating
Vector3 characterRotation = transform.eulerAngles + new Vector3(0, rotation * rotateSpeed, 0);
transform.eulerAngles = characterRotation;
//Press space to Jump
if (jump && controller.isGrounded && slopeAngle <= controller.slopeLimit)
Jump();
//apply gravity if not grounded
if (!controller.isGrounded && velocityY > terminalVelocity)
velocityY += gravity * Time.deltaTime;
else if (controller.isGrounded && slopeAngle > controller.slopeLimit)
velocityY = Mathf.Lerp(velocityY, terminalVelocity, 0.25f);
//Applying inputs
if (!jumping)
{
velocity = groundDirection.forward * inputNormalized.y * forwardMult + groundDirection.right * inputNormalized.x * strafeMult; //Applying movement direction inputs
velocity *= currentSpeed; //Applying current move speed
velocity += fallDirection.up * (velocityY * fallMult); //Gravity
}
else
velocity = jumpDirection * jumpSpeed + Vector3.up * velocityY;
//moving controller
controller.Move(velocity * Time.deltaTime);
if(controller.isGrounded)
{
//stop jumping if grounded
if(jumping)
jumping = false;
// stop gravity if grounded
velocityY = 0;
}
}
void GroundDirection()
{
//SETTING FORWARDDIRECTION
//Setting forwardDirection to controller position
forwardDirection = transform.position;
//Setting forwardDirection based on control input.
if (inputNormalized.magnitude > 0)
forwardDirection += transform.forward * inputNormalized.y + transform.right * inputNormalized.x;
else
forwardDirection += transform.forward;
//Setting groundDirection to look in the forwardDirection normal
moveDirection.LookAt(forwardDirection);
fallDirection.rotation = transform.rotation;
groundDirection.rotation = transform.rotation;
//setting ground ray
groundRay.origin = transform.position + collisionPoint + Vector3.up * 0.05f;
groundRay.direction = Vector3.down;
if(showGroundRay)
Debug.DrawLine(groundRay.origin, groundRay.origin + Vector3.down * 0.3f, Color.red);
forwardMult = 1;
fallMult = 1;
strafeMult = 1;
if (Physics.Raycast(groundRay, out groundHit, 0.3f))
{
//Getting angles
slopeAngle = Vector3.Angle(transform.up, groundHit.normal);
directionAngle = Vector3.Angle(moveDirection.forward, groundHit.normal) - 90;
if (directionAngle < 0 && slopeAngle <= controller.slopeLimit)
{
forwardAngle = Vector3.Angle(transform.forward, groundHit.normal) - 90; //Chekcing the forwardAngle against the slope
forwardMult = 1 / Mathf.Cos(forwardAngle * Mathf.Deg2Rad); //Applying the forward movement multiplier based on the forwardAngle
groundDirection.eulerAngles += new Vector3(-forwardAngle, 0, 0); //Rotating groundDirection X
strafeAngle = Vector3.Angle(groundDirection.right, groundHit.normal) - 90; //Checking the strafeAngle against the slope
strafeMult = 1 / Mathf.Cos(strafeAngle * Mathf.Deg2Rad); //Applying the strafe movement multiplier based on the strafeAngle
groundDirection.eulerAngles += new Vector3(0, 0, strafeAngle);
}
else if(slopeAngle > controller.slopeLimit)
{
float groundDistance = Vector3.Distance(groundRay.origin, groundHit.point);
if(groundDistance <= 0.1f)
{
fallMult = 1 / Mathf.Cos((90 - slopeAngle) * Mathf.Deg2Rad);
Vector3 groundCross = Vector3.Cross(groundHit.normal, Vector3.up);
fallDirection.rotation = Quaternion.FromToRotation(transform.up, Vector3.Cross(groundCross, groundHit.normal));
}
}
}
DebugGroundNormals();
}
void Jump()
{
//set Jumping to true
if(!jumping)
jumping = true;
//Set jump direction and speed
jumpDirection = (transform.forward * inputs.y + transform.right * inputs.x).normalized;
jumpSpeed = currentSpeed;
//set velocity Y
velocityY = Mathf.Sqrt(-gravity * jumpHeight);
}
void GetInputs()
{
if (controls.autoRun.GetControlBindingDown())
autoRun = !autoRun;
//FORWARDS BACKWARDS CONTROLS
inputs.y = Axis(controls.forwards.GetControlBinding(), controls.backwards.GetControlBinding());
if (inputs.y != 0 && !mainCam.autoRunReset)
autoRun = false;
if(autoRun)
{
inputs.y += Axis(true, false);
inputs.y = Mathf.Clamp(inputs.y, -1, 1);
}
//STRAFE LEFT RIGHT
inputs.x = Axis(controls.strafeRight.GetControlBinding(), controls.strafeLeft.GetControlBinding());
if(steer)
{
inputs.x += Axis(controls.rotateRight.GetControlBinding(), controls.rotateLeft.GetControlBinding());
inputs.x = Mathf.Clamp(inputs.x, -1, 1);
}
//ROTATE LEFT RIGHT
if (steer)
rotation = Input.GetAxis("Mouse X") * mainCam.CameraSpeed;
else
rotation = Axis(controls.rotateRight.GetControlBinding(), controls.rotateLeft.GetControlBinding());
//ToggleRun
if (controls.walkRun.GetControlBindingDown())
run = !run;
//Jumping
jump = controls.jump.GetControlBinding();
inputNormalized = inputs.normalized;
}
public float Axis(bool pos, bool neg)
{
float axis = 0;
if (pos)
axis += 1;
if (neg)
axis -= 1;
return axis;
}
void DebugGroundNormals()
{
Vector3 lineStart = transform.position + Vector3.up * 0.05f;
if (showMoveDirection)
Debug.DrawLine(lineStart, lineStart + moveDirection.forward, Color.cyan);
if (showForwardDirection)
Debug.DrawLine(lineStart - groundDirection.forward * 0.5f, lineStart + groundDirection.forward * 0.5f, Color.blue);
if (showStrafeDirection)
Debug.DrawLine(lineStart - groundDirection.right * 0.5f, lineStart + groundDirection.right * 0.5f, Color.red);
if (showFallNormal)
Debug.DrawLine(lineStart, lineStart + fallDirection.up * 0.5f, Color.green);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
collisionPoint = hit.point;
collisionPoint = collisionPoint - transform.position;
}
}
| 32.072464 | 175 | 0.616923 | [
"CC0-1.0"
] | Soupertrooper/WoW-Clone | WoWClone_08-5-ProjectFiles/Scripts/Player/PlayerControls.cs | 8,854 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CSG.cache;
namespace CSG.views
{
public partial class CdoPassValidate : Form
{
public IMsgMethod msg { get; set; }
public CdoPassValidate()
{
InitializeComponent();
}
private void BtnOk_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
var rsa = new cryptography.SystemSupportRSA();
Console.WriteLine(rsa.GetMd5Hash(txtPassValidate.Text) + "=" + UserCache.UserPass);
if (rsa.GetMd5Hash(txtPassValidate.Text).Equals(UserCache.UserPass))
{
//Permitimos editar contraseña
msg.txtpassActivator();
}
}
private void BtnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
private void BtnClose_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
protected string PassTranfer()
{
return "";
}
}
}
| 25.96 | 95 | 0.598613 | [
"MIT"
] | cjuanstevan/CSG | CSG/CSG/views/CdoPassValidate.cs | 1,301 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ProjectSystem.Properties;
namespace Microsoft.VisualStudio.ProjectSystem.VS.Properties.InterceptedProjectProperties
{
internal abstract partial class AbstractBuildEventValueProvider : InterceptingPropertyValueProviderBase
{
private readonly IProjectAccessor _projectAccessor;
private readonly UnconfiguredProject _unconfiguredProject;
private readonly AbstractBuildEventHelper _helper;
protected AbstractBuildEventValueProvider(
IProjectAccessor projectAccessor,
UnconfiguredProject project,
AbstractBuildEventHelper helper)
{
_projectAccessor = projectAccessor;
_unconfiguredProject = project;
_helper = helper;
}
public override async Task<string> OnGetEvaluatedPropertyValueAsync(
string evaluatedPropertyValue,
IProjectProperties defaultProperties)
{
(bool success, string property) = await _helper.TryGetPropertyAsync(defaultProperties);
if (success)
{
return property;
}
return await _projectAccessor.OpenProjectXmlForReadAsync(_unconfiguredProject, projectXml => _helper.GetProperty(projectXml));
}
public override async Task<string> OnSetPropertyValueAsync(
string unevaluatedPropertyValue,
IProjectProperties defaultProperties,
IReadOnlyDictionary<string, string> dimensionalConditions = null)
{
if (await _helper.TrySetPropertyAsync(unevaluatedPropertyValue, defaultProperties))
{
return null;
}
await _projectAccessor.OpenProjectXmlForWriteAsync(_unconfiguredProject, projectXml => _helper.SetProperty(unevaluatedPropertyValue, projectXml));
return null;
}
}
}
| 39.388889 | 161 | 0.695346 | [
"Apache-2.0"
] | M-Lipin/project-system | src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/Properties/InterceptedProjectProperties/AbstractBuildEventValueProvider.cs | 2,129 | C# |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Unity.Burst;
using Unity.Jobs;
using Unity.Mathematics;
namespace Unity.Collections.LowLevel.Unsafe
{
/// <summary>
/// An unmanaged, untyped, resizable list, without any thread safety check features.
/// </summary>
[DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}")]
[StructLayout(LayoutKind.Sequential)]
public unsafe struct UnsafeList : IDisposable
{
/// <summary>
/// </summary>
[NativeDisableUnsafePtrRestriction]
public void* Ptr;
/// <summary>
/// </summary>
public int Length;
/// <summary>
/// </summary>
public int Capacity;
/// <summary>
/// </summary>
public AllocatorManager.AllocatorHandle Allocator;
/// <summary>
/// Constructs a new container with type of memory allocation.
/// </summary>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
/// sufficient capacity up front.</remarks>
public unsafe UnsafeList(Allocator allocator)
{
Ptr = null;
Length = 0;
Capacity = 0;
Allocator = allocator;
}
/// <summary>
/// Constructs container as view into memory.
/// </summary>
/// <param name="ptr">Pointer to data.</param>
/// <param name="length">Lenght of data in bytes.</param>
public unsafe UnsafeList(void* ptr, int length)
{
Ptr = ptr;
Length = length;
Capacity = length;
Allocator = Collections.Allocator.None;
}
/// <summary>
/// Constructs a new container with the specified initial capacity and type of memory allocation.
/// </summary>
/// <param name="sizeOf">Size of element.</param>
/// <param name="alignOf">Alignment of element.</param>
/// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
/// the internal array is copied to a new, larger array.</param>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public unsafe UnsafeList(int sizeOf, int alignOf, int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
Allocator = allocator;
Ptr = null;
Length = 0;
Capacity = 0;
if (initialCapacity != 0)
{
SetCapacity(sizeOf, alignOf, initialCapacity);
}
if (options == NativeArrayOptions.ClearMemory
&& Ptr != null)
{
UnsafeUtility.MemClear(Ptr, Capacity * sizeOf);
}
}
/// <summary>
/// Constructs a new container with the specified initial capacity and type of memory allocation.
/// </summary>
/// <param name="sizeOf">Size of element.</param>
/// <param name="alignOf">Alignment of element.</param>
/// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
/// the internal array is copied to a new, larger array.</param>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public unsafe UnsafeList(int sizeOf, int alignOf, int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
Allocator = allocator;
Ptr = null;
Length = 0;
Capacity = 0;
if (initialCapacity != 0)
{
SetCapacity(sizeOf, alignOf, initialCapacity);
}
if (options == NativeArrayOptions.ClearMemory
&& Ptr != null)
{
UnsafeUtility.MemClear(Ptr, Capacity * sizeOf);
}
}
/// <summary>
/// Creates a new container with the specified initial capacity and type of memory allocation.
/// </summary>
/// <param name="sizeOf">Size of element.</param>
/// <param name="alignOf">Alignment of element.</param>
/// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
/// the internal array is copied to a new, larger array.</param>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public static UnsafeList* Create(int sizeOf, int alignOf, int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
var handle = new AllocatorManager.AllocatorHandle {Value = (int)allocator};
UnsafeList* listData = AllocatorManager.Allocate<UnsafeList>(handle);
UnsafeUtility.MemClear(listData, UnsafeUtility.SizeOf<UnsafeList>());
listData->Allocator = allocator;
if (initialCapacity != 0)
{
listData->SetCapacity(sizeOf, alignOf, initialCapacity);
}
if (options == NativeArrayOptions.ClearMemory
&& listData->Ptr != null)
{
UnsafeUtility.MemClear(listData->Ptr, listData->Capacity * sizeOf);
}
return listData;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
internal static void NullCheck(void* listData)
{
if (listData == null)
{
throw new Exception("UnsafeList has yet to be created or has been destroyed!");
}
}
/// <summary>
/// Destroys container.
/// </summary>
public static void Destroy(UnsafeList* listData)
{
NullCheck(listData);
var allocator = listData->Allocator;
listData->Dispose();
AllocatorManager.Free(allocator, listData);
}
/// <summary>
/// Reports whether memory for the container is allocated.
/// </summary>
/// <value>True if this container object's internal storage has been allocated.</value>
/// <remarks>Note that the container storage is not created if you use the default constructor. You must specify
/// at least an allocation type to construct a usable container.</remarks>
public bool IsCreated => Ptr != null;
/// <summary>
/// Disposes of this container and deallocates its memory immediately.
/// </summary>
public void Dispose()
{
if (CollectionHelper.ShouldDeallocate(Allocator))
{
AllocatorManager.Free(Allocator, Ptr);
Allocator = AllocatorManager.Invalid;
}
Ptr = null;
Length = 0;
Capacity = 0;
}
/// <summary>
/// Safely disposes of this container and deallocates its memory when the jobs that use it have completed.
/// </summary>
/// <remarks>You can call this function dispose of the container immediately after scheduling the job. Pass
/// the [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) returned by
/// the [Job.Schedule](https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobExtensions.Schedule.html)
/// method using the `jobHandle` parameter so the job scheduler can dispose the container after all jobs
/// using it have run.</remarks>
/// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
/// <returns>A new job handle containing the prior handles as well as the handle for the job that deletes
/// the container.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
if (CollectionHelper.ShouldDeallocate(Allocator))
{
var jobHandle = new UnsafeDisposeJob { Ptr = Ptr, Allocator = (Allocator)Allocator.Value }.Schedule(inputDeps);
Ptr = null;
Allocator = AllocatorManager.Invalid;
return jobHandle;
}
Ptr = null;
return inputDeps;
}
/// <summary>
/// Clears the container.
/// </summary>
/// <remarks>The container capacity remains unchanged.</remarks>
public void Clear()
{
Length = 0;
}
/// <summary>
/// Changes the list length, resizing if necessary.
/// </summary>
/// <param name="sizeOf">Size of element.</param>
/// <param name="alignOf">Alignment of element.</param>
/// <param name="length">The new length of the list.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public void Resize(int sizeOf, int alignOf, int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
var oldLength = Length;
if (length > Capacity)
{
SetCapacity(sizeOf, alignOf, length);
}
Length = length;
if (options == NativeArrayOptions.ClearMemory
&& oldLength < length)
{
var num = length - oldLength;
byte* ptr = (byte*)Ptr;
UnsafeUtility.MemClear(ptr + oldLength * sizeOf, num * sizeOf);
}
}
/// <summary>
/// Changes the list length, resizing if necessary.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="length">The new length of the list.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public void Resize<T>(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) where T : struct
{
Resize(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), length, options);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
static private void CheckAllocator(Allocator a)
{
if (!CollectionHelper.ShouldDeallocate(a))
{
throw new Exception("UnsafeList is not initialized, it must be initialized with allocator before use.");
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
static private void CheckAllocator(AllocatorManager.AllocatorHandle a)
{
if (!CollectionHelper.ShouldDeallocate(a))
{
throw new Exception("UnsafeList is not initialized, it must be initialized with allocator before use.");
}
}
void Realloc(int sizeOf, int alignOf, int capacity)
{
CheckAllocator(Allocator);
void* newPointer = null;
if (capacity > 0)
{
newPointer = AllocatorManager.Allocate(Allocator, sizeOf, alignOf, capacity);
if (Capacity > 0)
{
var itemsToCopy = math.min(capacity, Capacity);
var bytesToCopy = itemsToCopy * sizeOf;
UnsafeUtility.MemCpy(newPointer, Ptr, bytesToCopy);
}
}
AllocatorManager.Free(Allocator, Ptr);
Ptr = newPointer;
Capacity = capacity;
Length = math.min(Length, capacity);
}
void SetCapacity(int sizeOf, int alignOf, int capacity)
{
var newCapacity = math.max(capacity, 64 / sizeOf);
newCapacity = math.ceilpow2(newCapacity);
if (newCapacity == Capacity)
{
return;
}
Realloc(sizeOf, alignOf, newCapacity);
}
/// <summary>
/// Set the number of items that can fit in the container.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="capacity">The number of items that the container can hold before it resizes its internal storage.</param>
public void SetCapacity<T>(int capacity) where T : struct
{
SetCapacity(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), capacity);
}
/// <summary>
/// Sets the capacity to the actual number of elements in the container.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
public void TrimExcess<T>() where T : struct
{
if (Capacity != Length)
{
Realloc(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), Length);
}
}
/// <summary>
/// Searches for the specified element in list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="value"></param>
/// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
public int IndexOf<T>(T value) where T : struct, IEquatable<T>
{
return NativeArrayExtensions.IndexOf<T, T>(Ptr, Length, value);
}
/// <summary>
/// Determines whether an element is in the list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="value"></param>
/// <returns>True, if element is found.</returns>
public bool Contains<T>(T value) where T : struct, IEquatable<T>
{
return IndexOf(value) != -1;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private void CheckNoResizeHasEnoughCapacity(int length)
{
CheckNoResizeHasEnoughCapacity(length, Length);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private void CheckNoResizeHasEnoughCapacity(int length, int index)
{
if (Capacity < index + length)
{
throw new Exception($"AddNoResize assumes that list capacity is sufficient (Capacity {Capacity}, Length {Length}), requested length {length}!");
}
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="value">The value to be added at the end of the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddNoResize<T>(T value) where T : struct
{
CheckNoResizeHasEnoughCapacity(1);
UnsafeUtility.WriteArrayElement(Ptr, Length, value);
Length += 1;
}
private void AddRangeNoResize(int sizeOf, void* ptr, int length)
{
CheckNoResizeHasEnoughCapacity(length);
void* dst = (byte*)Ptr + Length * sizeOf;
UnsafeUtility.MemCpy(dst, ptr, length * sizeOf);
Length += length;
}
/// <summary>
/// Adds elements from a buffer to this list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="ptr">A pointer to the buffer.</param>
/// <param name="length">The number of elements to add to the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize<T>(void* ptr, int length) where T : struct
{
AddRangeNoResize(UnsafeUtility.SizeOf<T>(), ptr, length);
}
/// <summary>
/// Adds elements from a list to this list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize<T>(UnsafeList list) where T : struct
{
AddRangeNoResize(UnsafeUtility.SizeOf<T>(), list.Ptr, CollectionHelper.AssumePositive(list.Length));
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="value">The value to be added at the end of the list.</param>
/// <remarks>
/// If the list has reached its current capacity, it copies the original, internal array to
/// a new, larger array, and then deallocates the original.
/// </remarks>
public void Add<T>(T value) where T : struct
{
var idx = Length;
if (Length + 1 > Capacity)
{
Resize<T>(idx + 1);
}
else
{
Length += 1;
}
UnsafeUtility.WriteArrayElement(Ptr, idx, value);
}
private void AddRange(int sizeOf, int alignOf, void* ptr, int length)
{
var idx = Length;
if (Length + length > Capacity)
{
Resize(sizeOf, alignOf, Length + length);
}
else
{
Length += length;
}
void* dst = (byte*)Ptr + idx * sizeOf;
UnsafeUtility.MemCpy(dst, ptr, length * sizeOf);
}
/// <summary>
/// Adds elements from a buffer to this list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="ptr">A pointer to the buffer.</param>
/// <param name="length">The number of elements to add to the list.</param>
public void AddRange<T>(void* ptr, int length) where T : struct
{
AddRange(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), ptr, length);
}
/// <summary>
/// Adds elements from a list to this list.
/// </summary>
/// <remarks>
/// If the list has reached its current capacity, it copies the original, internal array to
/// a new, larger array, and then deallocates the original.
/// </remarks>
/// <typeparam name="T">Source type of elements</typeparam>
public void AddRange<T>(UnsafeList list) where T : struct
{
AddRange(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), list.Ptr, list.Length);
}
/// <summary>
/// Truncates the list by replacing the item at the specified index with the last item in the list. The list
/// is shortened by one.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="index">The index of the item to delete.</param>
public void RemoveAtSwapBack<T>(int index) where T : struct
{
RemoveRangeSwapBack<T>(index, index + 1);
}
private void RemoveRangeSwapBack(int sizeOf, int begin, int end)
{
int itemsToRemove = end - begin;
if (itemsToRemove > 0)
{
int copyFrom = math.max(Length - itemsToRemove, end);
void* dst = (byte*)Ptr + begin * sizeOf;
void* src = (byte*)Ptr + copyFrom * sizeOf;
UnsafeUtility.MemCpy(dst, src, math.min(itemsToRemove, Length - copyFrom) * sizeOf);
Length -= itemsToRemove;
}
}
/// <summary>
/// Truncates the list by replacing the item at the specified index range with the items from the end the list. The list
/// is shortened by number of elements in range.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="begin">The first index of the item to delete.</param>
/// <param name="end">The last index of the item to delete.</param>
public void RemoveRangeSwapBack<T>(int begin, int end) where T : struct
{
RemoveRangeSwapBack(UnsafeUtility.SizeOf<T>(), begin, end);
}
/// <summary>
/// Returns parallel reader instance.
/// </summary>
public ParallelReader AsParallelReader()
{
return new ParallelReader(Ptr, Length);
}
/// <summary>
/// Implements parallel reader. Use AsParallelReader to obtain it from container.
/// </summary>
public unsafe struct ParallelReader
{
[NativeDisableUnsafePtrRestriction]
public readonly void* Ptr;
public readonly int Length;
public ParallelReader(void* ptr, int length)
{
Ptr = ptr;
Length = length;
}
public int IndexOf<T>(T value) where T : struct, IEquatable<T>
{
return NativeArrayExtensions.IndexOf<T, T>(Ptr, Length, value);
}
public bool Contains<T>(T value) where T : struct, IEquatable<T>
{
return IndexOf(value) != -1;
}
}
/// <summary>
/// Returns parallel writer instance.
/// </summary>
public ParallelWriter AsParallelWriter()
{
return new ParallelWriter(Ptr, (UnsafeList*)UnsafeUtility.AddressOf(ref this));
}
public unsafe struct ParallelWriter
{
[NativeDisableUnsafePtrRestriction]
public readonly void* Ptr;
[NativeDisableUnsafePtrRestriction]
public UnsafeList* ListData;
public unsafe ParallelWriter(void* ptr, UnsafeList* listData)
{
Ptr = ptr;
ListData = listData;
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="value">The value to be added at the end of the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddNoResize<T>(T value) where T : struct
{
var idx = Interlocked.Increment(ref ListData->Length) - 1;
ListData->CheckNoResizeHasEnoughCapacity(idx, 1);
UnsafeUtility.WriteArrayElement(Ptr, idx, value);
}
private void AddRangeNoResize(int sizeOf, int alignOf, void* ptr, int length)
{
var idx = Interlocked.Add(ref ListData->Length, length) - length;
ListData->CheckNoResizeHasEnoughCapacity(idx, length);
void* dst = (byte*)Ptr + idx * sizeOf;
UnsafeUtility.MemCpy(dst, ptr, length * sizeOf);
}
/// <summary>
/// Adds elements from a buffer to this list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <param name="ptr">A pointer to the buffer.</param>
/// <param name="length">The number of elements to add to the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize<T>(void* ptr, int length) where T : struct
{
AddRangeNoResize(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), ptr, length);
}
/// <summary>
/// Adds elements from a list to this list.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize<T>(UnsafeList list) where T : struct
{
AddRangeNoResize(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), list.Ptr, list.Length);
}
}
}
[BurstCompile]
internal unsafe struct UnsafeDisposeJob : IJob
{
[NativeDisableUnsafePtrRestriction]
public void* Ptr;
public Allocator Allocator;
public void Execute()
{
var handle = new AllocatorManager.AllocatorHandle {Value = (int)Allocator};
AllocatorManager.Free(handle, Ptr);
}
}
/// <summary>
/// An managed, resizable list, without any thread safety check features.
/// </summary>
/// <typeparam name="T">Source type of elements</typeparam>
[DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}")]
[DebuggerTypeProxy(typeof(UnsafeListTDebugView<>))]
[StructLayout(LayoutKind.Sequential)]
public unsafe struct UnsafeList<T> : INativeList<T>, IDisposable
where T : unmanaged
{
[NativeDisableUnsafePtrRestriction]
public T* Ptr;
public int length;
public int capacity;
public AllocatorManager.AllocatorHandle Allocator;
public int Length
{
get { return length; }
set { length = value; }
}
public int Capacity
{
get { return capacity; }
set { capacity = value; }
}
public T this[int index]
{
get { return Ptr[index]; }
set { Ptr[index] = value; }
}
public ref T ElementAt(int index)
{
return ref Ptr[index];
}
/// <summary>
/// Constructs list as view into memory.
/// </summary>
public unsafe UnsafeList(T* ptr, int length)
{
Ptr = ptr;
this.length = length;
capacity = 0;
Allocator = AllocatorManager.None;
}
/// <summary>
/// Constructs a new list using the specified type of memory allocation.
/// </summary>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
/// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
/// sufficient capacity up front.</remarks>
public unsafe UnsafeList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
Ptr = null;
length = 0;
capacity = 0;
Allocator = AllocatorManager.None;
var sizeOf = UnsafeUtility.SizeOf<T>();
var alignOf = UnsafeUtility.AlignOf<T>();
this.ListData() = new UnsafeList(sizeOf, alignOf, initialCapacity, allocator, options);
}
/// <summary>
/// Constructs a new list using the specified type of memory allocation.
/// </summary>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
/// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
/// sufficient capacity up front.</remarks>
public unsafe UnsafeList(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
Ptr = null;
length = 0;
capacity = 0;
Allocator = AllocatorManager.None;
var sizeOf = UnsafeUtility.SizeOf<T>();
var alignOf = UnsafeUtility.AlignOf<T>();
this.ListData() = new UnsafeList(sizeOf, alignOf, initialCapacity, allocator, options);
}
/// <summary>
/// Reports whether memory for the container is allocated.
/// </summary>
/// <value>True if this container object's internal storage has been allocated.</value>
/// <remarks>Note that the container storage is not created if you use the default constructor. You must specify
/// at least an allocation type to construct a usable container.</remarks>
public bool IsCreated => Ptr != null;
/// <summary>
/// Disposes of this container and deallocates its memory immediately.
/// </summary>
public void Dispose()
{
this.ListData().Dispose();
}
/// <summary>
/// Safely disposes of this container and deallocates its memory when the jobs that use it have completed.
/// </summary>
/// <remarks>You can call this function dispose of the container immediately after scheduling the job. Pass
/// the [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) returned by
/// the [Job.Schedule](https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobExtensions.Schedule.html)
/// method using the `jobHandle` parameter so the job scheduler can dispose the container after all jobs
/// using it have run.</remarks>
/// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
/// <returns>A new job handle containing the prior handles as well as the handle for the job that deletes
/// the container.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
return this.ListData().Dispose(inputDeps);
}
/// <summary>
/// Clears the container.
/// </summary>
/// <remarks>List Capacity remains unchanged.</remarks>
public void Clear()
{
this.ListData().Clear();
}
/// <summary>
/// Changes the list length, resizing if necessary.
/// </summary>
/// <param name="length">The new length of the list.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
this.ListData().Resize<T>(length, options);
}
/// <summary>
/// Set the number of items that can fit in the list.
/// </summary>
/// <param name="capacity">The number of items that the list can hold before it resizes its internal storage.</param>
public void SetCapacity(int capacity)
{
this.ListData().SetCapacity<T>(capacity);
}
/// <summary>
/// Sets the capacity to the actual number of elements in the container.
/// </summary>
public void TrimExcess()
{
this.ListData().TrimExcess<T>();
}
/// <summary>
/// Adds an element to the container.
/// </summary>
/// <param name="value">The value to be added at the end of the container.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddNoResize(T value)
{
this.ListData().AddNoResize(value);
}
/// <summary>
/// Adds the elements to this container.
/// </summary>
/// <param name="ptr">A pointer to the buffer.</param>
/// <param name="length">The number of elements to add to the container.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize(void* ptr, int length)
{
this.ListData().AddRangeNoResize<T>(ptr, length);
}
/// <summary>
/// Adds elements from a list to this container.
/// </summary>
/// <param name="list">Other container to copy elements from.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize(UnsafeList<T> list)
{
this.ListData().AddRangeNoResize<T>(list.ListData());
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <param name="value">The struct to be added at the end of the list.</param>
public void Add(T value)
{
this.ListData().Add(value);
}
/// <summary>
/// Adds the elements of a UnsafePtrList to this list.
/// </summary>
/// <param name="list">The items to add.</param>
public void AddRange(UnsafeList<T> src)
{
this.ListData().AddRange<T>(src.ListData());
}
/// <summary>
/// Truncates the list by replacing the item at the specified index with the last item in the list. The list
/// is shortened by one.
/// </summary>
/// <param name="index">The index of the item to delete.</param>
public void RemoveAtSwapBack(int index)
{
this.ListData().RemoveAtSwapBack<T>(index);
}
/// <summary>
/// Returns parallel reader instance.
/// </summary>
public ParallelReader AsParallelReader()
{
return new ParallelReader(Ptr, Length);
}
/// <summary>
/// Implements parallel reader. Use AsParallelReader to obtain it from container.
/// </summary>
public unsafe struct ParallelReader
{
[NativeDisableUnsafePtrRestriction]
public readonly T* Ptr;
public readonly int Length;
internal ParallelReader(T* ptr, int length)
{
Ptr = ptr;
Length = length;
}
}
public ParallelWriter AsParallelWriter()
{
return new ParallelWriter((UnsafeList*)UnsafeUtility.AddressOf(ref this));
}
/// <summary>
/// Returns parallel writer instance.
/// </summary>
public unsafe struct ParallelWriter
{
public UnsafeList.ParallelWriter Writer;
internal unsafe ParallelWriter(UnsafeList* listData)
{
Writer = listData->AsParallelWriter();
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <param name="value">The value to be added at the end of the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddNoResize(T value)
{
Writer.AddNoResize(value);
}
/// <summary>
/// </summary>
/// <param name="ptr"></param>
/// <param name="length"></param>
public void AddRangeNoResize(void* ptr, int length)
{
Writer.AddRangeNoResize<T>(ptr, length);
}
/// <summary>
/// </summary>
/// <param name="list"></param>
public void AddRangeNoResize(UnsafeList<T> list)
{
Writer.AddRangeNoResize<T>(list.ListData());
}
}
}
internal unsafe static class UnsafeListExtensions
{
public static ref UnsafeList ListData<T>(ref this UnsafeList<T> from) where T : unmanaged => ref UnsafeUtilityEx.As<UnsafeList<T>, UnsafeList>(ref from);
/// Type parameter has the same name as the type parameter from outer type
/// <summary>
/// Searches for the specified element in the container.
/// </summary>
/// <param name="value"></param>
/// <typeparam name="T">The type of values in the container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="value">The value to locate.</param>
/// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
public static int IndexOf<T, U>(this UnsafeList<T> list, U value) where T : unmanaged, IEquatable<U>
{
return NativeArrayExtensions.IndexOf<T, U>(list.Ptr, list.Length, value);
}
/// <summary>
/// Determines whether an element is in the container.
/// </summary>
/// <typeparam name="T">The type of values in the container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <returns>True, if element is found.</returns>
public static bool Contains<T, U>(this UnsafeList<T> list, U value) where T : unmanaged, IEquatable<U>
{
return list.IndexOf(value) != -1;
}
/// Type parameter has the same name as the type parameter from outer type
/// <summary>
/// Searches for the specified element in the container.
/// </summary>
/// <param name="value"></param>
/// <typeparam name="T">The type of values in the container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="value">The value to locate.</param>
/// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
public static int IndexOf<T, U>(this UnsafeList<T>.ParallelReader list, U value) where T : unmanaged, IEquatable<U>
{
return NativeArrayExtensions.IndexOf<T, U>(list.Ptr, list.Length, value);
}
/// <summary>
/// Determines whether an element is in the container.
/// </summary>
/// <typeparam name="T">The type of values in the container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <returns>True, if element is found.</returns>
public static bool Contains<T, U>(this UnsafeList<T>.ParallelReader list, U value) where T : unmanaged, IEquatable<U>
{
return list.IndexOf(value) != -1;
}
}
internal sealed class UnsafeListTDebugView<T>
where T : unmanaged
{
UnsafeList<T> Data;
public UnsafeListTDebugView(UnsafeList<T> data)
{
Data = data;
}
public unsafe T[] Items
{
get
{
T[] result = new T[Data.Length];
for (var i = 0; i < result.Length; ++i)
{
result[i] = Data.Ptr[i];
}
return result;
}
}
}
/// <summary>
/// An unmanaged, resizable list, without any thread safety check features.
/// </summary>
[DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}")]
[DebuggerTypeProxy(typeof(UnsafePtrListDebugView))]
public unsafe struct UnsafePtrList : INativeList<IntPtr>, IDisposable
{
[NativeDisableUnsafePtrRestriction]
public readonly void** Ptr;
public readonly int length;
public readonly int capacity;
public readonly AllocatorManager.AllocatorHandle Allocator;
public int Length { get { return length; } set {} }
public int Capacity { get { return capacity; } set {} }
public IntPtr this[int index]
{
get { return new IntPtr(Ptr[index]); }
set { Ptr[index] = (void*)value; }
}
public ref IntPtr ElementAt(int index)
{
return ref ((IntPtr*)Ptr)[index];
}
/// <summary>
/// Constructs list as view into memory.
/// </summary>
public unsafe UnsafePtrList(void** ptr, int length)
{
Ptr = ptr;
this.length = length;
this.capacity = length;
Allocator = AllocatorManager.None;
}
/// <summary>
/// Constructs a new list using the specified type of memory allocation.
/// </summary>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
/// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
/// sufficient capacity up front.</remarks>
public unsafe UnsafePtrList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
Ptr = null;
length = 0;
capacity = 0;
Allocator = AllocatorManager.None;
var sizeOf = IntPtr.Size;
this.ListData() = new UnsafeList(sizeOf, sizeOf, initialCapacity, allocator, options);
}
/// <summary>
/// Constructs a new list using the specified type of memory allocation.
/// </summary>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
/// <remarks>The list initially has a capacity of one. To avoid reallocating memory for the list, specify
/// sufficient capacity up front.</remarks>
public unsafe UnsafePtrList(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
Ptr = null;
length = 0;
capacity = 0;
Allocator = AllocatorManager.None;
var sizeOf = IntPtr.Size;
this.ListData() = new UnsafeList(sizeOf, sizeOf, initialCapacity, allocator, options);
}
/// <summary>
/// </summary>
public static UnsafePtrList* Create(void** ptr, int length)
{
UnsafePtrList* listData = AllocatorManager.Allocate<UnsafePtrList>(AllocatorManager.Persistent);
*listData = new UnsafePtrList(ptr, length);
return listData;
}
/// <summary>
/// Creates a new list with the specified initial capacity and type of memory allocation.
/// </summary>
/// <param name="initialCapacity">The initial capacity of the list. If the list grows larger than its capacity,
/// the internal array is copied to a new, larger array.</param>
/// <param name="allocator">A member of the
/// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public static UnsafePtrList* Create(int initialCapacity, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
UnsafePtrList* listData = AllocatorManager.Allocate<UnsafePtrList>(allocator);
*listData = new UnsafePtrList(initialCapacity, allocator, options);
return listData;
}
/// <summary>
/// Destroys list.
/// </summary>
public static void Destroy(UnsafePtrList* listData)
{
UnsafeList.NullCheck(listData);
var allocator = listData->ListData().Allocator.Value == AllocatorManager.Invalid.Value
? AllocatorManager.Persistent
: listData->ListData().Allocator
;
listData->Dispose();
AllocatorManager.Free(allocator, listData);
}
/// <summary>
/// Reports whether memory for the container is allocated.
/// </summary>
/// <value>True if this container object's internal storage has been allocated.</value>
/// <remarks>Note that the container storage is not created if you use the default constructor. You must specify
/// at least an allocation type to construct a usable container.</remarks>
public bool IsCreated => Ptr != null;
/// <summary>
/// Disposes of this container and deallocates its memory immediately.
/// </summary>
public void Dispose()
{
this.ListData().Dispose();
}
/// <summary>
/// Safely disposes of this container and deallocates its memory when the jobs that use it have completed.
/// </summary>
/// <remarks>You can call this function dispose of the container immediately after scheduling the job. Pass
/// the [JobHandle](https://docs.unity3d.com/ScriptReference/Unity.Jobs.JobHandle.html) returned by
/// the [Job.Schedule](https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobExtensions.Schedule.html)
/// method using the `jobHandle` parameter so the job scheduler can dispose the container after all jobs
/// using it have run.</remarks>
/// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
/// <returns>A new job handle containing the prior handles as well as the handle for the job that deletes
/// the container.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
return this.ListData().Dispose(inputDeps);
}
/// <summary>
/// Clears the list.
/// </summary>
/// <remarks>List Capacity remains unchanged.</remarks>
public void Clear()
{
this.ListData().Clear();
}
/// <summary>
/// Changes the list length, resizing if necessary.
/// </summary>
/// <param name="length">The new length of the list.</param>
/// <param name="options">Memory should be cleared on allocation or left uninitialized.</param>
public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
this.ListData().Resize<IntPtr>(length, options);
}
/// <summary>
/// Set the number of items that can fit in the list.
/// </summary>
/// <param name="capacity">The number of items that the list can hold before it resizes its internal storage.</param>
public void SetCapacity(int capacity)
{
this.ListData().SetCapacity<IntPtr>(capacity);
}
/// <summary>
/// Sets the capacity to the actual number of elements in the container.
/// </summary>
public void TrimExcess()
{
this.ListData().TrimExcess<IntPtr>();
}
/// <summary>
/// Searches for the specified element in list.
/// </summary>
/// <param name="value"></param>
/// <returns>The zero-based index of the first occurrence element if found, otherwise returns -1.</returns>
public int IndexOf(void* value)
{
for (int i = 0; i < Length; ++i)
{
if (Ptr[i] == value) return i;
}
return -1;
}
/// <summary>
/// Determines whether an element is in the list.
/// </summary>
/// <param name="value"></param>
/// <returns>True, if element is found.</returns>
public bool Contains(void* value)
{
return IndexOf(value) != -1;
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <param name="value">The value to be added at the end of the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddNoResize(void* value)
{
this.ListData().AddNoResize((IntPtr)value);
}
/// <summary>
/// Adds elements from a buffer to this list.
/// </summary>
/// <param name="ptr">A pointer to the buffer.</param>
/// <param name="length">The number of elements to add to the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize(void** ptr, int length)
{
this.ListData().AddRangeNoResize<IntPtr>(ptr, length);
}
/// <summary>
/// Adds elements from a list to this list.
/// </summary>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize(UnsafePtrList list)
{
this.ListData().AddRangeNoResize<IntPtr>(list.Ptr, list.Length);
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <param name="value">The struct to be added at the end of the list.</param>
public void Add(void* value)
{
this.ListData().Add((IntPtr)value);
}
/// <summary>
/// Adds the elements of a UnsafePtrList to this list.
/// </summary>
/// <param name="list">The items to add.</param>
public void AddRange(UnsafePtrList list)
{
this.ListData().AddRange<IntPtr>(list.ListData());
}
/// <summary>
/// Truncates the list by replacing the item at the specified index with the last item in the list. The list
/// is shortened by one.
/// </summary>
/// <param name="index">The index of the item to delete.</param>
public void RemoveAtSwapBack(int index)
{
RemoveRangeSwapBack(index, index + 1);
}
/// <summary>
/// Truncates the list by replacing the item at the specified index range with the items from the end the list. The list
/// is shortened by number of elements in range.
/// </summary>
/// <param name="begin">The first index of the item to delete.</param>
/// <param name="end">The last index of the item to delete.</param>
public void RemoveRangeSwapBack(int begin, int end)
{
this.ListData().RemoveRangeSwapBack<IntPtr>(begin, end);
}
/// <summary>
/// Returns parallel reader instance.
/// </summary>
public ParallelReader AsParallelReader()
{
return new ParallelReader(Ptr, Length);
}
/// <summary>
/// Implements parallel reader. Use AsParallelReader to obtain it from container.
/// </summary>
public unsafe struct ParallelReader
{
[NativeDisableUnsafePtrRestriction]
public readonly void** Ptr;
public readonly int Length;
public ParallelReader(void** ptr, int length)
{
Ptr = ptr;
Length = length;
}
public int IndexOf(void* value)
{
for (int i = 0; i < Length; ++i)
{
if (Ptr[i] == value) return i;
}
return -1;
}
public bool Contains(void* value)
{
return IndexOf(value) != -1;
}
}
/// <summary>
/// Returns parallel writer instance.
/// </summary>
public ParallelWriter AsParallelWriter()
{
return new ParallelWriter(Ptr, (UnsafeList*)UnsafeUtility.AddressOf(ref this));
}
public unsafe struct ParallelWriter
{
[NativeDisableUnsafePtrRestriction]
public readonly void* Ptr;
[NativeDisableUnsafePtrRestriction]
public UnsafeList* ListData;
public unsafe ParallelWriter(void* ptr, UnsafeList* listData)
{
Ptr = ptr;
ListData = listData;
}
/// <summary>
/// Adds an element to the list.
/// </summary>
/// <param name="value">The value to be added at the end of the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddNoResize(void* value)
{
ListData->AddNoResize((IntPtr)value);
}
/// <summary>
/// Adds elements from a buffer to this list.
/// </summary>
/// <param name="ptr">A pointer to the buffer.</param>
/// <param name="length">The number of elements to add to the list.</param>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize(void** ptr, int length)
{
ListData->AddRangeNoResize<IntPtr>(ptr, length);
}
/// <summary>
/// Adds elements from a list to this list.
/// </summary>
/// <remarks>
/// If the list has reached its current capacity, internal array won't be resized, and exception will be thrown.
/// </remarks>
public void AddRangeNoResize(UnsafePtrList list)
{
ListData->AddRangeNoResize<IntPtr>(list.Ptr, list.Length);
}
}
}
internal static class UnsafePtrListExtensions
{
public static ref UnsafeList ListData(ref this UnsafePtrList from) => ref UnsafeUtilityEx.As<UnsafePtrList, UnsafeList>(ref from);
}
internal sealed class UnsafePtrListDebugView
{
private UnsafePtrList Data;
public UnsafePtrListDebugView(UnsafePtrList data)
{
Data = data;
}
public unsafe IntPtr[] Items
{
get
{
IntPtr[] result = new IntPtr[Data.Length];
for (var i = 0; i < result.Length; ++i)
{
result[i] = (IntPtr)Data.Ptr[i];
}
return result;
}
}
}
}
| 39.020776 | 191 | 0.57225 | [
"Apache-2.0"
] | bsides44/MARSGeofencing | MARS geofencing/Library/PackageCache/com.unity.collections@0.8.0-preview.5/Unity.Collections/UnsafeList.cs | 56,346 | C# |
namespace Serenity
{
/// <summary>
/// Custom validator abstraction
/// </summary>
public interface ICustomValidator
{
/// <summary>
/// Validates value using specified context.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
string Validate(IValidationContext context);
}
} | 25.0625 | 55 | 0.551122 | [
"MIT"
] | ArsenioInojosa/Serenity | src/Serenity.Net.Data/Validation/ICustomValidator.cs | 403 | C# |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Castle.Core.Interceptor;
using Rhino.Mocks.Constraints;
using System.Reflection;
namespace Rhino.Mocks.Interfaces
{
/*
* Interface: IMethodOptions
*
* Allows to define what would happen when a method is called.
*
*/
/// <summary>
/// Allows to define what would happen when a method
/// is called.
/// </summary>
public interface IMethodOptions<T>
{
/*
* Method: Return
*
* Sets the return value when the method is called.
*/
/// <summary>
/// Set the return value for the method.
/// </summary>
/// <param name="objToReturn">The object the method will return</param>
/// <returns>IRepeat that defines how many times the method will return this value</returns>
IMethodOptions<T> Return(T objToReturn);
/// <summary>
/// Allow to override this return value in the future
/// </summary>
/// <returns>IRepeat that defines how many times the method will return this value</returns>
IMethodOptions<T> TentativeReturn();
/*
* Method: Throw
*
* Throws the specified exception when the method is called.
*/
/// <summary>
/// Throws the specified exception when the method is called.
/// </summary>
/// <param name="exception">Exception to throw</param>
IMethodOptions<T> Throw(Exception exception);
/*
* Method: IgnoreArguments
*
* Ignores the arguments for this method. Any arguments are considered fine for this
* method.
*/
/// <summary>
/// Ignores the arguments for this method. Any argument will be matched
/// againt this method.
/// </summary>
IMethodOptions<T> IgnoreArguments();
/*
* Property: Repeat
*
* Allows to get the <Interfaces.IRepeat> instance that would allow to
* set the expected number of times that this method will occur.
*/
/// <summary>
/// Better syntax to define repeats.
/// </summary>
IRepeat<T> Repeat { get; }
/*
* Method: Constraints
*
* Sets the contraints on this method parameters.
* The number of the constraints *must* be equal to the number of method arguments.
*/
/// <summary>
/// Add constraints for the method's arguments.
/// </summary>
IMethodOptions<T> Constraints(params AbstractConstraint[] constraints);
/*
* Method: Callback
*
* Sets a callback delegate to be called when this method is called.
*
* Important:
* The callback *must* have the same signature as the last method call but its return value
* *must* be a boolean.
* The callback will be called with the same parameters as the method and the method will
* be accepted if the delegate return a positive value.
* Note:
* The callback may be called several times
*
*/
/// <summary>
/// Set a callback method for the last call
/// </summary>
IMethodOptions<T> Callback(Delegate callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback(Delegates.Function<bool> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0>(Delegates.Function<bool, TArg0> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1>(Delegates.Function<bool, TArg0, TArg1> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2>(Delegates.Function<bool, TArg0, TArg1, TArg2> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3, TArg4>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3, TArg4> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3, TArg4, TArg5> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8> callback);
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Callback<TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9>(Delegates.Function<bool, TArg0, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9> callback);
/*
* Method: Do
*
* Set an action to run when the expectation is matched.
*
* Important:
* The action's delegate *must* have the same signature as the last methdo call, and its return
* value must be assignable to the last method call return value.
*
* Note:
* This method is only called once, after the method call was match to the expectation.
*
*
*/
/// <summary>
/// Set a delegate to be called when the expectation is matched.
/// The delegate return value will be returned from the expectation.
/// </summary>
IMethodOptions<T> Do(Delegate action);
/// <summary>
/// Set a delegate to be called when the expectation is matched
/// and allow to optionally modify the invocation as needed
/// </summary>
IMethodOptions<T> WhenCalled(Action<MethodInvocation> action);
/*
* Method: CallOriginalMethod
*
* Call the original method on the class, bypassing the mocking layers.
*
* Important:
* Can only be used on a method that has an implementation.
* If you try that on an interface method or an abstract method, you'll get an
* exception.
*
*/
/// <summary>
/// Call the original method on the class, bypassing the mocking layers.
/// </summary>
/// <returns></returns>
[Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")]
void CallOriginalMethod();
/*
* Method: CallOriginalMethod
*
* Call the original method on the class, optionally bypassing the mocking layers.
*
* Important:
* Can only be used on a method that has an implementation.
* If you try that on an interface method or an abstract method, you'll get an
* exception.
*
*/
/// <summary>
/// Call the original method on the class, optionally bypassing the mocking layers.
/// </summary>
/// <returns></returns>
IMethodOptions<T> CallOriginalMethod(OriginalCallOptions options);
/* Method: PropertyBehavior
*
* Use the property as a normal property, so you can use it to save/load values
* without having to specify expectations for it.
*
* Note:
* This can be called only when the last call is a getter or setter.
*/
/// <summary>
/// Use the property as a simple property, getting/setting the values without
/// causing mock expectations.
/// </summary>
IMethodOptions<T> PropertyBehavior();
/// <summary>
/// Expect last (property) call as property setting, ignore the argument given
/// </summary>
/// <returns></returns>
IMethodOptions<T> SetPropertyAndIgnoreArgument();
/// <summary>
/// Expect last (property) call as property setting with a given argument.
/// </summary>
/// <param name="argument"></param>
/// <returns></returns>
IMethodOptions<T> SetPropertyWithArgument(T argument);
/// <summary>
/// Get an event raiser for the last subscribed event.
/// </summary>
IEventRaiser GetEventRaiser();
/// <summary>
/// Set the parameter values for out and ref parameters.
/// This is done using zero based indexing, and _ignoring_ any non out/ref parameter.
/// </summary>
IMethodOptions<T> OutRef(params object[] parameters);
/// <summary>
/// Documentation message for the expectation
/// </summary>
/// <param name="documentationMessage">Message</param>
IMethodOptions<T> Message(string documentationMessage);
}
}
| 37.335443 | 205 | 0.666808 | [
"BSD-3-Clause"
] | brumschlag/rhino-tools | rhino-mocks/Rhino.Mocks/Interfaces/IMethodOptions.cs | 11,800 | C# |
namespace RabbitRelink.Consumer
{
/// <summary>
/// State of <see cref="IRelinkConsumer"/>
/// </summary>
public enum RelinkConsumerState
{
/// <summary>
/// Initializing
/// </summary>
Init,
/// <summary>
/// Configuring channel and topology
/// </summary>
Configuring,
/// <summary>
/// Reconfiguring channel and topology
/// </summary>
Reconfiguring,
/// <summary>
/// Active
/// </summary>
Active,
/// <summary>
/// Stopping
/// </summary>
Stopping,
/// <summary>
/// Disposed
/// </summary>
Disposed
}
}
| 19.717949 | 47 | 0.427828 | [
"MIT"
] | ijsgaus/rabbit-relink | src/RabbitRelink/Consumer/RelinkConsumerState.cs | 733 | C# |
using System;
using System.Linq.Expressions;
namespace EZNEW.Data.Modification
{
/// <summary>
/// Defines modification factory
/// </summary>
public class ModificationFactory
{
/// <summary>
/// Create an IModification object
/// </summary>
/// <returns>Return a IModification object</returns>
public static IModification Create()
{
return new ModificationInfo();
}
/// <summary>
/// Create an IModification object
/// </summary>
/// <typeparam name="T">Data type</typeparam>
/// <param name="expressions">Expressions</param>
/// <returns>Return a IModification object</returns>
public static IModification Create<T>(params Expression<Func<T, dynamic>>[] expressions)
{
return Create().Set(expressions);
}
}
}
| 27.8125 | 96 | 0.583146 | [
"MIT"
] | eznew-net/EZNEW.Develop | EZNEW/Data/Modification/ModificationFactory.cs | 892 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
{
internal enum Http2SettingsParameter : ushort
{
SETTINGS_HEADER_TABLE_SIZE = 0x1,
SETTINGS_ENABLE_PUSH = 0x2,
SETTINGS_MAX_CONCURRENT_STREAMS = 0x3,
SETTINGS_INITIAL_WINDOW_SIZE = 0x4,
SETTINGS_MAX_FRAME_SIZE = 0x5,
SETTINGS_MAX_HEADER_LIST_SIZE = 0x6,
}
}
| 34.5625 | 111 | 0.725136 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Servers/Kestrel/Core/src/Internal/Http2/Http2SettingsParameter.cs | 553 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.TypeSystem
{
public enum SymbolKind : byte
{
None,
/// <seealso cref="ITypeDefinition"/>
TypeDefinition,
/// <seealso cref="IField"/>
Field,
/// <summary>
/// The symbol is a property, but not an indexer.
/// </summary>
/// <seealso cref="IProperty"/>
Property,
/// <summary>
/// The symbol is an indexer, not a regular property.
/// </summary>
/// <seealso cref="IProperty"/>
Indexer,
/// <seealso cref="IEvent"/>
Event,
/// <summary>
/// The symbol is a method which is not an operator/constructor/destructor or accessor.
/// </summary>
/// <seealso cref="IMethod"/>
Method,
/// <summary>
/// The symbol is a user-defined operator.
/// </summary>
/// <seealso cref="IMethod"/>
Operator,
/// <seealso cref="IMethod"/>
Constructor,
/// <seealso cref="IMethod"/>
Destructor,
/// <summary>
/// The accessor method for a property getter/setter or event add/remove.
/// </summary>
/// <seealso cref="IMethod"/>
Accessor,
/// <seealso cref="INamespace"/>
Namespace,
/// <summary>
/// The symbol is a variable, but not a parameter.
/// </summary>
/// <seealso cref="IVariable"/>
Variable,
/// <seealso cref="IParameter"/>
Parameter,
/// <seealso cref="ITypeParameter"/>
TypeParameter,
}
/// <summary>
/// Interface for type system symbols.
/// </summary>
public interface ISymbol
{
/// <summary>
/// This property returns an enum specifying which kind of symbol this is
/// (which derived interfaces of ISymbol are implemented)
/// </summary>
SymbolKind SymbolKind { get; }
/// <summary>
/// Gets the short name of the symbol.
/// </summary>
string Name { get; }
/// <summary>
/// Creates a symbol reference that can be used to rediscover this symbol in another compilation.
/// </summary>
ISymbolReference ToReference();
}
public interface ISymbolReference
{
ISymbol Resolve(ITypeResolveContext context);
}
}
| 31.079208 | 99 | 0.68748 | [
"MIT"
] | 376730969/ILSpy | NRefactory/ICSharpCode.NRefactory/TypeSystem/ISymbol.cs | 3,141 | C# |
using GardenMarket.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
namespace GardenMarket.Web.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ExternalLoginModel : PageModel
{
private readonly SignInManager<AppUser> _signInManager;
private readonly UserManager<AppUser> _userManager;
private readonly ILogger<ExternalLoginModel> _logger;
public ExternalLoginModel(
SignInManager<AppUser> signInManager,
UserManager<AppUser> userManager,
ILogger<ExternalLoginModel> logger)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public string LoginProvider { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
public IActionResult OnGetAsync()
{
return RedirectToPage("./Login");
}
public IActionResult OnPost(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information.";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
_logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
return LocalRedirect(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToPage("./Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ReturnUrl = returnUrl;
LoginProvider = info.LoginProvider;
if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
{
Input = new InputModel
{
Email = info.Principal.FindFirstValue(ClaimTypes.Email)
};
}
return Page();
}
}
public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information during confirmation.";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
if (ModelState.IsValid)
{
var user = new AppUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
LoginProvider = info.LoginProvider;
ReturnUrl = returnUrl;
return Page();
}
}
} | 38.615942 | 153 | 0.571965 | [
"Apache-2.0"
] | rozabto/GardenMarket | src/Presentation/GardenMarket.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs | 5,331 | C# |
using Microsoft.VisualStudio.Shell;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Task = System.Threading.Tasks.Task;
namespace VSIXProject1 {
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(JanCVSIXPackage.PackageGuidString)]
public sealed class JanCVSIXPackage : AsyncPackage {
/// <summary>
/// VSIXProject1Package GUID string.
/// </summary>
public const string PackageGuidString = "341b5840-c89c-4c29-9ca1-db4a58562ddc";
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
/// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
/// <param name="progress">A provider for progress updates.</param>
/// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) {
// When initialized asynchronously, the current thread may be a background thread at this point.
// Do any initialization that requires the UI thread after switching to the UI thread.
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
}
#endregion
}
}
| 49.627451 | 170 | 0.757013 | [
"MIT"
] | kris701/JanC | JanCVSIX/JanCPackage.cs | 2,533 | C# |
using System;
namespace _03._Rounding_Numbers
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
int input = int.Parse(Console.ReadLine());
numbers[i] = input;
}
for (int i = numbers.Length; i > 0; i--)
{
Console.Write(numbers[i - 1] + " ");
}
double name = double.Parse(Console.ReadLine());
}
}
}
| 21.214286 | 59 | 0.429293 | [
"MIT"
] | Anzzhhela98/CSharp-Fundamentals | Arrays/Arrays - Lab/02. Print Numbers in Reverse Order/Program.cs | 596 | C# |
/*
* Copyright 2014 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
//// TODO:
//// [O] Contracts
//// [O] Documentation
namespace Splunk.Client
{
using System.Runtime.Serialization;
/// <summary>
/// Specifies the page orientation for a report.
/// </summary>
public enum PaperOrientation
{
/// <summary>
/// Height of the display area is less than the width.
/// </summary>
[EnumMember(Value = "landscape")]
Landscape,
/// <summary>
/// Height of the display area is greater than the width.
/// </summary>
[EnumMember(Value = "portrait")]
Portrait
}
}
| 27.790698 | 76 | 0.644351 | [
"Apache-2.0"
] | Balfa/splunk-sdk-csharp-pcl | src/Splunk.Client/Splunk/Client/PaperOrientation.cs | 1,197 | C# |
using System.Reflection;
namespace DIMOWAModLoader.Mod_Loading
{
public struct MOWAP
{
//Mod de Outer Wilds Alpha Padrão
public MethodInfo ModInnitMethod { get; set; }
public int ModLoadingPlace { get; set; }
public int ModPriority { get; set; }
}
}
| 18.6875 | 54 | 0.638796 | [
"MIT"
] | ShoosGun/DIMOWA | DIMOWAModLoader/Mod Loading/MOWAP.cs | 302 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Collections.Generic;
using System.Text;
using Elasticsearch.Net.Utf8Json;
using Elasticsearch.Net.Utf8Json.Resolvers;
namespace Nest
{
internal class QueryContainerFormatter : IJsonFormatter<QueryContainer>
{
private static readonly IJsonFormatter<QueryContainer> QueryFormatter =
DynamicObjectResolver.AllowPrivateExcludeNullCamelCase.GetFormatter<QueryContainer>();
public QueryContainer Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
switch (reader.GetCurrentJsonToken())
{
case JsonToken.BeginObject:
return QueryFormatter.Deserialize(ref reader, formatterResolver);
case JsonToken.String:
var jsonString = reader.ReadStringSegmentUnsafe();
var jsonStringReader = new JsonReader(jsonString.Array, jsonString.Offset);
return QueryFormatter.Deserialize(ref jsonStringReader, formatterResolver);
default:
reader.ReadNextBlock();
return null;
}
}
public void Serialize(ref JsonWriter writer, QueryContainer value, IJsonFormatterResolver formatterResolver)
{
var queryFormatter = formatterResolver.GetFormatter<IQueryContainer>();
queryFormatter.Serialize(ref writer, value, formatterResolver);
}
}
internal class QueryContainerInterfaceFormatter : IJsonFormatter<IQueryContainer>
{
public IQueryContainer Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var queryFormatter = formatterResolver.GetFormatter<QueryContainer>();
return queryFormatter.Deserialize(ref reader, formatterResolver);
}
public void Serialize(ref JsonWriter writer, IQueryContainer value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
var rawQuery = value.RawQuery;
if ((!rawQuery?.Raw.IsNullOrEmpty() ?? false) && rawQuery.IsWritable)
{
writer.WriteRaw(Encoding.UTF8.GetBytes(rawQuery.Raw));
return;
}
var queryFormatter = DynamicObjectResolver.ExcludeNullCamelCase.GetFormatter<IQueryContainer>();
queryFormatter.Serialize(ref writer, value, formatterResolver);
}
}
internal class QueryContainerCollectionFormatter : IJsonFormatter<IEnumerable<QueryContainer>>
{
private static readonly QueryContainerFormatter QueryContainerFormatter =
new QueryContainerFormatter();
private static readonly QueryContainerInterfaceFormatter QueryContainerInterfaceFormatter =
new QueryContainerInterfaceFormatter();
public IEnumerable<QueryContainer> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var token = reader.GetCurrentJsonToken();
switch (token)
{
case JsonToken.BeginArray:
{
var count = 0;
var queryContainers = new List<QueryContainer>();
while (reader.ReadIsInArray(ref count))
queryContainers.Add(QueryContainerFormatter.Deserialize(ref reader, formatterResolver));
return queryContainers;
}
case JsonToken.BeginObject:
{
var queryContainers = new List<QueryContainer>
{
QueryContainerFormatter.Deserialize(ref reader, formatterResolver)
};
return queryContainers;
}
default:
reader.ReadNextBlock();
return null;
}
}
public void Serialize(ref JsonWriter writer, IEnumerable<QueryContainer> value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
writer.WriteNull();
else
{
writer.WriteBeginArray();
var e = value.GetEnumerator();
try
{
var written = false;
while (e.MoveNext())
{
if (e.Current != null && e.Current.IsWritable)
{
if (written)
writer.WriteValueSeparator();
QueryContainerInterfaceFormatter.Serialize(ref writer, e.Current, formatterResolver);
written = true;
}
}
}
finally
{
e.Dispose();
}
writer.WriteEndArray();
}
}
}
}
| 29.446043 | 123 | 0.738578 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | src/Nest/QueryDsl/Abstractions/Container/QueryContainerFormatter.cs | 4,093 | C# |
using QRCoder;
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using System.Drawing;
namespace ClipboardToQR
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
QRCodeGenerator qrGenerator = new QRCodeGenerator();
}
private void nappi_Click(object sender, RoutedEventArgs e)
{
renderQR();
}
private void renderQR()
{
if (Clipboard.GetText(TextDataFormat.UnicodeText).Length <= 1000)
{
try
{
QRCodeGenerator qrGenerator = new QRCodeGenerator();
BitmapImage bi = new BitmapImage();
textBlock.Text = Clipboard.GetText(TextDataFormat.UnicodeText);
QRCodeData qrCodeData = qrGenerator.CreateQrCode(Clipboard.GetText(TextDataFormat.UnicodeText), QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);
ConvertBitmapToBitmapImage T = new ConvertBitmapToBitmapImage();
BitmapImage imageee;
imageee = T.Convert(qrCodeImage);
PngBitmapEncoder BtP = new PngBitmapEncoder();
BtP.Frames.Add(BitmapFrame.Create(imageee));
image.Stretch = Stretch.Uniform;
image.Source = imageee;
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
throw;
}
}
}
// Demonstrates SetText, ContainsText, and GetText.
public String SwapClipboardHtmlText(String replacementHtmlText)
{
String returnHtmlText = null;
if (Clipboard.ContainsText(TextDataFormat.Html))
{
returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
return returnHtmlText;
}
private void image_GotFocus(object sender, RoutedEventArgs e)
{
}
private void Window_Activated(object sender, EventArgs e)
{
if (autogen_checkBox.IsChecked == true)
{
renderQR();
}
}
private void Window_Deactivated(object sender, EventArgs e)
{
if (alwaysontop_checkBox.IsChecked == true)
{
Window window = (Window)sender;
window.Topmost = true;
}
}
private void alwaysontop_checkBox_Checked(object sender, RoutedEventArgs e)
{
this.Topmost = true;
}
private void alwaysontop_checkBox_Unchecked(object sender, RoutedEventArgs e)
{
this.Topmost = false;
}
}
public class ConvertBitmapToBitmapImage
{
/// <summary>
/// Takes a bitmap and converts it to an image that can be handled by WPF ImageBrush
/// </summary>
/// <param name="src">A bitmap image</param>
/// <returns>The image as a BitmapImage for WPF</returns>
public BitmapImage Convert(Bitmap src)
{
MemoryStream ms = new MemoryStream();
((System.Drawing.Bitmap)src).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage image = new BitmapImage();
image.BeginInit();
ms.Seek(0, SeekOrigin.Begin);
image.StreamSource = ms;
image.EndInit();
return image;
}
}
}
| 31.585366 | 144 | 0.551609 | [
"MIT"
] | AnttiJanhonen/Clipboard-to-qr-code | ClipboardToQR/MainWindow.xaml.cs | 3,887 | 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.StorageSync.V20190601
{
public static class GetSyncGroup
{
public static Task<GetSyncGroupResult> InvokeAsync(GetSyncGroupArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetSyncGroupResult>("azure-nextgen:storagesync/v20190601:getSyncGroup", args ?? new GetSyncGroupArgs(), options.WithVersion());
}
public sealed class GetSyncGroupArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the resource group. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// Name of Storage Sync Service resource.
/// </summary>
[Input("storageSyncServiceName", required: true)]
public string StorageSyncServiceName { get; set; } = null!;
/// <summary>
/// Name of Sync Group resource.
/// </summary>
[Input("syncGroupName", required: true)]
public string SyncGroupName { get; set; } = null!;
public GetSyncGroupArgs()
{
}
}
[OutputType]
public sealed class GetSyncGroupResult
{
/// <summary>
/// The name of the resource
/// </summary>
public readonly string Name;
/// <summary>
/// Sync group status
/// </summary>
public readonly string SyncGroupStatus;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
public readonly string Type;
/// <summary>
/// Unique Id
/// </summary>
public readonly string UniqueId;
[OutputConstructor]
private GetSyncGroupResult(
string name,
string syncGroupStatus,
string type,
string uniqueId)
{
Name = name;
SyncGroupStatus = syncGroupStatus;
Type = type;
UniqueId = uniqueId;
}
}
}
| 29.743902 | 181 | 0.601066 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/StorageSync/V20190601/GetSyncGroup.cs | 2,439 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
namespace Amazon.PowerShell.Cmdlets.CFN
{
/// <summary>
/// Creates a stack as specified in the template. After the call completes successfully,
/// the stack creation starts. You can check the status of the stack via the <a>DescribeStacks</a>
/// API.
/// </summary>
[Cmdlet("New", "CFNStack", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("System.String")]
[AWSCmdlet("Calls the AWS CloudFormation CreateStack API operation.", Operation = new[] {"CreateStack"}, SelectReturnType = typeof(Amazon.CloudFormation.Model.CreateStackResponse))]
[AWSCmdletOutput("System.String or Amazon.CloudFormation.Model.CreateStackResponse",
"This cmdlet returns a System.String object.",
"The service call response (type Amazon.CloudFormation.Model.CreateStackResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class NewCFNStackCmdlet : AmazonCloudFormationClientCmdlet, IExecutor
{
#region Parameter Capability
/// <summary>
/// <para>
/// <para>In some cases, you must explicity acknowledge that your stack template contains certain
/// capabilities in order for AWS CloudFormation to create the stack.</para><ul><li><para><code>CAPABILITY_IAM</code> and <code>CAPABILITY_NAMED_IAM</code></para><para>Some stack templates might include resources that can affect permissions in your AWS
/// account; for example, by creating new AWS Identity and Access Management (IAM) users.
/// For those stacks, you must explicitly acknowledge this by specifying one of these
/// capabilities.</para><para>The following IAM resources require you to specify either the <code>CAPABILITY_IAM</code>
/// or <code>CAPABILITY_NAMED_IAM</code> capability.</para><ul><li><para>If you have IAM resources, you can specify either capability. </para></li><li><para>If you have IAM resources with custom names, you <i>must</i> specify <code>CAPABILITY_NAMED_IAM</code>.
/// </para></li><li><para>If you don't specify either of these capabilities, AWS CloudFormation returns an <code>InsufficientCapabilities</code>
/// error.</para></li></ul><para>If your stack template contains these resources, we recommend that you review all
/// permissions associated with them and edit their permissions if necessary.</para><ul><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html">
/// AWS::IAM::AccessKey</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html">
/// AWS::IAM::Group</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html">
/// AWS::IAM::InstanceProfile</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html">
/// AWS::IAM::Policy</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html">
/// AWS::IAM::Role</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html">
/// AWS::IAM::User</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html">
/// AWS::IAM::UserToGroupAddition</a></para></li></ul><para>For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging
/// IAM Resources in AWS CloudFormation Templates</a>.</para></li><li><para><code>CAPABILITY_AUTO_EXPAND</code></para><para>Some template contain macros. Macros perform custom processing on templates; this
/// can include simple actions like find-and-replace operations, all the way to extensive
/// transformations of entire templates. Because of this, users typically create a change
/// set from the processed template, so that they can review the changes resulting from
/// the macros before actually creating the stack. If your stack template contains one
/// or more macros, and you choose to create a stack directly from the processed template,
/// without first reviewing the resulting changes in a change set, you must acknowledge
/// this capability. This includes the <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html">AWS::Include</a>
/// and <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html">AWS::Serverless</a>
/// transforms, which are macros hosted by AWS CloudFormation.</para><para>Change sets do not currently support nested stacks. If you want to create a stack
/// from a stack template that contains macros <i>and</i> nested stacks, you must create
/// the stack directly from the template using this capability.</para><important><para>You should only create stacks directly from a stack template that contains macros
/// if you know what processing the macro performs.</para><para>Each macro relies on an underlying Lambda service function for processing stack templates.
/// Be aware that the Lambda function owner can update the function operation without
/// AWS CloudFormation being notified.</para></important><para>For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html">Using
/// AWS CloudFormation Macros to Perform Custom Processing on Templates</a>.</para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Capabilities")]
public System.String[] Capability { get; set; }
#endregion
#region Parameter ClientRequestToken
/// <summary>
/// <para>
/// <para>A unique identifier for this <code>CreateStack</code> request. Specify this token
/// if you plan to retry requests so that AWS CloudFormation knows that you're not attempting
/// to create a stack with the same name. You might retry <code>CreateStack</code> requests
/// to ensure that AWS CloudFormation successfully received them.</para><para>All events triggered by a given stack operation are assigned the same client request
/// token, which you can use to track operations. For example, if you execute a <code>CreateStack</code>
/// operation with the token <code>token1</code>, then all the <code>StackEvents</code>
/// generated by that operation will have <code>ClientRequestToken</code> set as <code>token1</code>.</para><para>In the console, stack operations display the client request token on the Events tab.
/// Stack operations that are initiated from the console use the token format <i>Console-StackOperation-ID</i>,
/// which helps you easily identify the stack operation . For example, if you create a
/// stack using the console, each stack event would be assigned the same token in the
/// following format: <code>Console-CreateStack-7f59c3cf-00d2-40c7-b2ff-e75db0987002</code>.
/// </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String ClientRequestToken { get; set; }
#endregion
#region Parameter DisableRollback
/// <summary>
/// <para>
/// <para>Set to <code>true</code> to disable rollback of the stack if stack creation failed.
/// You can specify either <code>DisableRollback</code> or <code>OnFailure</code>, but
/// not both.</para><para>Default: <code>false</code></para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Boolean? DisableRollback { get; set; }
#endregion
#region Parameter EnableTerminationProtection
/// <summary>
/// <para>
/// <para>Whether to enable termination protection on the specified stack. If a user attempts
/// to delete a stack with termination protection enabled, the operation fails and the
/// stack remains unchanged. For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html">Protecting
/// a Stack From Being Deleted</a> in the <i>AWS CloudFormation User Guide</i>. Termination
/// protection is disabled on stacks by default. </para><para> For <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html">nested
/// stacks</a>, termination protection is set on the root stack and cannot be changed
/// directly on the nested stack.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Boolean? EnableTerminationProtection { get; set; }
#endregion
#region Parameter RollbackConfiguration_MonitoringTimeInMinute
/// <summary>
/// <para>
/// <para>The amount of time, in minutes, during which CloudFormation should monitor all the
/// rollback triggers after the stack creation or update operation deploys all necessary
/// resources.</para><para>The default is 0 minutes.</para><para>If you specify a monitoring period but do not specify any rollback triggers, CloudFormation
/// still waits the specified period of time before cleaning up old resources after update
/// operations. You can use this monitoring period to perform any manual stack validation
/// desired, and manually cancel the stack creation or update (using <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CancelUpdateStack.html">CancelUpdateStack</a>,
/// for example) as necessary.</para><para>If you specify 0 for this parameter, CloudFormation still monitors the specified rollback
/// triggers during stack creation and update operations. Then, for update operations,
/// it begins disposing of old resources immediately once the operation completes.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("RollbackConfiguration_MonitoringTimeInMinutes")]
public System.Int32? RollbackConfiguration_MonitoringTimeInMinute { get; set; }
#endregion
#region Parameter NotificationARNs
/// <summary>
/// <para>
/// <para>The Simple Notification Service (SNS) topic ARNs to publish stack related events.
/// You can find your SNS topic ARNs using the SNS console or your Command Line Interface
/// (CLI).</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String[] NotificationARNs { get; set; }
#endregion
#region Parameter OnFailure
/// <summary>
/// <para>
/// <para>Determines what action will be taken if stack creation fails. This must be one of:
/// DO_NOTHING, ROLLBACK, or DELETE. You can specify either <code>OnFailure</code> or
/// <code>DisableRollback</code>, but not both.</para><para>Default: <code>ROLLBACK</code></para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.CloudFormation.OnFailure")]
public Amazon.CloudFormation.OnFailure OnFailure { get; set; }
#endregion
#region Parameter Parameter
/// <summary>
/// <para>
/// <para>A list of <code>Parameter</code> structures that specify input parameters for the
/// stack. For more information, see the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Parameter.html">Parameter</a>
/// data type.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Parameters")]
public Amazon.CloudFormation.Model.Parameter[] Parameter { get; set; }
#endregion
#region Parameter ResourceType
/// <summary>
/// <para>
/// <para>The template resource types that you have permissions to work with for this create
/// stack action, such as <code>AWS::EC2::Instance</code>, <code>AWS::EC2::*</code>, or
/// <code>Custom::MyCustomInstance</code>. Use the following syntax to describe template
/// resource types: <code>AWS::*</code> (for all AWS resource), <code>Custom::*</code>
/// (for all custom resources), <code>Custom::<i>logical_ID</i></code> (for a specific
/// custom resource), <code>AWS::<i>service_name</i>::*</code> (for all resources of a
/// particular AWS service), and <code>AWS::<i>service_name</i>::<i>resource_logical_ID</i></code> (for a specific AWS resource).</para><para>If the list of resource types doesn't include a resource that you're creating, the
/// stack creation fails. By default, AWS CloudFormation grants permissions to all resource
/// types. AWS Identity and Access Management (IAM) uses this parameter for AWS CloudFormation-specific
/// condition keys in IAM policies. For more information, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html">Controlling
/// Access with AWS Identity and Access Management</a>.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ResourceTypes")]
public System.String[] ResourceType { get; set; }
#endregion
#region Parameter RoleARN
/// <summary>
/// <para>
/// <para>The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role
/// that AWS CloudFormation assumes to create the stack. AWS CloudFormation uses the role's
/// credentials to make calls on your behalf. AWS CloudFormation always uses this role
/// for all future operations on the stack. As long as users have permission to operate
/// on the stack, AWS CloudFormation uses this role even if the users don't have permission
/// to pass it. Ensure that the role grants least privilege.</para><para>If you don't specify a value, AWS CloudFormation uses the role that was previously
/// associated with the stack. If no role is available, AWS CloudFormation uses a temporary
/// session that is generated from your user credentials.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String RoleARN { get; set; }
#endregion
#region Parameter RollbackConfiguration_RollbackTrigger
/// <summary>
/// <para>
/// <para>The triggers to monitor during stack creation or update actions. </para><para>By default, AWS CloudFormation saves the rollback triggers specified for a stack and
/// applies them to any subsequent update operations for the stack, unless you specify
/// otherwise. If you do specify rollback triggers for this parameter, those triggers
/// replace any list of triggers previously specified for the stack. This means:</para><ul><li><para>To use the rollback triggers previously specified for this stack, if any, don't specify
/// this parameter.</para></li><li><para>To specify new or updated rollback triggers, you must specify <i>all</i> the triggers
/// that you want used for this stack, even triggers you've specifed before (for example,
/// when creating the stack or during a previous stack update). Any triggers that you
/// don't include in the updated list of triggers are no longer applied to the stack.</para></li><li><para>To remove all currently specified triggers, specify an empty list for this parameter.</para></li></ul><para>If a specified trigger is missing, the entire stack operation fails and is rolled
/// back. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("RollbackConfiguration_RollbackTriggers")]
public Amazon.CloudFormation.Model.RollbackTrigger[] RollbackConfiguration_RollbackTrigger { get; set; }
#endregion
#region Parameter StackName
/// <summary>
/// <para>
/// <para>The name that is associated with the stack. The name must be unique in the region
/// in which you are creating the stack.</para><note><para>A stack name can contain only alphanumeric characters (case sensitive) and hyphens.
/// It must start with an alphabetic character and cannot be longer than 128 characters.</para></note>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String StackName { get; set; }
#endregion
#region Parameter StackPolicyBody
/// <summary>
/// <para>
/// <para>Structure containing the stack policy body. For more information, go to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html">
/// Prevent Updates to Stack Resources</a> in the <i>AWS CloudFormation User Guide</i>.
/// You can specify either the <code>StackPolicyBody</code> or the <code>StackPolicyURL</code>
/// parameter, but not both.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String StackPolicyBody { get; set; }
#endregion
#region Parameter StackPolicyURL
/// <summary>
/// <para>
/// <para>Location of a file containing the stack policy. The URL must point to a policy (maximum
/// size: 16 KB) located in an S3 bucket in the same region as the stack. You can specify
/// either the <code>StackPolicyBody</code> or the <code>StackPolicyURL</code> parameter,
/// but not both.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String StackPolicyURL { get; set; }
#endregion
#region Parameter Tag
/// <summary>
/// <para>
/// <para>Key-value pairs to associate with this stack. AWS CloudFormation also propagates these
/// tags to the resources created in the stack. A maximum number of 50 tags can be specified.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Tags")]
public Amazon.CloudFormation.Model.Tag[] Tag { get; set; }
#endregion
#region Parameter TemplateBody
/// <summary>
/// <para>
/// <para>Structure containing the template body with a minimum length of 1 byte and a maximum
/// length of 51,200 bytes. For more information, go to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template
/// Anatomy</a> in the AWS CloudFormation User Guide.</para><para>Conditional: You must specify either the <code>TemplateBody</code> or the <code>TemplateURL</code>
/// parameter, but not both.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String TemplateBody { get; set; }
#endregion
#region Parameter TemplateURL
/// <summary>
/// <para>
/// <para>Location of file containing the template body. The URL must point to a template (max
/// size: 460,800 bytes) that is located in an Amazon S3 bucket. For more information,
/// go to the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template
/// Anatomy</a> in the AWS CloudFormation User Guide.</para><para>Conditional: You must specify either the <code>TemplateBody</code> or the <code>TemplateURL</code>
/// parameter, but not both.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String TemplateURL { get; set; }
#endregion
#region Parameter TimeoutInMinutes
/// <summary>
/// <para>
/// <para>The amount of time that can pass before the stack status becomes CREATE_FAILED; if
/// <code>DisableRollback</code> is not set or is set to <code>false</code>, the stack
/// will be rolled back.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Int32? TimeoutInMinutes { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'StackId'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CloudFormation.Model.CreateStackResponse).
/// Specifying the name of a property of type Amazon.CloudFormation.Model.CreateStackResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "StackId";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the StackName parameter.
/// The -PassThru parameter is deprecated, use -Select '^StackName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^StackName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.StackName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-CFNStack (CreateStack)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.CloudFormation.Model.CreateStackResponse, NewCFNStackCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.StackName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (this.Capability != null)
{
context.Capability = new List<System.String>(this.Capability);
}
context.ClientRequestToken = this.ClientRequestToken;
context.DisableRollback = this.DisableRollback;
context.EnableTerminationProtection = this.EnableTerminationProtection;
if (this.NotificationARNs != null)
{
context.NotificationARNs = new List<System.String>(this.NotificationARNs);
}
context.OnFailure = this.OnFailure;
if (this.Parameter != null)
{
context.Parameter = new List<Amazon.CloudFormation.Model.Parameter>(this.Parameter);
}
if (this.ResourceType != null)
{
context.ResourceType = new List<System.String>(this.ResourceType);
}
context.RoleARN = this.RoleARN;
context.RollbackConfiguration_MonitoringTimeInMinute = this.RollbackConfiguration_MonitoringTimeInMinute;
if (this.RollbackConfiguration_RollbackTrigger != null)
{
context.RollbackConfiguration_RollbackTrigger = new List<Amazon.CloudFormation.Model.RollbackTrigger>(this.RollbackConfiguration_RollbackTrigger);
}
context.StackName = this.StackName;
#if MODULAR
if (this.StackName == null && ParameterWasBound(nameof(this.StackName)))
{
WriteWarning("You are passing $null as a value for parameter StackName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.StackPolicyBody = this.StackPolicyBody;
context.StackPolicyURL = this.StackPolicyURL;
if (this.Tag != null)
{
context.Tag = new List<Amazon.CloudFormation.Model.Tag>(this.Tag);
}
context.TemplateBody = this.TemplateBody;
context.TemplateURL = this.TemplateURL;
context.TimeoutInMinutes = this.TimeoutInMinutes;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.CloudFormation.Model.CreateStackRequest();
if (cmdletContext.Capability != null)
{
request.Capabilities = cmdletContext.Capability;
}
if (cmdletContext.ClientRequestToken != null)
{
request.ClientRequestToken = cmdletContext.ClientRequestToken;
}
if (cmdletContext.DisableRollback != null)
{
request.DisableRollback = cmdletContext.DisableRollback.Value;
}
if (cmdletContext.EnableTerminationProtection != null)
{
request.EnableTerminationProtection = cmdletContext.EnableTerminationProtection.Value;
}
if (cmdletContext.NotificationARNs != null)
{
request.NotificationARNs = cmdletContext.NotificationARNs;
}
if (cmdletContext.OnFailure != null)
{
request.OnFailure = cmdletContext.OnFailure;
}
if (cmdletContext.Parameter != null)
{
request.Parameters = cmdletContext.Parameter;
}
if (cmdletContext.ResourceType != null)
{
request.ResourceTypes = cmdletContext.ResourceType;
}
if (cmdletContext.RoleARN != null)
{
request.RoleARN = cmdletContext.RoleARN;
}
// populate RollbackConfiguration
var requestRollbackConfigurationIsNull = true;
request.RollbackConfiguration = new Amazon.CloudFormation.Model.RollbackConfiguration();
System.Int32? requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute = null;
if (cmdletContext.RollbackConfiguration_MonitoringTimeInMinute != null)
{
requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute = cmdletContext.RollbackConfiguration_MonitoringTimeInMinute.Value;
}
if (requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute != null)
{
request.RollbackConfiguration.MonitoringTimeInMinutes = requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute.Value;
requestRollbackConfigurationIsNull = false;
}
List<Amazon.CloudFormation.Model.RollbackTrigger> requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger = null;
if (cmdletContext.RollbackConfiguration_RollbackTrigger != null)
{
requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger = cmdletContext.RollbackConfiguration_RollbackTrigger;
}
if (requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger != null)
{
request.RollbackConfiguration.RollbackTriggers = requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger;
requestRollbackConfigurationIsNull = false;
}
// determine if request.RollbackConfiguration should be set to null
if (requestRollbackConfigurationIsNull)
{
request.RollbackConfiguration = null;
}
if (cmdletContext.StackName != null)
{
request.StackName = cmdletContext.StackName;
}
if (cmdletContext.StackPolicyBody != null)
{
request.StackPolicyBody = cmdletContext.StackPolicyBody;
}
if (cmdletContext.StackPolicyURL != null)
{
request.StackPolicyURL = cmdletContext.StackPolicyURL;
}
if (cmdletContext.Tag != null)
{
request.Tags = cmdletContext.Tag;
}
if (cmdletContext.TemplateBody != null)
{
request.TemplateBody = cmdletContext.TemplateBody;
}
if (cmdletContext.TemplateURL != null)
{
request.TemplateURL = cmdletContext.TemplateURL;
}
if (cmdletContext.TimeoutInMinutes != null)
{
request.TimeoutInMinutes = cmdletContext.TimeoutInMinutes.Value;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.CloudFormation.Model.CreateStackResponse CallAWSServiceOperation(IAmazonCloudFormation client, Amazon.CloudFormation.Model.CreateStackRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS CloudFormation", "CreateStack");
try
{
#if DESKTOP
return client.CreateStack(request);
#elif CORECLR
return client.CreateStackAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public List<System.String> Capability { get; set; }
public System.String ClientRequestToken { get; set; }
public System.Boolean? DisableRollback { get; set; }
public System.Boolean? EnableTerminationProtection { get; set; }
public List<System.String> NotificationARNs { get; set; }
public Amazon.CloudFormation.OnFailure OnFailure { get; set; }
public List<Amazon.CloudFormation.Model.Parameter> Parameter { get; set; }
public List<System.String> ResourceType { get; set; }
public System.String RoleARN { get; set; }
public System.Int32? RollbackConfiguration_MonitoringTimeInMinute { get; set; }
public List<Amazon.CloudFormation.Model.RollbackTrigger> RollbackConfiguration_RollbackTrigger { get; set; }
public System.String StackName { get; set; }
public System.String StackPolicyBody { get; set; }
public System.String StackPolicyURL { get; set; }
public List<Amazon.CloudFormation.Model.Tag> Tag { get; set; }
public System.String TemplateBody { get; set; }
public System.String TemplateURL { get; set; }
public System.Int32? TimeoutInMinutes { get; set; }
public System.Func<Amazon.CloudFormation.Model.CreateStackResponse, NewCFNStackCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.StackId;
}
}
}
| 58.174184 | 304 | 0.646661 | [
"Apache-2.0"
] | alexandair/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/CloudFormation/Basic/New-CFNStack-Cmdlet.cs | 37,406 | C# |
// <auto-generated />
using System;
using AdminArea_IdentityBase.Models.Services.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace AdminArea_IdentityBase.Migrations
{
[DbContext(typeof(AdminAreaDbContext))]
partial class AdminAreaDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.8");
modelBuilder.Entity("AdminArea_IdentityBase.Models.Entities.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("FullName")
.HasColumnType("TEXT");
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.HasColumnType("TEXT");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("SecurityStamp")
.HasColumnType("TEXT");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.HasColumnType("TEXT");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("AdminArea_IdentityBase.Models.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("AdminArea_IdentityBase.Models.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AdminArea_IdentityBase.Models.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("AdminArea_IdentityBase.Models.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.860294 | 95 | 0.45284 | [
"MIT"
] | AngeloDotNet/AdminArea-IdentityBase | Migrations/AdminAreaDbContextModelSnapshot.cs | 9,756 | C# |
using System;
using UnityEngine.Networking;
namespace ET
{
public class UnityWebRequestUpdateSystem : UpdateSystem<UnityWebRequestAsync>
{
public override void Update(UnityWebRequestAsync self)
{
self.Update();
}
}
public class UnityWebRequestAsync : Entity
{
public class AcceptAllCertificate: CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
return true;
}
}
public static AcceptAllCertificate certificateHandler = new AcceptAllCertificate();
public UnityWebRequest Request;
public bool isCancel;
public ETTaskCompletionSource tcs;
public override void Dispose()
{
if (this.IsDisposed)
{
return;
}
base.Dispose();
this.Request?.Dispose();
this.Request = null;
this.isCancel = false;
}
public float Progress
{
get
{
if (this.Request == null)
{
return 0;
}
return this.Request.downloadProgress;
}
}
public ulong ByteDownloaded
{
get
{
if (this.Request == null)
{
return 0;
}
return this.Request.downloadedBytes;
}
}
public void Update()
{
if (this.isCancel)
{
this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
return;
}
if (!this.Request.isDone)
{
return;
}
if (!string.IsNullOrEmpty(this.Request.error))
{
this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
return;
}
this.tcs.SetResult();
}
public async ETTask DownloadAsync(string url)
{
this.tcs = new ETTaskCompletionSource();
url = url.Replace(" ", "%20");
this.Request = UnityWebRequest.Get(url);
this.Request.certificateHandler = certificateHandler;
this.Request.SendWebRequest();
await this.tcs.Task;
}
}
}
| 17.361905 | 85 | 0.656061 | [
"MIT"
] | AnotherEnd15/ET_NetcodeDemo | Unity/Assets/Model/Module/UnityWebRequest/UnityWebRequestAsync.cs | 1,825 | C# |
using Stride.Core;
using Stride.Editor.Design.Core;
using Virtual = Stride.Editor.Presentation.VirtualDom.Controls;
namespace Stride.Editor.Presentation.Core
{
public class LoadingStatusView : ViewBase<LoadingStatus>
{
public LoadingStatusView(IServiceRegistry services) : base(services)
{
}
public override IViewBuilder CreateView(LoadingStatus viewModel)
{
var bar = new Virtual.ProgressBar
{
IsIndeterminate = viewModel.Mode == LoadingStatus.LoadingMode.Indeterminate,
Minimum = 0,
Maximum = 100,
Value = viewModel.PercentCompleted,
};
var container = new Virtual.ContentControl
{
Width = 100, // TODO: this might need to be configurable if LoadingStatus is to be reused outside of the status bar
Margin = new Avalonia.Thickness(4),
Content = bar,
};
var message = new Virtual.TextBlock
{
Text = viewModel.Message,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
};
return new Virtual.StackPanel
{
Orientation = Avalonia.Layout.Orientation.Horizontal,
Children = new IViewBuilder[]
{
container,
message,
}
};
}
}
}
| 33.044444 | 131 | 0.548083 | [
"MIT"
] | manio143/StrideComponentsEditorAvalonia | Stride.Editor.Presentation/Core/LoadingStatusView.cs | 1,489 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Security;
using Merchello.Core;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Examine.Providers;
namespace Merchello.Examine.DataServices
{
public class OrderDataService : IOrderDataService
{
private readonly IMerchelloContext _merchelloContext;
[SecuritySafeCritical]
public OrderDataService()
: this(MerchelloContext.Current)
{ }
public OrderDataService(IMerchelloContext merchelloContext)
{
_merchelloContext = merchelloContext;
}
public IEnumerable<IOrder> GetAll()
{
return new OrderService().GetAll();
}
public IEnumerable<string> GetIndexFieldNames()
{
return OrderIndexer.IndexFieldPolicies.Select(x => x.Name);
}
}
} | 23.552632 | 71 | 0.66257 | [
"MIT"
] | bowserm/Merchello | src/Merchello.Examine/DataServices/OrderDataService.cs | 897 | C# |
using System.IO;
using System.IO.Compression;
namespace Ccf.Ck.Libs.AutoUpdater.Models
{
internal static class ZipHelper
{
internal static void Unzip(Stream zippedStream, string targetDir)
{
DirectoryInfo targetDirInfo = new DirectoryInfo(targetDir);
if (targetDirInfo.Exists)
{
DeleteRecursive(targetDirInfo);
}
using (ZipArchive archive = new ZipArchive(zippedStream))
{
archive.ExtractToDirectory(targetDir);
}
}
private static void DeleteRecursive(DirectoryInfo targetDirInfo)
{
DirectoryInfo[] subDirs = targetDirInfo.GetDirectories();
FileInfo[] files = targetDirInfo.GetFiles();
for (int i = 0; i < files.Length; i++)
{
files[i].Delete();
}
for (int i = 0; i < subDirs.Length; i++)
{
DeleteRecursive(subDirs[i]);
subDirs[i].Delete();
}
}
}
}
| 29.945946 | 74 | 0.513538 | [
"MIT"
] | Cleancodefactory/NetCoreAutoUpdater | src/Ccf.Ck.Libs.AutoUpdater/Models/ZipHelper.cs | 1,110 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.